Completed
Push — sdk ( 5a9985...c7ab5a )
by Aymen
07:04
created

ModelTransformer   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 37
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 3

Importance

Changes 0
Metric Value
dl 0
loc 37
c 0
b 0
f 0
wmc 4
lcom 0
cbo 3
rs 10

1 Method

Rating   Name   Duplication   Size   Complexity  
B transform() 0 31 4
1
<?php
2
/**
3
 * This file is part of the fnayou/instapush-php project.
4
 *
5
 * Copyright (c) 2017. Aymen FNAYOU <[email protected]>
6
 *
7
 * For the full copyright and license information, please view the LICENSE
8
 * file that was distributed with this source code.
9
 */
10
11
namespace Fnayou\InstapushPHP\Transformer;
12
13
use Fnayou\InstapushPHP\Exception\TransformerException;
14
use Fnayou\InstapushPHP\Model\FromArrayInterface;
15
use Psr\Http\Message\ResponseInterface;
16
17
/**
18
 * Class ModelTransformer.
19
 */
20
class ModelTransformer implements TransformerInterface
21
{
22
    /**
23
     * {@inheritdoc}
24
     */
25
    public function transform(ResponseInterface $response, string $class)
26
    {
27
        if (0 !== \strpos($response->getHeaderLine('Content-Type'), 'application/json')) {
28
            throw new TransformerException(
29
                \sprintf(
30
                    'The ModelTransformer can transform json response but %s given',
31
                    $response->getHeaderLine('Content-Type')
32
                )
33
            );
34
        }
35
36
        $body = $response->getBody()->__toString();
37
        $data = \json_decode($body, true);
38
39
        if (JSON_ERROR_NONE !== \json_last_error()) {
40
            throw new TransformerException(
41
                \sprintf(
42
                    'Invalid json response format : Error %d when trying to \json_decode response',
43
                    \json_last_error()
44
                )
45
            );
46
        }
47
48
        if (\is_subclass_of($class, FromArrayInterface::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 \Fnayou\InstapushPHP\Mod...omArrayInterface::class can be an interface. If so, you could instead use ReflectionClass::implementsInterface.
Loading history...
49
            $object = \call_user_func($class.'::createFromArray', $data);
50
        } else {
51
            $object = new $class($data);
52
        }
53
54
        return $object;
55
    }
56
}
57