Completed
Push — master ( fd00f3...3479b2 )
by Tim
12s
created

getProductVariantProcessor()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 0
cts 4
cp 0
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 0
crap 2
1
<?php
2
3
/**
4
 * TechDivision\Import\Product\Variant\Observers\VariantSuperAttributeObserver
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-variant
18
 * @link      http://www.techdivision.com
19
 */
20
21
namespace TechDivision\Import\Product\Variant\Observers;
22
23
use TechDivision\Import\Utils\StoreViewCodes;
24
use TechDivision\Import\Product\Variant\Utils\ColumnKeys;
25
use TechDivision\Import\Product\Variant\Utils\MemberNames;
26
use TechDivision\Import\Product\Observers\AbstractProductImportObserver;
27
use TechDivision\Import\Product\Variant\Services\ProductVariantProcessorInterface;
28
29
/**
30
 * Oberserver that provides functionality for the product variant super attributes replace operation.
31
 *
32
 * @author    Tim Wagner <[email protected]>
33
 * @copyright 2016 TechDivision GmbH <[email protected]>
34
 * @license   http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
35
 * @link      https://github.com/techdivision/import-product-variant
36
 * @link      http://www.techdivision.com
37
 */
38
class VariantSuperAttributeObserver extends AbstractProductImportObserver
39
{
40
41
    /**
42
     * The ID of the actual store to use.
43
     *
44
     * @var integer
45
     */
46
    protected $storeId;
47
48
    /**
49
     * The EAV attribute to handle.
50
     *
51
     * @var array
52
     */
53
    protected $eavAttribute;
54
55
    /**
56
     * The tempoarary stored product super attribute ID.
57
     *
58
     * @var integer
59
     */
60
    protected $productSuperAttributeId;
61
62
    /**
63
     * The product variant processor instance.
64
     *
65
     * @var \TechDivision\Import\Product\Variant\Services\ProductVariantProcessorInterface
66
     */
67
    protected $productVariantProcessor;
68
69
    /**
70
     * Initialize the observer with the passed product variant processor instance.
71
     *
72
     * @param \TechDivision\Import\Product\Variant\Services\ProductVariantProcessorInterface $productVariantProcessor The product variant processor instance
73
     */
74
    public function __construct(ProductVariantProcessorInterface $productVariantProcessor)
75
    {
76
        $this->productVariantProcessor = $productVariantProcessor;
77
    }
78
79
    /**
80
     * Return's the product variant processor instance.
81
     *
82
     * @return \TechDivision\Import\Product\Variant\Services\ProductVariantProcessorInterface The product variant processor instance
83
     */
84
    protected function getProductVariantProcessor()
85
    {
86
        return $this->productVariantProcessor;
87
    }
88
89
    /**
90
     * Process the observer's business logic.
91
     *
92
     * @return array The processed row
93
     */
94
    protected function process()
95
    {
96
97
        // load parent/child IDs
98
        $parentId = $this->mapParentSku($parentSku = $this->getValue(ColumnKeys::VARIANT_PARENT_SKU));
99
100
        // query whether or not, the parent ID have changed
101
        if ($this->isParentId($parentId)) {
102
            return;
103
        }
104
105
        // prepare the store view code
106
        $this->prepareStoreViewCode($this->getRow());
0 ignored issues
show
Unused Code introduced by
The call to VariantSuperAttributeObs...:prepareStoreViewCode() has too many arguments starting with $this->getRow().

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...
107
108
        // preserve the parent ID
109
        $this->setParentId($parentId);
110
111
        // extract the option value and attribute code from the row
112
        $attributeCode = $this->getValue(ColumnKeys::VARIANT_ATTRIBUTE_CODE);
113
114
        // load the store and set the store ID
115
        $store = $this->getStoreByStoreCode($this->getStoreViewCode(StoreViewCodes::ADMIN));
116
        $this->storeId = $store[MemberNames::STORE_ID];
117
118
        try {
119
            // load the EAV attribute with the found attribute code
120
            $this->eavAttribute = $this->getEavAttributeByAttributeCode($attributeCode);
121
        } catch (\Exception $e) {
122
            throw $this->wrapException(array(ColumnKeys::VARIANT_ATTRIBUTE_CODE), $e);
0 ignored issues
show
Documentation introduced by
array(\TechDivision\Impo...VARIANT_ATTRIBUTE_CODE) is of type array<integer,?>, but the function expects a string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
123
        }
124
125
        try {
126
            // initialize and save the super attribute
127
            $productSuperAttribute = $this->initializeProductSuperAttribute($this->prepareProducSuperAttributeAttributes());
128
            $this->productSuperAttributeId = $this->persistProductSuperAttribute($productSuperAttribute);
0 ignored issues
show
Documentation Bug introduced by
The property $productSuperAttributeId was declared of type integer, but $this->persistProductSup...$productSuperAttribute) is of type string. Maybe add a type cast?

This check looks for assignments to scalar types that may be of the wrong type.

To ensure the code behaves as expected, it may be a good idea to add an explicit type cast.

$answer = 42;

$correct = false;

$correct = (bool) $answer;
Loading history...
129
130
            // initialize and save the super attribute label
131
            $productSuperAttributeLabel = $this->initializeProductSuperAttributeLabel($this->prepareProductSuperAttributeLabelAttributes());
132
            $this->persistProductSuperAttributeLabel($productSuperAttributeLabel);
133
0 ignored issues
show
Coding Style introduced by
Blank line found at end of control structure
Loading history...
134
        } catch (\Exception $e) {
135
            // prepare a more detailed error message
136
            $message = $this->appendExceptionSuffix(
137
                sprintf(
138
                    'Super attribute for SKU %s and attribute %s can\'t be created',
139
                    $parentSku,
140
                    $attributeCode
141
                )
142
            );
143
144
            // if we're NOT in debug mode, re-throw a more detailed exception
145
            $wrappedException = $this->wrapException(
146
                array(ColumnKeys::VARIANT_PARENT_SKU, ColumnKeys::VARIANT_ATTRIBUTE_CODE),
0 ignored issues
show
Documentation introduced by
array(\TechDivision\Impo...VARIANT_ATTRIBUTE_CODE) is of type array<integer,?>, but the function expects a string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
147
                new \Exception($message, null, $e)
148
            );
149
150
            // query whether or not, debug mode is enabled
151
            if ($this->isDebugMode()) {
152
                // log a warning and return immediately
153
                $this->getSystemLogger()->warning($wrappedException->getMessage());
154
                return;
155
            }
156
157
            // else, throw the exception
158
            throw $wrappedException;
159
        }
160
    }
