Completed
Push — master ( b3f24e...84a5c5 )
by Tobias
03:15
created

ModelHydrator::deserialize()   B

Complexity

Conditions 5
Paths 4

Size

Total Lines 21
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 30

Importance

Changes 0
Metric Value
dl 0
loc 21
ccs 0
cts 13
cp 0
rs 8.7624
c 0
b 0
f 0
cc 5
eloc 13
nc 4
nop 2
crap 30
1
<?php
2
3
/*
4
 * Copyright (C) 2013-2016 Mailgun
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 Mailgun\Hydrator;
11
12
use Mailgun\Exception\DeserializeException;
13
use Mailgun\Model\ApiResponse;
14
use Psr\Http\Message\ResponseInterface;
15
16
/**
17
 * Serialize an HTTP response to domain object.
18
 *
19
 * @author Tobias Nyholm <[email protected]>
20
 */
21
class ModelHydrator implements Hydrator
22
{
23
    /**
24
     * @param ResponseInterface $response
25
     * @param string            $class
26
     *
27
     * @return ResponseInterface
28
     */
29
    public function deserialize(ResponseInterface $response, $class)
30
    {
31
        $body = $response->getBody()->__toString();
32
        $contentType = $response->getHeaderLine('Content-Type');
33
        if (strpos($contentType, 'application/json') !== 0 && strpos($contentType, 'application/octet-stream') !== 0) {
34
            throw new DeserializeException('The ModelHydrator cannot hydrate response with Content-Type: '.$contentType);
35
        }
36
37
        $data = json_decode($body, true);
38
        if (JSON_ERROR_NONE !== json_last_error()) {
39
            throw new DeserializeException(sprintf('Error (%d) when trying to json_decode response', json_last_error()));
40
        }
41
42
        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...
43
            $object = call_user_func($class.'::create', $data);
44
        } else {
45
            $object = new $class($data);
46
        }
47
48
        return $object;
49
    }
50
}
51