Passed
Pull Request — develop (#22)
by Adam
01:46 queued 30s
created

ModelHydrator::hydrate()   A

Complexity

Conditions 5
Paths 5

Size

Total Lines 29
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 5
eloc 17
nc 5
nop 2
dl 0
loc 29
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
     *
24
     * @throws \ReflectionException
25
     * @throws \BadMethodCallException
26
     */
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
    }
57
}
58