Completed
Push — master ( e11229...90bc38 )
by Gilmar
23:15
created

Manager   A

Complexity

Total Complexity 11

Size/Duplication

Total Lines 121
Duplicated Lines 24.79 %

Coupling/Cohesion

Components 2
Dependencies 5

Importance

Changes 18
Bugs 1 Features 0
Metric Value
wmc 11
c 18
b 1
f 0
lcom 2
cbo 5
dl 30
loc 121
rs 10

7 Methods

Rating   Name   Duplication   Size   Complexity  
A setUp() 0 4 1
A getDetail() 0 18 1
A findById() 17 17 2
A getPriceScheduleCollection() 13 13 2
A saveDetail() 0 7 1
A hydrate() 0 9 1
B update() 0 33 3

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
/*
4
 * This file is part of gpupo/netshoes-sdk
5
 * Created by Gilmar Pupo <[email protected]>
6
 * For the information of copyright and license you should read the file
7
 * LICENSE which is distributed with this source code.
8
 * Para a informação dos direitos autorais e de licença você deve ler o arquivo
9
 * LICENSE que é distribuído com este código-fonte.
10
 * Para obtener la información de los derechos de autor y la licencia debe leer
11
 * el archivo LICENSE que se distribuye con el código fuente.
12
 * For more information, see <http://www.g1mr.com/>.
13
 */
14
15
namespace Gpupo\NetshoesSdk\Entity\Product\Sku;
16
17
use Gpupo\CommonSdk\Entity\EntityInterface;
18
use Gpupo\NetshoesSdk\Entity\AbstractManager;
19
20
class Manager extends AbstractManager
21
{
22
    protected $entity = 'SkuCollection';
23
24
    /**
25
     * @codeCoverageIgnore
26
     */
27
    protected function setUp()
28
    {
29
        $this->maps = include 'map.php';
30
    }
31
32
    /**
33
     * @return Gpupo\Common\Entity\CollectionAbstract|null
34
     */
35 View Code Duplication
    public function findById($itemId)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
36
    {
37
        $response = $this->perform($this->factoryMap('findById', [
38
            'productId' => $itemId,
39
            'itemId'    => $itemId,
40
        ]));
41
42
        $data = $this->processResponse($response);
43
44
        if (empty($data)) {
45
            return;
46
        }
47
48
        $sku = new Item($data->toArray());
49
50
        return $this->hydrate($sku);
51
    }
52
53
    protected function getDetail(EntityInterface $sku, $type)
54
    {
55
        $response = $this->perform($this->factoryMap('get'.$type, ['sku' => $sku->getId()]));
56
        $className = 'Gpupo\NetshoesSdk\Entity\Product\Sku\\'.$type;
57
        $data = $this->processResponse($response);
58
59
        $o = new $className($data->toArray());
60
61
        $this->getLogger()->addInfo('Detail', [
62
            'sku'       => $sku->getId(),
63
            'typ'       => $type,
64
            'response'  => $data,
65
            'className' => $className,
66
            'object'    => $o,
67
        ]);
68
69
        return $o;
70
    }
71
72 View Code Duplication
    protected function getPriceScheduleCollection(EntityInterface $sku)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
73
    {
74
        $response = $this->perform($this->factoryMap('getPriceSchedule', ['sku' => $sku->getId()]));
75
        $data = $this->processResponse($response);
76
77
        if (empty($data)) {
78
            return;
79
        }
80
81
        $collection = new PriceScheduleCollection($data->toArray());
82
83
        return $collection;
84
    }
85
86
    public function saveDetail(Item $sku, $type)
87
    {
88
        $json = $sku->toJson($type);
89
        $map = $this->factoryMap('save'.$type, ['sku' => $sku->getId()]);
90
91
        return $this->execute($map, $json);
92
    }
93
94
    protected function hydrate(EntityInterface $sku)
95
    {
96
        $sku->setPrice($this->getDetail($sku, 'Price'))
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Gpupo\CommonSdk\Entity\EntityInterface as the method setPrice() does only exist in the following implementations of said interface: Gpupo\NetshoesSdk\Entity\Product\Sku\Price.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
97
            ->setPriceSchedule($this->getPriceScheduleCollection($sku)->getCurrent())
98
            ->setStock($this->getDetail($sku, 'Stock'))
99
            ->setStatus($this->getDetail($sku, 'Status'));
100
101
        return $sku;
102
    }
103
104
    /**
105
     * {@inheritdoc}
106
     */
107
    public function update(EntityInterface $entity, EntityInterface $existent = null)
108
    {
109
        parent::update($entity, $existent);
110
111
        $response = [
112
            'sku'      => $entity->getId(),
113
            'bypassed' => [],
114
            'updated'  => [],
115
            'code'     => [],
116
        ];
117
118
        foreach ([
119
            'Status' => ['active'],
120
            'Stock' => ['available'],
121
            'Price' => ['price'],
122
            'PriceSchedule' => ['priceTo'],
123
        ] as $key => $attributes) {
124
            $getter = 'get'.$key;
125
            $diff = $this->attributesDiff($entity->$getter(), $existent->$getter(), $attributes);
126
            if (!empty($diff)) {
127
                $response['code'][$key] = $this->saveDetail($entity, $key)->getHttpStatusCode();
0 ignored issues
show
Compatibility introduced by
$entity of type object<Gpupo\CommonSdk\Entity\EntityInterface> is not a sub-type of object<Gpupo\NetshoesSdk\Entity\Product\Sku\Item>. It seems like you assume a concrete implementation of the interface Gpupo\CommonSdk\Entity\EntityInterface to be always present.

This check looks for parameters that are defined as one type in their type hint or doc comment but seem to be used as a narrower type, i.e an implementation of an interface or a subclass.

Consider changing the type of the parameter or doing an instanceof check before assuming your parameter is of the expected type.

Loading history...
128
129
                $response['updated'][] = $key;
130
            } else {
131
                $response['bypassed'][] = $key;
132
            }
133
        }
134
135
        $this->log('info', 'Operação de Atualização de entity '
136
            .$this->entity, $response);
137
138
        return $response;
139
    }
140
}
141