161
162
    /**
163
     * Prepare the product super attribute attributes that has to be persisted.
164
     *
165
     * @return array The prepared product attribute attributes
166
     */
167
    protected function prepareProducSuperAttributeAttributes()
168
    {
169
170
        // load the parent ID
171
        $parentId = $this->getParentId();
172
173
        // load the attribute ID
174
        $attributeId = $this->eavAttribute[MemberNames::ATTRIBUTE_ID];
175
176
        // initialize the attributes and return them
177
        return $this->initializeEntity(
178
            array(
179
                MemberNames::PRODUCT_ID   => $parentId,
180
                MemberNames::ATTRIBUTE_ID => $attributeId,
181
                MemberNames::POSITION     => 0
182
            )
183
        );
184
    }
185
186
    /**
187
     * Prepare the product super attribute label attributes that has to be persisted.
188
     *
189
     * @return array The prepared product super attribute label attributes
190
     */
191
    protected function prepareProductSuperAttributeLabelAttributes()
192
    {
193
194
        // extract the parent/child ID as well as option value and variation label from the row
195
        $variationLabel = $this->getValue(ColumnKeys::VARIANT_VARIATION_LABEL);
196
197
        // query whether or not we've to create super attribute labels
198
        if (empty($variationLabel)) {
199
            $variationLabel = $this->eavAttribute[MemberNames::FRONTENT_LABEL];
200
        }
201
202
        // initialize the attributes and return them
203
        return $this->initializeEntity(
204
            array(
205
                MemberNames::PRODUCT_SUPER_ATTRIBUTE_ID => $this->productSuperAttributeId,
206
                MemberNames::STORE_ID                   => $this->storeId,
207
                MemberNames::USE_DEFAULT                => 0,
208
                MemberNames::VALUE                      => $variationLabel
209
            )
210
        );
211
    }
212
213
    /**
214
     * Initialize the product super attribute with the passed attributes and returns an instance.
215
     *
216
     * @param array $attr The product super attribute attributes
217
     *
218
     * @return array The initialized product super attribute
219
     */
220
    protected function initializeProductSuperAttribute(array $attr)
221
    {
222
        return $attr;
223
    }
224
225
    /**
226
     * Initialize the product super attribute label with the passed attributes and returns an instance.
227
     *
228
     * @param array $attr The product super attribute label attributes
229
     *
230
     * @return array The initialized product super attribute label
231
     */
232
    protected function initializeProductSuperAttributeLabel(array $attr)
233
    {
234
        return $attr;
235
    }
