ModelHydrator::hydrate()   B
last analyzed

Complexity

Conditions 4
Paths 4

Size

Total Lines 23
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 13
CRAP Score 4

Importance

Changes 0
Metric Value
dl 0
loc 23
ccs 13
cts 13
cp 1
rs 8.7972
c 0
b 0
f 0
cc 4
eloc 14
nc 4
nop 1
crap 4
1
<?php
2
3
declare(strict_types = 1);
4
5
namespace AdamPaterson\ApiClient\Foundation\Hydrator;
6
7
use AdamPaterson\ApiClient\Foundation\Contract\HydratorInterface as Hydrator;
8
use AdamPaterson\ApiClient\Foundation\Contract\CreatableFromArray;
9
use AdamPaterson\ApiClient\Foundation\Exception\HydrationException;
10
use Psr\Http\Message\ResponseInterface;
11
12
/**
13
 * Class ModelHydrator
14
 *
15
 * @package AdamPaterson\ApiClient\Foundation\Hydrator
16
 */
17
final class ModelHydrator implements Hydrator
18
{
19
    /**
20
     * @var $class string Class to create with response data
21
     */
22
    private $class;
23
24
    /**
25
     * ModelHydrator constructor.
26
     *
27
     * @param $class
28
     */
29 12
    public function __construct($class)
30
    {
31 12
        $this->class = $class;
32 12
    }
33
34
    /**
35
     * Hydrate ResponseInterface into class/model
36
     *
37
     * @param \Psr\Http\Message\ResponseInterface $response
38
     *
39
     * @return mixed
40
     */
41 12
    public function hydrate(ResponseInterface $response)
42
    {
43 12
        $body = $response->getBody()->__toString();
44 12
        $contentType = $response->getHeaderLine('Content-Type');
45 12
        if (strpos($contentType, 'application/json') !== 0) {
46 3
            throw new HydrationException('The ModelHydrator cannot hydrate response with Content-Type:'.$contentType);
47
        }
48
49 9
        $data = json_decode($body, true);
50 9
        if (JSON_ERROR_NONE !== json_last_error()) {
51 3
            throw new HydrationException(
52 3
                sprintf('Error (%d) when trying to json_decode response', json_last_error())
53
            );
54
        }
55
56 6
        if (is_subclass_of($this->class, CreatableFromArray::class)) {
57 3
            $object = forward_static_call([$this->class, 'createFromArray'], $data);
58
        } else {
59 3
            $object = new $this->class($data);
60
        }
61
62 6
        return $object;
63
    }
64
}
65