Completed
Push — master ( d72e6b...d34f34 )
by Gilmar
24:51
created

Manager   A

Complexity

Total Complexity 26

Size/Duplication

Total Lines 209
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 6

Test Coverage

Coverage 100%

Importance

Changes 27
Bugs 2 Features 0
Metric Value
wmc 26
c 27
b 2
f 0
lcom 1
cbo 6
dl 0
loc 209
ccs 44
cts 44
cp 1
rs 10

12 Methods

Rating   Name   Duplication   Size   Complexity  
A setUp() 0 4 1
A findById() 0 17 2
A add() 0 6 1
A saveDetail() 0 7 1
A resolvePrevious() 0 11 3
B update() 0 31 4
A updateInfo() 0 19 2
B updateDetails() 0 28 5
A getDetail() 0 18 1
A getPriceScheduleCollection() 0 19 3
A hydratePriceSchedule() 0 11 2
A hydrate() 0 8 1
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\CommonSdk\Exception\ManagerException;
19
use Gpupo\NetshoesSdk\Entity\AbstractManager;
20
21
final class Manager extends AbstractManager
22
{
23
    protected $entity = 'Sku';
24
25
    protected $strategy = [
26
        'info'    => false,
27
        'pricing' => 'simples',
28
    ];
29
30
    /**
31
     * @codeCoverageIgnore
32
     */
33
    protected function setUp()
34
    {
35
        $this->maps = include 'map.config.php';
36
    }
37
38
    /**
39
     * @return Gpupo\Common\Entity\CollectionAbstract|null
40
     */
41 1
    public function findById($itemId)
42
    {
43 1
        $response = $this->perform($this->factoryMap('findById', [
44 1
            'productId' => $itemId,
45 1
            'itemId'    => $itemId,
46
        ]));
47
48 1
        $data = $this->processResponse($response);
49
50 1
        if (empty($data)) {
51
            return;
52
        }
53
54 1
        $sku = new Item($data->toArray());
55
56 1
        return $this->hydrate($sku);
57
    }
58
59
    protected function getDetail(EntityInterface $sku, $type)
60
    {
61
        $response = $this->perform($this->factoryMap('get'.$type, ['sku' => $sku->getId()]));
62
        $className = 'Gpupo\NetshoesSdk\Entity\Product\Sku\\'.$type;
63
        $data = $this->processResponse($response);
64
65
        $o = new $className($data->toArray());
66
67
        $this->log('info', 'Detail', [
68
            'sku'       => $sku->getId(),
69
            'typ'       => $type,
70
            'response'  => $data,
71
            'className' => $className,
72
            'object'    => $o,
73
        ]);
74
75
        return $o;
76
    }
77
78
    protected function getPriceScheduleCollection(EntityInterface $sku)
79
    {
80
        try {
81
            $response = $this->perform($this->factoryMap('getPriceSchedule', ['sku' => $sku->getId()]));
82
            $data = $this->processResponse($response);
83
84
            if (empty($data)) {
85
                throw new ManagerException('No price schedule on SKU #'.$sku->getId());
86
            }
87
        } catch (ManagerException $e) {
88
            $this->log('error', $e->getMessage());
89
90
            return;
91
        }
92
93
        $collection = new PriceScheduleCollection($data->toArray());
94
95
        return $collection;
96
    }
97
98
    public function add(EntityInterface $entity, $productId)
99
    {
100
        return $this->execute($this->factoryMap('add', [
101
            'productId' => $productId,
102
        ]), $entity->toJson());
103
    }
104
105 1
    public function saveDetail(Item $sku, $type)
106
    {
107 1
        $json = $sku->toJson($type);
108 1
        $map = $this->factoryMap('save'.$type, ['sku' => $sku->getId()]);
109
110 1
        return $this->execute($map, $json);
111
    }
112
113
    protected function hydratePriceSchedule(EntityInterface $sku)
114
    {
115
        $ps = $this->getPriceScheduleCollection($sku);
116
117
        $sku->setPriceSchedule(false);
0 ignored issues
show
Bug introduced by
The method setPriceSchedule() does not seem to exist on object<Gpupo\CommonSdk\Entity\EntityInterface>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
118
        if ($ps instanceof PriceScheduleCollection) {
119
            $sku->setPriceSchedule($ps->getCurrent());
0 ignored issues
show
Bug introduced by
The method setPriceSchedule() does not seem to exist on object<Gpupo\CommonSdk\Entity\EntityInterface>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
120
        }
121
122
        return $sku;
123
    }
124
125
    public function hydrate(EntityInterface $sku)
126
    {
127
        $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...
128
            ->setStock($this->getDetail($sku, 'Stock'))
129
            ->setStatus($this->getDetail($sku, 'Status'));
130
131
        return $this->hydratePriceSchedule($sku);
132
    }
133
134
    protected function resolvePrevious(Item $entity)
135
    {
136
        try {
137
            $p = $this->findById($entity->getId());
138
            if ($p instanceof Item) {
139
                return $p;
140
            }
141
        } catch (\Exception $e) {
142
            throw new \Exception('Sku #'.$entity->getId().' not found on marketplace!');
143
        }
144
    }
145
146
    /**
147
     * {@inheritdoc}
148
     */
149 1
    public function update(EntityInterface $entity, EntityInterface $existent = null)
150
    {
151 1
        parent::update($entity, $existent);
152
153 1
        if (empty($existent)) {
154
            $existent = $this->resolvePrevious($entity);
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...
155
        }
156
157
        $response = [
158 1
            'sku'      => $entity->getId(),
159
            'bypassed' => [],
160
            'code'     => [],
161
            'updated'  => [],
162
        ];
163
164
        $list = [
165 1
            'updateDetails',
166
        ];
167
168 1
        if (true === $this->strategy['info']) {
169
            $list[] = 'updateInfo';
170
        }
171
172 1
        foreach ($list as $method) {
173 1
            $response = $this->$method($entity, $existent, $response);
174
        }
175
176 1
        $this->log('info', 'Operação de Atualização', $response);
177
178 1
        return $response;
179
    }
180
181 2
    public function updateInfo(Item $entity, $existent = null, array $response = [])
182
    {
183 2
        $compare = $this->attributesDiff($entity, $existent, ['name', 'color',
184
            'size', 'gender', 'eanIsbn', 'images', 'video', 'height',
185
            'width', 'depth', 'weight', ]);
186
187 2
        if (false === $compare) {
188 1
            $response['bypassed'][] = 'info';
189
190 1
            return $response;
191
        }
192
193 1
        $map = $this->factoryMap('update', ['itemId' => $entity->getId(), 'sku' => $entity->getId()]);
194 1
        $operation = $this->execute($map, $entity->toJson());
195 1
        $response['code']['info'] = $operation->getHttpStatusCode();
196 1
        $response['updated'][] = 'info';
197
198 1
        return $response;
199
    }
200
201 2
    public function updateDetails(Item $entity, Item $existent = null, array $response = [])
202
    {
203
        $list = [
204 2
            'Status' => ['active'],
205
            'Stock'  => ['available'],
206
            'Price'  => ['price'],
207
        ];
208
209 2
        if ($this->strategy['pricing'] === 'schedule') {
210
            $list['PriceSchedule'] = ['priceTo'];
211
        }
212
213 2
        foreach ($list as $key => $attributes) {
214 2
            $getter = 'get'.$key;
215
216 2
            if (!empty($existent)) {
217 2
                if (false === $this->attributesDiff($entity->$getter(), $existent->$getter(), $attributes)) {
218 1
                    $response['bypassed'][] = $key;
219 1
                    continue;
220
                }
221
            }
222
223 1
            $response['code'][$key] = $this->saveDetail($entity, $key)->getHttpStatusCode();
224 1
            $response['updated'][] = $key;
225
        }
226
227 2
        return $response;
228
    }
229
}
230