ModelHydrator   A
last analyzed

Complexity

Total Complexity 4

Size/Duplication

Total Lines 36
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 14
dl 0
loc 36
rs 10
c 0
b 0
f 0
wmc 4

1 Method

Rating   Name   Duplication   Size   Complexity  
A hydrate() 0 22 4
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
     * @throws \IBM\Watson\Common\Exception\JsonException
28
     */
29
    public function hydrate(ResponseInterface $response, string $class = null)
30
    {
31
        if (null === $class) {
32
            throw new HydrationException('The ModelHydrator requires a model class as the second parameter.');
33
        }
34
35
        if (!$this->isJsonResponse($response)) {
36
            $message = 'The ModelHydrator cannot hydrate a response with Content-Type: ';
37
38
            throw new HydrationException($message.$response->getHeaderLine('Content-Type'));
39
        }
40
41
        $body = $this->getBodyContent($response);
42
43
        $reflection = new ReflectionClass($class);
44
        if ($reflection->implementsInterface(CreatableFromArray::class)) {
45
            $model = \call_user_func($class.self::METHOD_CREATE, $body);
46
        } else {
47
            $model = new $class($body);
48
        }
49
50
        return $model;
51
    }
52
}
53