ModelTransformer::transform()   A
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 23
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 23
rs 9.0856
c 0
b 0
f 0
cc 3
eloc 14
nc 3
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
        $body = $response->getBody()->__toString();
28
        $data = \json_decode($body, true);
29
30
        if (JSON_ERROR_NONE !== \json_last_error()) {
31
            throw new TransformerException(
32
                \sprintf(
33
                    'Invalid json response format : Error %d when trying to \json_decode response',
34
                    \json_last_error()
35
                )
36
            );
37
        }
38
39
        $reflection = new \ReflectionClass($class);
40
        if (true === $reflection->implementsInterface(FromArrayInterface::class)) {
41
            $object = \call_user_func($class.'::fromArray', $data);
42
        } else {
43
            $object = new $class($data);
44
        }
45
46
        return $object;
47
    }
48
}
49