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

ModelTransformer   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 38
Duplicated Lines 21.05 %

Coupling/Cohesion

Components 0
Dependencies 3

Importance

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

1 Method

Rating   Name   Duplication   Size   Complexity  
B transform() 8 32 4

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

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 View Code Duplication
        if (0 !== \strpos($response->getHeaderLine('Content-Type'), 'application/json')) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
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::class)) {
50
            $object = \call_user_func($class.'::fromArray', $data);
51
        } else {
52
            $object = new $class($data);
53
        }
54
55
        return $object;
56
    }
57
}
58