Completed
Push — master ( c13142...c0435c )
by Tobias
02:34
created

ModelHydrator::hydrate()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 18
Code Lines 12

Duplication

Lines 3
Ratio 16.67 %

Code Coverage

Tests 8
CRAP Score 4.3244

Importance

Changes 0
Metric Value
dl 3
loc 18
ccs 8
cts 11
cp 0.7272
rs 9.2
c 0
b 0
f 0
cc 4
eloc 12
nc 4
nop 2
crap 4.3244
1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * This software may be modified and distributed under the terms
7
 * of the MIT license. See the LICENSE file for details.
8
 */
9
10
namespace Billogram\Hydrator;
11
12
use Billogram\Exception\HydrationException;
13
use Billogram\Model\CreatableFromArray;
14
use Psr\Http\Message\ResponseInterface;
15
16
/**
17
 * Hydrate an HTTP response to domain object.
18
 *
19
 * @author Tobias Nyholm <[email protected]>
20
 */
21
final class ModelHydrator implements Hydrator
22
{
23
    /**
24
     * @param ResponseInterface $response
25
     * @param string            $class
26
     *
27
     * @return mixed
28
     */
29 13
    public function hydrate(ResponseInterface $response, string $class)
30
    {
31 13
        $body = $response->getBody()->__toString();
32 13 View Code Duplication
        if (strpos($response->getHeaderLine('Content-Type'), 'application/json') !== 0) {
0 ignored issues
show
Duplication introduced by Ibrahimhizeoui
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...
33
            throw new HydrationException('The ModelHydrator cannot hydrate response with Content-Type:'.$response->getHeaderLine('Content-Type'));
34
        }
35 13
        $data = json_decode($body, true);
36 13
        if (JSON_ERROR_NONE !== json_last_error()) {
37
            throw new HydrationException(sprintf('Error (%d) when trying to json_decode response', json_last_error()));
38
        }
39 13
        if (is_subclass_of($class, CreatableFromArray::class)) {
0 ignored issues
show
Bug introduced by Ibrahimhizeoui
Due to PHP Bug #53727, is_subclass_of might return inconsistent results on some PHP versions if \Billogram\Model\CreatableFromArray::class can be an interface. If so, you could instead use ReflectionClass::implementsInterface.
Loading history...
40 13
            $object = call_user_func($class.'::createFromArray', $data);
41
        } else {
42
            $object = new $class($data);
43
        }
44
45 13
        return $object;
46
    }
47
}
48