Completed
Pull Request — develop (#5)
by Adam
01:26
created

ModelHydrator::hydrate()   B

Complexity

Conditions 5
Paths 5

Size

Total Lines 28
Code Lines 17

Duplication

Lines 4
Ratio 14.29 %

Importance

Changes 0
Metric Value
dl 4
loc 28
rs 8.439
c 0
b 0
f 0
cc 5
eloc 17
nc 5
nop 2
1
<?php
2
3
namespace IBM\Watson\Common\Hydrator;
4
5
use IBM\Watson\Common\Exception\HydrationException;
6
use IBM\Watson\Common\Model\ApiResponse;
7
use Psr\Http\Message\ResponseInterface;
8
9
final class ModelHydrator implements HydratorInterface
10
{
11
    /**
12
     * Hydrate API response
13
     *
14
     * @param \Psr\Http\Message\ResponseInterface $response
15
     * @param string|null                         $class
16
     *
17
     * @return mixed
18
     *
19
     * @throws \IBM\Watson\Common\Exception\HydrationException
20
     */
21
    public function hydrate(ResponseInterface $response, $class = null)
22
    {
23
        if (null === $class) {
24
            throw new HydrationException('The ModelHydrator requires a model class as the second parameter');
25
        }
26
27
        $body = $response->getBody()->__toString();
28 View Code Duplication
        if (\strpos($response->getHeaderLine('Content-Type'), 'application/json') !== 0) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
29
            $message = 'The ModelHydrator cannot hydrate response with Content-Type: ';
30
            throw new HydrationException($message . $response->getHeaderLine('Content-Type'));
31
        }
32
33
        $data = \json_decode($body, true);
34
        if (\JSON_ERROR_NONE !== \json_last_error()) {
35
            throw new HydrationException(\sprintf(
36
                'Error (%d) when trying to json_decode response',
37
                \json_last_error()
38
            ));
39
        }
40
41
        if (\is_subclass_of($class, ApiResponse::class)) {
42
            $model = \call_user_func($class.'::create', $data);
43
        } else {
44
            $model = new $class($data);
45
        }
46
47
        return $model;
48
    }
49
}
50