These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more
1 | <?php |
||
2 | |||
3 | /* |
||
4 | * Copyright (C) 2013 Mailgun |
||
5 | * |
||
6 | * This software may be modified and distributed under the terms |
||
7 | * of the MIT license. See the LICENSE file for details. |
||
8 | */ |
||
9 | |||
10 | namespace Mailgun\Hydrator; |
||
11 | |||
12 | use Mailgun\Exception\HydrationException; |
||
13 | use Mailgun\Model\ApiResponse; |
||
14 | use Psr\Http\Message\ResponseInterface; |
||
15 | |||
16 | /** |
||
17 | * Serialize an HTTP response to domain object. |
||
18 | * |
||
19 | * @author Tobias Nyholm <[email protected]> |
||
20 | */ |
||
21 | final class ModelHydrator implements Hydrator |
||
22 | { |
||
23 | /** |
||
24 | * @param ResponseInterface $response |
||
25 | * @param string $class |
||
26 | * |
||
27 | * @return ResponseInterface |
||
28 | */ |
||
29 | 19 | public function hydrate(ResponseInterface $response, $class) |
|
30 | { |
||
31 | 19 | $body = $response->getBody()->__toString(); |
|
32 | 19 | $contentType = $response->getHeaderLine('Content-Type'); |
|
33 | 19 | if (0 !== strpos($contentType, 'application/json') && 0 !== strpos($contentType, 'application/octet-stream')) { |
|
34 | throw new HydrationException('The ModelHydrator cannot hydrate response with Content-Type: '.$contentType); |
||
35 | } |
||
36 | |||
37 | 19 | $data = json_decode($body, true); |
|
38 | 19 | if (JSON_ERROR_NONE !== json_last_error()) { |
|
39 | 1 | throw new HydrationException(sprintf('Error (%d) when trying to json_decode response', json_last_error())); |
|
40 | 1 | } |
|
41 | |||
42 | 19 | if (is_subclass_of($class, ApiResponse::class)) { |
|
0 ignored issues
–
show
Bug
introduced
by
Loading history...
|
|||
43 | 19 | $object = call_user_func($class.'::create', $data); |
|
44 | 19 | } else { |
|
45 | $object = new $class($data); |
||
46 | } |
||
47 | |||
48 | 19 | return $object; |
|
49 | } |
||
50 | } |
||
51 |