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

ModelHydrator::hydrate()   A

Complexity

Conditions 5
Paths 5

Size

Total Lines 28
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Importance

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