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

ModelHydrator   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 29
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 3

Test Coverage

Coverage 72.72%

Importance

Changes 0
Metric Value
wmc 5
lcom 0
cbo 3
dl 0
loc 29
ccs 8
cts 11
cp 0.7272
rs 10
c 0
b 0
f 0

1 Method

Rating   Name   Duplication   Size   Complexity  
A hydrate() 0 23 5
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