Completed
Push — master ( c9dd2f...f3d682 )
by Gilmar
25:00
created

Manager::save()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
c 2
b 0
f 0
dl 0
loc 4
rs 10
cc 1
eloc 2
nc 1
nop 2
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
    protected $maps = [
25
        'save'              => ['POST', '/products/{productId}/skus'], //Create a new sku for a product
26
        'findSkuById'       => ['GET', '/products/{productId}/skus/{itemId}'], // Get the a sku by product Id and sku Id
27
        'update'            => ['PUT', '/products/{productId}/skus/{itemId}'], //Update a product based on SKU
28
        'findById'          => ['GET', '/products/{itemId}/skus'], //Get the list of product skus
29
        'saveStatus'        => ['PUT', '/skus/{sku}/bus/{buId}/status'], //Enable or disable sku for sale
30
        'savePriceSchedule' => ['POST', '/skus/{sku}/priceSchedules'], //Save a price schedule
31
        'getPriceSchedule'  => ['GET', '/skus/{sku}/priceSchedules'], //Get PriceSchedule
32
        'getPrice'          => ['GET', '/skus/{sku}/prices'], //Get a base price
33
        'savePrice'         => ['PUT', '/skus/{sku}/prices'], //Save a base price
34
        'saveStock'         => ['PUT', '/skus/{sku}/stocks'], //Update stock quantity by sku
35
        'getStock'          => ['GET', '/skus/{sku}/stocks'], //Get Stock
36
        'saveStatus'        => ['GET', '/skus/{sku}/bus/{buId}/status'], //Save Status
37
        'getStatus'         => ['GET', '/skus/{sku}/bus/{buId}/status'], //Get Status
38
    ];
39
40
    /**
41
     * @return Gpupo\Common\Entity\CollectionAbstract|null
42
     */
43
    public function findSkuById($itemId)
44
    {
45
        $response = $this->perform($this->factoryMap('findSkuById', [
46
            'productId' => $itemId,
47
            'itemId'    => $itemId,
48
        ]));
49
50
        $data = $this->processResponse($response);
51
52
        if (empty($data)) {
53
            return;
54
        }
55
56
        $sku = new Item($data->toArray());
57
58
        return $this->hydrate($sku);
59
    }
60
61
    protected function getDetail(EntityInterface $sku, $type)
62
    {
63
        $response = $this->perform($this->factoryMap('get'.$type, ['sku' => $sku->getId()]));
64
        $className = 'Gpupo\NetshoesSdk\Entity\Product\Sku\\'.$type;
65
        $data = $this->processResponse($response);
66
67
        $o = new $className($data->toArray());
68
69
        $this->getLogger()->addInfo('Detail', [
70
            'sku'       => $sku->getId(),
71
            'typ'       => $type,
72
            'response'  => $data,
73
            'className' => $className,
74
            'object'    => $o,
75
        ]);
76
77
        return $o;
78
    }
79
80
    public function saveDetail(Item $sku, $type)
81
    {
82
        $json = $sku->toJson($type);
83
        $map = $this->factoryMap('save'.$type, ['sku' => $sku->getId()]);
84
85
        return $this->execute($map, $json);
86
    }
87
88
    protected function hydrate(EntityInterface $sku)
89
    {
90
        $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...
91
            ->setPriceSchedule($this->getDetail($sku, 'PriceSchedule'))
92
            ->setStock($this->getDetail($sku, 'Stock'))
93
            ->setStatus($this->getDetail($sku, 'Status'));
94
95
        return $sku;
96
    }
97
98
    /**
99
     * {@inheritdoc}
100
     */
101
    public function update(EntityInterface $entity, EntityInterface $existent = null)
102
    {
103
        parent::update($entity, $existent);
104
105
        $response = [
106
            'sku'      => $entity->getId(),
107
            'bypassed' => [],
108
            'updated'  => [],
109
            'code'     => [],
110
        ];
111
112
        foreach ([
113
            'Status' => ['active'],
114
            'Stock' => ['available'],
115
            'Price' => ['price'],
116
            'PriceSchedule' => ['priceTo'],
117
        ] as $key => $attributes) {
118
            $getter = 'get'.$key;
119
            $diff = $this->attributesDiff($entity->$getter(), $existent->$getter(), $attributes);
120
            if (!empty($diff)) {
121
                $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...
122
123
                $response['updated'][] = $key;
124
            } else {
125
                $response['bypassed'][] = $key;
126
            }
127
        }
128
129
        $this->log('info', 'Operação de Atualização de entity '
130
            .$this->entity, $response);
131
132
        return $response;
133
    }
134
}
135