Completed
Push — master ( c01c8f...045907 )
by Gilmar
25:31
created

Manager::resolveIfNew()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 11
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 11
ccs 0
cts 7
cp 0
rs 9.4285
cc 3
eloc 6
nc 3
nop 2
crap 12
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;
16
17
use Gpupo\CommonSdk\Entity\EntityInterface;
18
use Gpupo\CommonSdk\Traits\TranslatorManagerTrait;
19
use Gpupo\NetshoesSdk\Entity\AbstractManager;
20
use Gpupo\NetshoesSdk\Factory;
21
22
final class Manager extends AbstractManager
23
{
24
    use TranslatorManagerTrait;
25
26
    protected $entity = 'Product';
27
28
    protected $strategy = [
29
        'info' => false,
30
    ];
31
32
    /**
33
     * @codeCoverageIgnore
34
     */
35
    protected $maps = [
36
        'save'     => ['POST', '/products'],
37
        'findById' => ['GET', '/products/{itemId}'],
38
        'patch'    => ['PATCH', '/products/{itemId}'],
39
        'update'   => ['PUT', '/products/{itemId}'],
40
        'fetch'    => ['GET', '/products?page={offset}&size={limit}'],
41
    ];
42
43 1
    public function patch(EntityInterface $entity, $compare)
44
    {
45 1
        if (empty($compare)) {
46 1
            return false;
47
        }
48
49 1
        $json = json_encode($entity->toPatch($compare));
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 toPatch() does only exist in the following implementations of said interface: Gpupo\NetshoesSdk\Entity\Product\Product.

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...
50 1
        $map = $this->factoryMap('patch', ['itemId' => $entity->getId()]);
51 1
        $operation = $this->execute($map, $json);
52
53
        $feedback = [
54 1
            'fields'        => $compare,
55 1
            'response_code' => $operation->getHttpStatusCode(),
56
        ];
57
58 1
        $this->log('info', 'Operação de Atualização de produto (PATCH)', $feedback);
59
60 1
        return $feedback;
61
    }
62
63
    protected function resolveIfNew(EntityInterface $entity, EntityInterface $existent = null)
64
    {
65
        if ($existent instanceof EntityInterface) {
66
            return;
67
        }
68
        if (false !== parent::findById($entity->getId())) {
0 ignored issues
show
Comprehensibility Bug introduced by
It seems like you call parent on a different method (findById() instead of resolveIfNew()). Are you sure this is correct? If so, you might want to change this to $this->findById().

This check looks for a call to a parent method whose name is different than the method from which it is called.

Consider the following code:

class Daddy
{
    protected function getFirstName()
    {
        return "Eidur";
    }

    protected function getSurName()
    {
        return "Gudjohnsen";
    }
}

class Son
{
    public function getFirstName()
    {
        return parent::getSurname();
    }
}

The getFirstName() method in the Son calls the wrong method in the parent class.

Loading history...
69
            return;
70
        }
71
72
        $this->save($entity);
73
    }
74
75 1
    private function skuManager()
76
    {
77 1
        return $this->factorySubManager(Factory::getInstance(), 'sku');
78
    }
79
80
    /**
81
     * {@inheritdoc}
82
     */
83 2
    public function update(EntityInterface $entity, EntityInterface $existent = null)
84
    {
85 2
        if (0 === $entity->getSkus()->count()) {
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 getSkus() does only exist in the following implementations of said interface: Gpupo\NetshoesSdk\Entity\Product\Product.

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...
86 1
            throw new \InvalidArgumentException('Product precisa conter SKU!');
87
        }
88
89 1
        $this->resolveIfNew($entity, $existent);
90
91 1
        $response = [];
92
93 1
        if (true === $this->strategy['info']) {
94
            $compare = $this->attributesDiff($entity, $existent, ['department', 'productType']);
95
            $response['patch'] = $this->patch($entity, $compare);
96
        }
97
98 1
        $response['skus'] = [];
99
100 1
        foreach ($entity->getSkus() as $sku) {
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 getSkus() does only exist in the following implementations of said interface: Gpupo\NetshoesSdk\Entity\Product\Product.

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...
101 1
            $previous = null;
102
103 1
            if ($existent instanceof EntityInterface) {
104 1
                $previous = $existent->getSkus()->findById($sku->getId());
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 getSkus() does only exist in the following implementations of said interface: Gpupo\NetshoesSdk\Entity\Product\Product.

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...
105
            }
106
107 1
            $response['skus'][] = $this->skuManager()->update($sku, $previous);
108
        }
109
110 1
        return $response;
111
    }
112
113 1
    public function factoryTranslator(array $data = [])
114
    {
115 1
        $translator = new Translator($data);
116
117 1
        return $translator;
118
    }
119
120 2
    public function findById($itemId)
121
    {
122 2
        $product = parent::findById($itemId);
123
124 2
        if (empty($product)) {
125 1
            return false;
126
        }
127
128 1
        $sm = $this->skuManager();
129 1
        $product->getSkus()->forAll(function ($key, $element) use ($sm) {
130 1
            $sm->hydrate($element);
131 1
        });
132
133 1
        return $product;
134
    }
135
}
136