Completed
Push — 19.x ( 8328ae...eef76a )
by Tim
05:57
created

ProductObserver::mergeEntity()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 9
ccs 0
cts 1
cp 0
rs 9.9666
c 0
b 0
f 0
cc 1
nc 1
nop 3
crap 2
1
<?php
2
3
/**
4
 * TechDivision\Import\Product\Observers\ProductObserver
5
 *
6
 * NOTICE OF LICENSE
7
 *
8
 * This source file is subject to the Open Software License (OSL 3.0)
9
 * that is available through the world-wide-web at this URL:
10
 * http://opensource.org/licenses/osl-3.0.php
11
 *
12
 * PHP version 5
13
 *
14
 * @author    Tim Wagner <[email protected]>
15
 * @copyright 2016 TechDivision GmbH <[email protected]>
16
 * @license   http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
17
 * @link      https://github.com/techdivision/import-product
18
 * @link      http://www.techdivision.com
19
 */
20
21
namespace TechDivision\Import\Product\Observers;
22
23
use TechDivision\Import\Product\Utils\ColumnKeys;
24
use TechDivision\Import\Product\Utils\MemberNames;
25
use TechDivision\Import\Observers\StateDetectorInterface;
26
use TechDivision\Import\Product\Services\ProductBunchProcessorInterface;
27
28
/**
29
 * Observer that create's the product itself.
30
 *
31
 * @author    Tim Wagner <[email protected]>
32
 * @copyright 2016 TechDivision GmbH <[email protected]>
33
 * @license   http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
34
 * @link      https://github.com/techdivision/import-product
35
 * @link      http://www.techdivision.com
36
 */
