Conditions | 5 |
Paths | 5 |
Total Lines | 29 |
Code Lines | 17 |
Lines | 0 |
Ratio | 0 % |
Changes | 0 |
1 | <?php |
||
27 | public function hydrate(ResponseInterface $response, string $class = null) |
||
28 | { |
||
29 | if (null === $class) { |
||
30 | throw new \BadMethodCallException('The ModelHydrator requires a model class as the second parameter.'); |
||
31 | } |
||
32 | |||
33 | if (!$this->isJsonResponse($response)) { |
||
34 | $message = 'The ModelHydrator cannot hydrate a response with Content-Type: '; |
||
35 | |||
36 | throw new \BadMethodCallException($message.$response->getHeaderLine('Content-Type')); |
||
37 | } |
||
38 | |||
39 | $body = $this->getBodyContent($response); |
||
40 | if (JSON_ERROR_NONE !== \json_last_error()) { |
||
41 | throw new \BadMethodCallException(sprintf( |
||
42 | 'Error (%d) when trying to json_decode response: %s', |
||
43 | \json_last_error(), |
||
44 | \json_last_error_msg() |
||
45 | )); |
||
46 | } |
||
47 | |||
48 | $reflection = new ReflectionClass($class); |
||
49 | if ($reflection->implementsInterface(CreatableFromArray::class)) { |
||
50 | $model = \call_user_func($class.self::METHOD_CREATE, $body); |
||
51 | } else { |
||
52 | $model = new $class($body); |
||
53 | } |
||
54 | |||
55 | return $model; |
||
56 | } |
||
58 |