-
Notifications
You must be signed in to change notification settings - Fork 319
/
Copy pathArrayHydrator.php
43 lines (36 loc) · 1.17 KB
/
ArrayHydrator.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
<?php
declare(strict_types=1);
/*
* Copyright (C) 2013 Mailgun
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
namespace Mailgun\Hydrator;
use Mailgun\Exception\HydrationException;
use Psr\Http\Message\ResponseInterface;
/**
* Serialize an HTTP response to array.
*
* @author Tobias Nyholm <[email protected]>
*/
final class ArrayHydrator implements Hydrator
{
/**
* @param class-string $class
*
* @throws HydrationException
*/
public function hydrate(ResponseInterface $response, string $class): array
{
$body = $response->getBody()->__toString();
if (0 !== strpos($response->getHeaderLine('Content-Type'), 'application/json')) {
throw new HydrationException('The ArrayHydrator cannot hydrate response with Content-Type:'.$response->getHeaderLine('Content-Type'));
}
$content = json_decode($body, true);
if (JSON_ERROR_NONE !== json_last_error()) {
throw new HydrationException(sprintf('Error (%d) when trying to json_decode response', json_last_error()));
}
return $content;
}
}