Completed
Push — master ( d8ae00...12ed8a )
by Tobias
02:18
created

ModelHydrator::hydrate()   A

Complexity

Conditions 5
Paths 4

Size

Total Lines 23

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 5.5069

Importance

Changes 0
Metric Value
dl 0
loc 23
ccs 8
cts 11
cp 0.7272
rs 9.2408
c 0
b 0
f 0
cc 5
nc 4
nop 2
crap 5.5069
1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * Copyright (C) 2013 Mailgun
7
 *
8
 * This software may be modified and distributed under the terms
9
 * of the MIT license. See the LICENSE file for details.
10
 */
11
12
namespace Mailgun\Hydrator;
13
14
use Mailgun\Exception\HydrationException;
15
use Mailgun\Model\ApiResponse;
16
use Psr\Http\Message\ResponseInterface;
17
18
/**
19
 * Serialize an HTTP response to domain object.
20
 *
21
 * @author Tobias Nyholm <[email protected]>
22
 */
23
final class ModelHydrator implements Hydrator
24
{
25
    /**
26
     * @return ResponseInterface
27
     */
28 10
    public function hydrate(ResponseInterface $response, string $class)
29
    {
30 10
        $body = $response->getBody()->__toString();
31 10
        $contentType = $response->getHeaderLine('Content-Type');
32
33 10
        if (0 !== strpos($contentType, 'application/json') && 0 !== strpos($contentType, 'application/octet-stream')) {
34
            throw new HydrationException('The ModelHydrator cannot hydrate response with Content-Type: '.$contentType);
35
        }
36
37 10
        $data = json_decode($body, true);
38
39 10
        if (JSON_ERROR_NONE !== json_last_error()) {
40
            throw new HydrationException(sprintf('Error (%d) when trying to json_decode response', json_last_error()));
41
        }
42
43
        if (is_subclass_of($class, ApiResponse::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 \Mailgun\Model\ApiResponse::class can be an interface. If so, you could instead use ReflectionClass::implementsInterface.
Loading history...
44 10
            $object = call_user_func($class.'::create', $data);
45
        } else {
46
            $object = new $class($data);
47
        }
48
49 10
        return $object;
50
    }
51
}
52