ModelHydrator::hydrate()   A
last analyzed

Complexity

Conditions 4
Paths 4

Size

Total Lines 19
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 20

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 4
eloc 11
c 1
b 0
f 0
nc 4
nop 2
dl 0
loc 19
ccs 0
cts 16
cp 0
crap 20
rs 9.9
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 FAPI\Localise\Hydrator;
11
12
use FAPI\Localise\Exception\HydrationException;
13
use FAPI\Localise\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
    public function hydrate(ResponseInterface $response, string $class)
30
    {
31
        $body = $response->getBody()->__toString();
32
        if (0 !== strpos($response->getHeaderLine('Content-Type'), 'application/json')) {
33
            throw new HydrationException('The ModelHydrator cannot hydrate response with Content-Type:'.$response->getHeaderLine('Content-Type'));
34
        }
35
36
        $data = json_decode($body, true);
37
        if (JSON_ERROR_NONE !== json_last_error()) {
38
            throw new HydrationException(sprintf('Error (%d) when trying to json_decode response', json_last_error()));
39
        }
40
41
        if (is_subclass_of($class, CreatableFromArray::class)) {
42
            $object = call_user_func($class.'::createFromArray', $data);
43
        } else {
44
            $object = new $class($data);
45
        }
46
47
        return $object;
48
    }
49
}
50