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

src/Hydrator/ModelHydrator.php (1 issue)

reflection_usage.could_be_subclass_problem

Bug Minor

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

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) {
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
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