Completed
Push — master ( cbd662...dcc54b )
by Gilmar
25:22
created

Manager   A

Complexity

Total Complexity 9

Size/Duplication

Total Lines 125
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 4

Importance

Changes 13
Bugs 1 Features 0
Metric Value
wmc 9
c 13
b 1
f 0
lcom 1
cbo 4
dl 0
loc 125
rs 10

6 Methods

Rating   Name   Duplication   Size   Complexity  
A save() 0 4 1
A findSkuById() 0 17 2
A getDetail() 0 18 1
A saveDetail() 0 7 1
A hydrate() 0 9 1
B update() 0 38 3
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
    public function save(EntityInterface $product, $route = 'save')
41
    {
42
        return $this->execute($this->factoryMap($route), $product->toJson());
43
    }
44
45
    /**
46
     * @return Gpupo\Common\Entity\CollectionAbstract|null
47
     */
48
    public function findSkuById($itemId)
49
    {
50
        $response = $this->perform($this->factoryMap('findSkuById', [
51
            'productId' => $itemId,
52
            'itemId'    => $itemId,
53
        ]));
54
55
        $data = $this->processResponse($response);
56
57
        if (empty($data)) {
58
            return;
59
        }
60
61
        $sku = new Item($data->toArray());
62
63
        return $this->hydrate($sku);
64
    }
65
66
    protected function getDetail(EntityInterface $sku, $type)
67
    {
68
        $response = $this->perform($this->factoryMap('get'.$type, ['sku' => $sku->getId()]));
69
        $className = 'Gpupo\NetshoesSdk\Entity\Product\Sku\\'.$type;
70
        $data = $this->processResponse($response);
71
72
        $o = new $className($data->toArray());
73
74
        $this->getLogger()->addInfo('Detail', [
75
            'sku'       => $sku->getId(),
76
            'typ'       => $type,
77
            'response'  => $data,
78
            'className' => $className,
79
            'object'    => $o,
80
        ]);
81
82
        return $o;
83
    }
84
85
    public function saveDetail(Item $sku, $type)
86
    {
87
        $json = $sku->toJson($type);
88
        $map = $this->factoryMap('save'.$type, ['sku' => $sku->getId()]);
89
90
        return $this->execute($map, $json);
91
    }
92
93
    protected function hydrate(EntityInterface $sku)
94
    {
95
        $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...
96
            ->setPriceSchedule($this->getDetail($sku, 'PriceSchedule'))
97
            ->setStock($this->getDetail($sku, 'Stock'))
98
            ->setStatus($this->getDetail($sku, 'Status'));
99
100
        return $sku;
101
    }
102
103
    /**
104
     * {@inheritdoc}
105
     */
106
    public function update(EntityInterface $entity, EntityInterface $existent = null)
107
    {
108
        parent::update($entity, $existent);
109
110
        $m = $this->factoryMap('update', [
0 ignored issues
show
Unused Code introduced by
$m is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
111
            'productId' => $entity->getId(),
112
            'itemId'    => $entity->getId(),
113
        ]);
114
115
        $response = [
116
            'sku'      => $entity->getId(),
117
            'bypassed' => [],
118
            'updated'  => [],
119
            'code'     => [],
120
        ];
121
122
        foreach ([
123
            'Status' => ['active'],
124
            'Stock' => ['available'],
125
            'Price' => ['price'],
126
            'PriceSchedule' => ['priceTo'],
127
        ] as $key => $attributes) {
128
            $getter = 'get'.$key;
129
            $diff = $this->attributesDiff($entity->$getter(), $existent->$getter(), $attributes);
130
            if (!empty($diff)) {
131
                $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...
132
133
                $response['updated'][] = $key;
134
            } else {
135
                $response['bypassed'][] = $key;
136
            }
137
        }
138
139
        $this->log('info', 'Operação de Atualização de entity '
140
            .$this->entity, $response);
141
142
        return $response;
143
    }
144
}
145