37
class ProductObserver extends AbstractProductImportObserver
38
{
39
40
    /**
41
     * The product bunch processor instance.
42
     *
43
     * @var \TechDivision\Import\Product\Services\ProductBunchProcessorInterface
44
     */
45
    protected $productBunchProcessor;
46
47
    /**
48
     * Initialize the observer with the passed product bunch processor instance.
49
     *
50
     * @param \TechDivision\Import\Product\Services\ProductBunchProcessorInterface $productBunchProcessor The product bunch processor instance
51 1
     * @param \TechDivision\Import\Observers\StateDetectorInterface|null           $stateDetector         The state detector instance to use
52
     */
53 1
    public function __construct(ProductBunchProcessorInterface $productBunchProcessor, StateDetectorInterface $stateDetector = null)
54 1
    {
55
56
        // initialize the bunch processor instance
57
        $this->productBunchProcessor = $productBunchProcessor;
58
59
        // pass the state detector to the parent method
60
        parent::__construct($stateDetector);
0 ignored issues
show
Bug introduced by
It seems like you code against a specific sub-type and not the parent class TechDivision\Import\Prod...ctProductImportObserver as the method __construct() does only exist in the following sub-classes of TechDivision\Import\Prod...ctProductImportObserver: TechDivision\Import\Prod...ProductRelationObserver, TechDivision\Import\Prod...tRelationUpdateObserver, TechDivision\Import\Prod...CategoryProductObserver, TechDivision\Import\Prod...ryProductUpdateObserver, TechDivision\Import\Prod...servers\CleanUpObserver, TechDivision\Import\Prod...rs\ClearProductObserver, TechDivision\Import\Prod...EntityIdMappingObserver, TechDivision\Import\Prod...rs\LastEntityIdObserver, TechDivision\Import\Prod...PreLoadEntityIdObserver, TechDivision\Import\Prod...roductInventoryObserver, TechDivision\Import\Prod...InventoryUpdateObserver, TechDivision\Import\Prod...servers\ProductObserver, TechDivision\Import\Prod...\ProductWebsiteObserver, TechDivision\Import\Prod...ctWebsiteUpdateObserver, TechDivision\Import\Prod...bservers\UrlKeyObserver. Maybe you want to instanceof check for one of these explicitly?

Let’s take a look at an example:

abstract class User
{
    /** @return string */
    abstract public function getPassword();
}

class MyUser extends 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 sub-classes 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 parent class:

    abstract class User
    {
        /** @return string */
        abstract public function getPassword();
    
        /** @return string */
        abstract public function getDisplayName();
    }
    
Loading history...
61 1
    }
62
63 1
    /**
64
     * Return's the product bunch processor instance.
65
     *
66
     * @return \TechDivision\Import\Product\Services\ProductBunchProcessorInterface The product bunch processor instance
67
     */
68
    protected function getProductBunchProcessor()
69
    {
70
        return $this->productBunchProcessor;
71 1
    }
72
73
    /**
74
     * Process the observer's business logic.
75 1
     *
76
     * @return void
77
     */
78
    protected function process()
79
    {
80 1
81
        // query whether or not, we've found a new SKU => means we've found a new product
82
        if ($this->hasBeenProcessed($this->getValue(ColumnKeys::SKU))) {
83 1
            return;
84 1
        }
85
86
        // prepare the product and query whether or not it has to be persisted or the row has to be skipped
87
        if ($this->hasChanges($product = $this->initializeProduct($this->prepareAttributes()))) {
0 ignored issues
show
Bug introduced by
The method hasChanges() does not seem to exist on object<TechDivision\Impo...ervers\ProductObserver>.

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...
88
            $this->persistProduct($product);
89
        }
90
    }
91 1
92
    /**
93
     * Prepare the attributes of the entity that has to be persisted.
94
     *
95 1
     * @return array The prepared attributes
96 1
     */
97
    protected function prepareAttributes()
98
    {
99 1
100 1
        // prepare the date format for the created at/updated at dates
101
        $createdAt = $this->getValue(ColumnKeys::CREATED_AT, date('Y-m-d H:i:s'), array($this, 'formatDate'));
102
        $updatedAt = $this->getValue(ColumnKeys::UPDATED_AT, date('Y-m-d H:i:s'), array($this, 'formatDate'));
103 1
104 1
        // initialize the product values
105
        $sku = $this->getValue(ColumnKeys::SKU);
106
        $productType = $this->getValue(ColumnKeys::PRODUCT_TYPE);
107 1
108
        // load the product's attribute set ID
109 1
        $attributeSet = $this->getAttributeSet();
110 1
        $attributeSetId = $attributeSet[MemberNames::ATTRIBUTE_SET_ID];
111 1
112 1
        // return the prepared product
113 1
        return $this->initializeEntity(
114 1
            array(
115 1
                MemberNames::SKU              => $sku,
116
                MemberNames::CREATED_AT       => $createdAt,
117
                MemberNames::UPDATED_AT       => $updatedAt,
118
                MemberNames::HAS_OPTIONS      => 0,
119
                MemberNames::REQUIRED_OPTIONS => 0,
120
                MemberNames::TYPE_ID          => $productType,
121
                MemberNames::ATTRIBUTE_SET_ID => $attributeSetId
122
            )
123
        );
124
    }
125
126
    /**
127 1
     * Merge's and return's the entity with the passed attributes and set's the
128
     * passed status.
129
     *
130
     * @param array       $entity        The entity to merge the attributes into
131 1
     * @param array       $attr          The attributes to be merged
132 1
     * @param string|null $changeSetName The change set name to use
133
     *
134
     * @return array The merged entity
135
     */
136
    protected function mergeEntity(array $entity, array $attr, $changeSetName = null)
137
    {
138
139
        // temporary persist the entity ID
140
        $this->setLastEntityId($entity[MemberNames::ENTITY_ID]);
141
142
        // merge and return the entity
143
        return parent::mergeEntity($entity, $attr, $changeSetName);
0 ignored issues
show
Unused Code introduced by
The call to AbstractProductImportObserver::mergeEntity() has too many arguments starting with $changeSetName.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
144
    }
145
146 1
    /**
147
     * Initialize the product with the passed attributes and returns an instance.
148 1
     *
149
     * @param array $attr The product attributes
150
     *
151
     * @return array The initialized product
152
     */
153
    protected function initializeProduct(array $attr)
154
    {
155
156
        // load the product with the passed SKU and merge it with the attributes
157
        if ($entity = $this->loadProduct($attr[MemberNames::SKU])) {
158 1
            return $this->mergeEntity($entity, $attr);
159
        }
160 1
161
        // otherwise simply return the attributes
162
        return $attr;
163
    }
164
165
    /**
166
     * Load's and return's the product with the passed SKU.
167
     *
168 1
     * @param string $sku The SKU of the product to load
169
     *
170 1
     * @return array The product
171
     */
172
    protected function loadProduct($sku)
173
    {
174
        return $this->getProductBunchProcessor()->loadProduct($sku);
175
    }
176
177
    /**
178
     * Persist's the passed product data.
179
     *
180 1
     * @param array $product The product data to persist
181
     *
182 1
     * @return void
183 1
     */
184
    protected function persistProduct($product)
185
    {
186
        $this->setLastEntityId($this->getProductBunchProcessor()->persistProduct($product));
187
    }
188
189
    /**
190
     * Return's the attribute set of the product that has to be created.
191
     *
192
     * @return array The attribute set
193
     */
194
    protected function getAttributeSet()
195
    {
196
        return $this->getSubject()->getAttributeSet();
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface TechDivision\Import\Subjects\SubjectInterface as the method getAttributeSet() does only exist in the following implementations of said interface: TechDivision\Import\Observers\EntitySubjectImpl, TechDivision\Import\Prod...\AbstractProductSubject, TechDivision\Import\Product\Subjects\BunchSubject, TechDivision\Import\Subjects\AbstractEavSubject.

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...
197
    }
198
199
    /**
200
     * Set's the ID of the product that has been created recently.
201
     *
202
     * @param string $lastEntityId The entity ID
203
     *
204
     * @return void
205
     */
206
    protected function setLastEntityId($lastEntityId)
207
    {
208
        $this->getSubject()->setLastEntityId($lastEntityId);
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface TechDivision\Import\Subjects\SubjectInterface as the method setLastEntityId() does only exist in the following implementations of said interface: TechDivision\Import\Plugins\ExportableSubjectImpl, TechDivision\Import\Prod...\AbstractProductSubject, TechDivision\Import\Product\Subjects\BunchSubject, TechDivision\Import\Subjects\ExportableTraitImpl.

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...
209
    }
210
}
211