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

ModelTransformer::transform()   B

Complexity

Conditions 4
Paths 4

Size

Total Lines 32
Code Lines 19

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 32
rs 8.5806
c 0
b 0
f 0
cc 4
eloc 19
nc 4
nop 2
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
        $reflection = new \ReflectionClass($class);
49
        if (true === $reflection->implementsInterface('FromArrayInterface')) {
50
            $object = \call_user_func($class.'::fromArray', $data);
51
        } else {
52
            $object = new $class($data);
53
        }
54
55
        return $object;
56
    }
57
}
58