Completed
Pull Request — master (#3)
by Aymen
02:03
created

ModelTransformer   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 38
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 3

Importance

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

1 Method

Rating   Name   Duplication   Size   Complexity  
B transform() 0 32 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 Fnayou\InstapushPHP\Transformer\TransformerInterface;
16
use Psr\Http\Message\ResponseInterface;
17
18
/**
19
 * Class ModelTransformer.
20
 */
21
class ModelTransformer implements TransformerInterface
22
{
23
    /**
24
     * {@inheritdoc}
25
     */
26
    public function transform(ResponseInterface $response, string $class)
27
    {
28
        if (0 !== \strpos($response->getHeaderLine('Content-Type'), 'application/json')) {
29
            throw new TransformerException(
30
                \sprintf(
31
                    'The ModelTransformer can transform json response but %s given',
32
                    $response->getHeaderLine('Content-Type')
33
                )
34
            );
35
        }
36
37
        $body = $response->getBody()->__toString();
38
        $data = \json_decode($body, true);
39
40
        if (JSON_ERROR_NONE !== \json_last_error()) {
41
            throw new TransformerException(
42
                \sprintf(
43
                    'Invalid json response format : Error %d when trying to \json_decode response',
44
                    \json_last_error()
45
                )
46
            );
47
        }
48
49
        $reflection = new \ReflectionClass($class);
50
        if (true == $reflection->implementsInterface('FromArrayInterface')) {
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like you are loosely comparing two booleans. Considering using the strict comparison === instead.

When comparing two booleans, it is generally considered safer to use the strict comparison operator.

Loading history...
51
            $object = \call_user_func($class.'::fromArray', $data);
52
        } else {
53
            $object = new $class($data);
54
        }
55
56
        return $object;
57
    }
58
}
59