236
237
    /**
238
     * Map's the passed SKU of the parent product to it's PK.
239
     *
240
     * @param string $parentSku The SKU of the parent product
241
     *
242
     * @return integer The primary key used to create relations
243
     */
244
    protected function mapParentSku($parentSku)
245
    {
246
        return $this->mapSkuToEntityId($parentSku);
247
    }
248
249
    /**
250
     * Return the entity ID for the passed SKU.
251
     *
252
     * @param string $sku The SKU to return the entity ID for
253
     *
254
     * @return integer The mapped entity ID
255
     * @throws \Exception Is thrown if the SKU is not mapped yet
256
     */
257
    protected function mapSkuToEntityId($sku)
258
    {
259
        return $this->getSubject()->mapSkuToEntityId($sku);
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 mapSkuToEntityId() does only exist in the following implementations of said interface: TechDivision\Import\Prod...Subjects\VariantSubject.

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...
260
    }
261
262
    /**
263
     * Return's TRUE if the passed ID is the parent one.
264
     *
265
     * @param integer $parentId The parent ID to check
266
     *
267
     * @return boolean TRUE if the passed ID is the parent one
268
     */
269
    protected function isParentId($parentId)
270
    {
271
        return $this->getParentId() === $parentId;
272
    }
273
274
    /**
275
     * Set's the ID of the parent product to relate the variant with.
276
     *
277
     * @param integer $parentId The ID of the parent product
278
     *
279
     * @return void
280
     */
281
    protected function setParentId($parentId)
282
    {
283
        $this->getSubject()->setParentId($parentId);
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 setParentId() does only exist in the following implementations of said interface: TechDivision\Import\Prod...Subjects\VariantSubject.

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...
284
    }
285
286
    /**
287
     * Return's the ID of the parent product to relate the variant with.
288
     *
289
     * @return integer The ID of the parent product
290
     */
291
    protected function getParentId()
292
    {
293
        return $this->getSubject()->getParentId();
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 getParentId() does only exist in the following implementations of said interface: TechDivision\Import\Prod...Subjects\VariantSubject.

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...
294
    }
295
296
    /**
297
     * Return's the store for the passed store code.
298
     *
299
     * @param string $storeCode The store code to return the store for
300
     *
301
     * @return array The requested store
302
     * @throws \Exception Is thrown, if the requested store is not available
303
     */
304
    protected function getStoreByStoreCode($storeCode)
305
    {
306
        return $this->getSubject()->getStoreByStoreCode($storeCode);
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 getStoreByStoreCode() does only exist in the following implementations of said interface: TechDivision\Import\Prod...Subjects\VariantSubject.

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...
307
    }
308
309
    /**
310
     * Return's an array with the available stores.
311
     *
312
     * @return array The available stores
313
     */
314
    protected function getStores()
315
    {
316
        return $this->getSubject()->getStores();
0 ignored issues
show
Bug introduced by
The method getStores() does not seem to exist on object<TechDivision\Impo...jects\SubjectInterface>.

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...
317
    }
318
319
    /**
320
     * Return's the first EAV attribute for the passed attribute code.
321
     *
322
     * @param string $attributeCode The attribute code
323
     *
324
     * @return array The array with the EAV attribute
325
     */
326
    protected function getEavAttributeByAttributeCode($attributeCode)
327
    {
328
        return $this->getSubject()->getEavAttributeByAttributeCode($attributeCode);
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 getEavAttributeByAttributeCode() does only exist in the following implementations of said interface: TechDivision\Import\Prod...\AbstractProductSubject, TechDivision\Import\Product\Subjects\BunchSubject, TechDivision\Import\Prod...Subjects\VariantSubject, 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...
329
    }
330
331
    /**
332
     * Persist's the passed product super attribute data and return's the ID.
333
     *
334
     * @param array $productSuperAttribute The product super attribute data to persist
335
     *
336
     * @return void
337
     */
338
    protected function persistProductSuperAttribute($productSuperAttribute)
339
    {
340
        return $this->getProductVariantProcessor()->persistProductSuperAttribute($productSuperAttribute);
341
    }
342
343
    /**
344
     * Persist's the passed product super attribute label data and return's the ID.
345
     *
346
     * @param array $productSuperAttributeLabel The product super attribute label data to persist
347
     *
348
     * @return void
349
     */
350
    protected function persistProductSuperAttributeLabel($productSuperAttributeLabel)
351
    {
352
        return $this->getProductVariantProcessor()->persistProductSuperAttributeLabel($productSuperAttributeLabel);
353
    }
354
}
355