Completed
Push — develop ( 68a985...a1f82e )
by Adam
10s
created

ModelHydrator::hydrate()   B

Complexity

Conditions 5
Paths 5

Size

Total Lines 28
Code Lines 17

Duplication

Lines 4
Ratio 14.29 %

Code Coverage

Tests 18
CRAP Score 5

Importance

Changes 0
Metric Value
dl 4
loc 28
ccs 18
cts 18
cp 1
rs 8.439
c 0
b 0
f 0
cc 5
eloc 17
nc 5
nop 2
crap 5
1
<?php
2
3
namespace IBM\Watson\Common\Hydrator;
4
5
use IBM\Watson\Common\Exception\HydrationException;
6
use IBM\Watson\Common\Model\ApiResponseInterface;
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 18
    public function hydrate(ResponseInterface $response, $class = null)
22
    {
23 18
        if (null === $class) {
24 3
            throw new HydrationException('The ModelHydrator requires a model class as the second parameter');
25
        }
26
27 15
        $body = $response->getBody()->__toString();
28 15 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 3
            $message = 'The ModelHydrator cannot hydrate response with Content-Type: ';
30 3
            throw new HydrationException($message . $response->getHeaderLine('Content-Type'));
31
        }
32
33 12
        $data = \json_decode($body, true);
34 12
        if (\JSON_ERROR_NONE !== \json_last_error()) {
35 3
            throw new HydrationException(\sprintf(
36 3
                'Error (%d) when trying to json_decode response',
37 3
                \json_last_error()
38 2
            ));
39
        }
40
41 9
        if (\is_subclass_of($class, ApiResponseInterface::class)) {
0 ignored issues
show
Bug introduced by
Due to PHP Bug #53727, is_subclass_of might return inconsistent results on some PHP versions if \IBM\Watson\Common\Model...esponseInterface::class can be an interface. If so, you could instead use ReflectionClass::implementsInterface.
Loading history...
42 6
            $model = \call_user_func($class.'::create', $data);
43 4
        } else {
44 3
            $model = new $class($data);
45
        }
46
47 9
        return $model;
48
    }
49
}
50