Completed
Push — master ( 7e286e...291aee )
by Gilmar
26:11
created

Manager::update()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 19
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 7
Bugs 1 Features 0
Metric Value
c 7
b 1
f 0
dl 0
loc 19
rs 9.4285
ccs 0
cts 0
cp 0
cc 2
eloc 11
nc 2
nop 2
crap 6
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 = 'Sku';
23
24
    /**
25
     * @codeCoverageIgnore
26
     */
27
    protected function setUp()
28
    {
29
        $this->maps = include 'map.config.php';
30
    }
31
32
    /**
33
     * @return Gpupo\Common\Entity\CollectionAbstract|null
34
     */
35 1 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 1
        $response = $this->perform($this->factoryMap('findById', [
38 1
            'productId' => $itemId,
39 1
            'itemId'    => $itemId,
40
        ]));
41
42 1
        $data = $this->processResponse($response);
43
44 1
        if (empty($data)) {
45
            return;
46
        }
47
48 1
        $sku = new Item($data->toArray());
49
50 1
        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 (['updateInfo', 'updateDetails'] as $method) {
119
            $response = $this->$method($entity, $existent, $response);
120
        }
121
122
        $this->log('info', 'Operação de Atualização', $response);
123
124
        return $response;
125
    }
126
127 1
    public function updateInfo(Item $entity, Item $existent = null, array $response = [])
128
    {
129 1
        $compare = $this->attributesDiff($entity, $existent, ['name', 'color',
0 ignored issues
show
Bug introduced by
It seems like $existent defined by parameter $existent on line 127 can be null; however, Gpupo\CommonSdk\Traits\E...Trait::attributesDiff() does not accept null, maybe add an additional type check?

It seems like you allow that null is being passed for a parameter, however the function which is called does not seem to accept null.

We recommend to add an additional type check (or disallow null for the parameter):

function notNullable(stdClass $x) { }

// Unsafe
function withoutCheck(stdClass $x = null) {
    notNullable($x);
}

// Safe - Alternative 1: Adding Additional Type-Check
function withCheck(stdClass $x = null) {
    if ($x instanceof stdClass) {
        notNullable($x);
    }
}

// Safe - Alternative 2: Changing Parameter
function withNonNullableParam(stdClass $x) {
    notNullable($x);
}
Loading history...
130
            'size', 'gender', 'eanIsbn', 'images', 'video', 'height',
131
            'width', 'depth', 'weight', ]);
132
133 1
        if (false === $compare) {
134
            $response['bypassed'][] = $key;
0 ignored issues
show
Bug introduced by
The variable $key does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
135
136
            return $response;
137
        }
138
139 1
        $map = $this->factoryMap('save', ['sku' => $entity->getId()]);
140 1
        $operation = $this->execute($map, $entity->toJson());
141 1
        $response['code']['info'] = $operation->getHttpStatusCode();
142 1
        $response['updated'][] = 'info';
143
144 1
        return $response;
145
    }
146
147 1
    public function updateDetails(Item $entity, Item $existent = null, array $response = [])
148
    {
149
        foreach ([
150 1
            'Status' => ['active'],
151
            'Stock' => ['available'],
152
            'Price' => ['price'],
153
            'PriceSchedule' => ['priceTo'],
154
        ] as $key => $attributes) {
155 1
            $getter = 'get'.$key;
156
157 1
            if (!empty($existent)) {
158 1
                if (false === $this->attributesDiff($entity->$getter(), $existent->$getter(), $attributes)) {
159
                    $response['bypassed'][] = $key;
160
                    continue;
161
                }
162
            }
163
164 1
            $response['code'][$key] = $this->saveDetail($entity, $key)->getHttpStatusCode();
165 1
            $response['updated'][] = $key;
166
        }
167
168 1
        return $response;
169
    }
170
}
171