1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace IBM\Watson\Common\Hydrator; |
6
|
|
|
|
7
|
|
|
use IBM\Watson\Common\Exception\HydrationException; |
8
|
|
|
use IBM\Watson\Common\Model\CreatableFromArray; |
9
|
|
|
use Psr\Http\Message\ResponseInterface; |
10
|
|
|
use ReflectionClass; |
11
|
|
|
|
12
|
|
|
/** |
13
|
|
|
* ModelHydrator will hydrate a ResponseInterface into a model. |
14
|
|
|
*/ |
15
|
|
|
class ModelHydrator extends AbstractHydrator |
16
|
|
|
{ |
17
|
|
|
const METHOD_CREATE = '::create'; |
18
|
|
|
|
19
|
|
|
/** |
20
|
|
|
* @param \Psr\Http\Message\ResponseInterface $response Response to hydrate. |
21
|
|
|
* @param string|null $class Class for hydration. |
22
|
|
|
* |
23
|
|
|
* @return \IBM\Watson\Common\Model\CreatableFromArray |
24
|
|
|
* |
25
|
|
|
* @throws \ReflectionException |
26
|
|
|
* @throws \IBM\Watson\Common\Exception\HydrationException |
27
|
|
|
*/ |
28
|
|
|
public function hydrate(ResponseInterface $response, string $class = null) |
29
|
|
|
{ |
30
|
|
|
if (null === $class) { |
31
|
|
|
throw new HydrationException('The ModelHydrator requires a model class as the second parameter.'); |
32
|
|
|
} |
33
|
|
|
|
34
|
|
|
if (!$this->isJsonResponse($response)) { |
35
|
|
|
$message = 'The ModelHydrator cannot hydrate a response with Content-Type: '; |
36
|
|
|
|
37
|
|
|
throw new HydrationException($message.$response->getHeaderLine('Content-Type')); |
38
|
|
|
} |
39
|
|
|
|
40
|
|
|
$body = $this->getBodyContent($response); |
41
|
|
|
if (JSON_ERROR_NONE !== \json_last_error()) { |
42
|
|
|
throw new HydrationException(sprintf( |
43
|
|
|
'Error (%d) when trying to json_decode response: %s', |
44
|
|
|
\json_last_error(), |
45
|
|
|
\json_last_error_msg() |
46
|
|
|
)); |
47
|
|
|
} |
48
|
|
|
|
49
|
|
|
$reflection = new ReflectionClass($class); |
50
|
|
|
if ($reflection->implementsInterface(CreatableFromArray::class)) { |
51
|
|
|
$model = \call_user_func($class.self::METHOD_CREATE, $body); |
52
|
|
|
} else { |
53
|
|
|
$model = new $class($body); |
54
|
|
|
} |
55
|
|
|
|
56
|
|
|
return $model; |
57
|
|
|
} |
58
|
|
|
} |
59
|
|
|
|