Passed
Pull Request — develop (#22)
by Adam
01:58
created

ModelHydrator   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 42
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 19
dl 0
loc 42
rs 10
c 0
b 0
f 0
wmc 5

1 Method

Rating   Name   Duplication   Size   Complexity  
A hydrate() 0 29 5
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