Completed
Pull Request — master (#79)
by Tim
02:50
created

UrlRewriteObserver::isNotVisible()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 2
cts 2
cp 1
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 0
crap 1
1
<?php
2
3
/**
4
 * TechDivision\Import\Product\Observers\UrlRewriteObserver
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\Utils\StoreViewCodes;
24
use TechDivision\Import\Product\Utils\ColumnKeys;
25
use TechDivision\Import\Product\Utils\MemberNames;
26
use TechDivision\Import\Product\Utils\CoreConfigDataKeys;
27
use TechDivision\Import\Product\Services\ProductBunchProcessorInterface;
28
use TechDivision\Import\Product\Utils\VisibilityKeys;
29
30
/**
31
 * Observer that creates/updates the product's URL rewrites.
32
 *
33
 * @author    Tim Wagner <[email protected]>
34
 * @copyright 2016 TechDivision GmbH <[email protected]>
35
 * @license   http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
36
 * @link      https://github.com/techdivision/import-product
37
 * @link      http://www.techdivision.com
38
 */
39
class UrlRewriteObserver extends AbstractProductImportObserver
40
{
41
42
    /**
43
     * The entity type to load the URL rewrites for.
44
     *
45
     * @var string
46
     */
47
    const ENTITY_TYPE = 'product';
48
49
    /**
50
     * The key for the category in the metadata.
51
     *
52
     * @var string
53
     */
54
    const CATEGORY_ID = 'category_id';
55
56
    /**
57
     * The URL key from the CSV file column that has to be processed by the observer.
58
     *
59
     * @var string
60
     */
61
    protected $urlKey;
62
63
    /**
64
     * The actual category ID to process.
65
     *
66
     * @var integer
67
     */
68
    protected $categoryId;
69
70
    /**
71
     * The actual entity ID to process.
72
     *
73
     * @var integer
74
     */
75
    protected $entityId;
76
77
    /**
78
     * The ID of the recently created URL rewrite.
79
     *
80
     * @var integer
81
     */
82
    protected $urlRewriteId;
83
84
    /**
85
     * The array with the URL rewrites that has to be created.
86
     *
87
     * @var array
88
     */
89
    protected $urlRewrites = array();
90
91
    /**
92
     * The array with the category IDs related with the product.
93
     *
94
     * @var array
95
     */
96
    protected $productCategoryIds = array();
97
98
    /**
99
     * The product bunch processor instance.
100
     *
101
     * @var \TechDivision\Import\Product\Services\ProductBunchProcessorInterface
102
     */
103
    protected $productBunchProcessor;
104
105
    /**
106
     * Initialize the observer with the passed product bunch processor instance.
107
     *
108
     * @param \TechDivision\Import\Product\Services\ProductBunchProcessorInterface $productBunchProcessor The product bunch processor instance
109
     */
110 3
    public function __construct(ProductBunchProcessorInterface $productBunchProcessor)
111
    {
112 3
        $this->productBunchProcessor = $productBunchProcessor;
113 3
    }
114
115
    /**
116
     * Return's the product bunch processor instance.
117
     *
118
     * @return \TechDivision\Import\Product\Services\ProductBunchProcessorInterface The product bunch processor instance
119
     */
120 3
    protected function getProductBunchProcessor()
121
    {
122 3
        return $this->productBunchProcessor;
123
    }
124
125
    /**
126
     * Process the observer's business logic.
127
     *
128
     * @return void
129
     */
130 3
    protected function process()
131
    {
132
133
        // initialize the store view code
134 3
        $this->getSubject()->prepareStoreViewCode();
135
136
        // load the SKU and the store view code
137 3
        $sku = $this->getValue($this->getPrimaryKeyColumnName());
138 3
        $storeViewCode = $this->getSubject()->getStoreViewCode();
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 getStoreViewCode() does only exist in the following implementations of said interface: TechDivision\Import\Prod...\AbstractProductSubject, TechDivision\Import\Product\Subjects\BunchSubject, TechDivision\Import\Subjects\AbstractEavSubject, TechDivision\Import\Subjects\AbstractSubject, TechDivision\Import\Subjects\MoveFilesSubject.

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...
139
140
        // query whether or not the row has already been processed
141 3
        if ($this->storeViewHasBeenProcessed($sku, $storeViewCode)) {
142
            // log a message
143
            $this->getSubject()
144
                 ->getSystemLogger()
145
                 ->warning(
146
                     sprintf(
147
                         'URL rewrites for SKU + store view "%s" + "%s" has already been processed',
148
                         $sku,
149
                         $storeViewCode
150
                     )
151
                 );
152
153
            // return immediately
154
            return;
155
        };
156
157
        // try to load the URL key, return immediately if not possible
158 3
        if ($this->hasValue(ColumnKeys::URL_KEY)) {
159 3
            $this->urlKey = $urlKey = $this->getValue(ColumnKeys::URL_KEY);
160
        } else {
161
            return;
162
        }
163
164
        // prepare the URL rewrites
165 3
        $this->prepareUrlRewrites();
166
167
        // do NOT create new URL rewrites, if the product is NOT visible (any more), BUT
168
        // handle existing URL rewrites, e. g. to remove and clean up the URL rewrites
169 3
        if ($this->isNotVisible()) {
170
            return;
171
        }
172
173
        // iterate over the categories and create the URL rewrites
174 3
        foreach ($this->urlRewrites as $categoryId => $urlRewrite) {
175
            // initialize and persist the URL rewrite
176 3
            if ($urlRewrite = $this->initializeUrlRewrite($urlRewrite)) {
177
                // initialize URL rewrite and catagory ID
178 3
                $this->categoryId = $categoryId;
0 ignored issues
show
Documentation Bug introduced by
It seems like $categoryId can also be of type string. However, the property $categoryId is declared as type integer. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
179 3
                $this->entityId = $urlRewrite[MemberNames::ENTITY_ID];
180 3
                $this->urlRewriteId = $this->persistUrlRewrite($urlRewrite);
0 ignored issues
show
Documentation Bug introduced by
The property $urlRewriteId was declared of type integer, but $this->persistUrlRewrite($urlRewrite) 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...
181
182
                // initialize and persist the URL rewrite product => category relation
183 3
                $urlRewriteProductCategory = $this->initializeUrlRewriteProductCategory(
184 3
                    $this->prepareUrlRewriteProductCategoryAttributes()
185
                );
186
187
                // persist the URL rewrite product category relation
188 3
                $this->persistUrlRewriteProductCategory($urlRewriteProductCategory);
189
            }
190
        }
191
192
        // if changed, e. g. the request path of the URL rewrite has been suffixed with a
193
        // number because another one with the same request path for an other entity and
194
        // a different store view already exists, then override the old URL key with the
195
        // new generated one
196 3
        if ($urlKey !== $this->urlKey) {
197
            $this->setValue(ColumnKeys::URL_KEY, $this->urlKey);
198
        }
199 3
    }
200
201
    /**
202
     * Initialize the category product with the passed attributes and returns an instance.
203
     *
204
     * @param array $attr The category product attributes
205
     *
206
     * @return array The initialized category product
207
     */
208 2
    protected function initializeUrlRewrite(array $attr)
209
    {
210 2
        return $attr;
211
    }
212
213
    /**
214
     * Initialize the URL rewrite product => category relation with the passed attributes
215
     * and returns an instance.
216
     *
217
     * @param array $attr The URL rewrite product => category relation attributes
218
     *
219
     * @return array The initialized URL rewrite product => category relation
220
     */
221 2
    protected function initializeUrlRewriteProductCategory($attr)
222
    {
223 2
        return $attr;
224
    }
225
226
    /**
227
     * Prepare's the URL rewrites that has to be created/updated.
228
     *
229
     * @return void
230
     */
231 3
    protected function prepareUrlRewrites()
232
    {
233
234
        // (re-)initialize the array for the URL rewrites and the product category IDs
235 3
        $this->urlRewrites = array();
236 3
        $this->productCategoryIds = array();
237
238
        // load the root category, because we need that to create the default product URL rewrite
239 3
        $rootCategory = $this->getRootCategory();
240
241
        // query whether or not categories has to be used as product URL suffix
242 3
        if ($this->getSubject()->getCoreConfigData(CoreConfigDataKeys::CATALOG_SEO_PRODUCT_USE_CATEGORIES, false)) {
243
            // if yes, add the category IDs of the products
244 3
            foreach ($this->getProductCategoryIds() as $categoryId => $entityId) {
245 3
                $this->resolveCategoryIds($categoryId, $entityId, true);
246
            }
247
        }
248
249
        // at least, add the root category ID to the category => product relations
250 3
        $this->productCategoryIds[$rootCategory[MemberNames::ENTITY_ID]] = $this->getSubject()->getLastEntityId();
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 getLastEntityId() does only exist in the following implementations of said interface: TechDivision\Import\Observers\EntitySubjectImpl, 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...
251
252
        // prepare the URL rewrites
253 3
        foreach ($this->productCategoryIds as $categoryId => $entityId) {
254
            // set category/entity ID
255 3
            $this->entityId = $entityId;
256 3
            $this->categoryId = $categoryId;
257
258
            // prepare the attributes for each URL rewrite
259 3
            $this->urlRewrites[$categoryId] = $this->prepareAttributes();
260
        }
261 3
    }
262
263
    /**
264
     * Resolve's the parent categories of the category with the passed ID and relate's
265
     * it with the product with the passed ID, if the category is top level OR has the
266
     * anchor flag set.
267
     *
268
     * @param integer $categoryId The ID of the category to resolve the parents
269
     * @param integer $entityId   The ID of the product entity to relate the category with
270
     * @param boolean $topLevel   TRUE if the passed category has top level, else FALSE
271
     *
272
     * @return void
273
     */
274 3
    protected function resolveCategoryIds($categoryId, $entityId, $topLevel = false)
275
    {
276
277
        // return immediately if this is the absolute root node
278 3
        if ((integer) $categoryId === 1) {
279 3
            return;
280
        }
281
282
        // load the data of the category with the passed ID
283 3
        $category = $this->getCategory($categoryId);
284
285
        // query whether or not the product has already been related
286 3
        if (!isset($this->productCategoryIds[$categoryId])) {
287 3
            if ($topLevel) {
288
                // relate it, if the category is top level
289 3
                $this->productCategoryIds[$categoryId] = $entityId;
290
            } elseif ((integer) $category[MemberNames::IS_ANCHOR] === 1) {
291
                // relate it, if the category is not top level, but has the anchor flag set
292
                $this->productCategoryIds[$categoryId] = $entityId;
293
            } else {
294
                $this->getSubject()
295
                     ->getSystemLogger()
296
                     ->debug(sprintf('Can\'t create URL rewrite for category "%s" because of missing anchor flag', $category[MemberNames::PATH]));
297
            }
298
        }
299
300
        // load the root category
301 3
        $rootCategory = $this->getRootCategory();
302
303
        // try to resolve the parent category IDs
304 3
        if ($rootCategory[MemberNames::ENTITY_ID] !== ($parentId = $category[MemberNames::PARENT_ID])) {
305 3
            $this->resolveCategoryIds($parentId, $entityId, false);
306
        }
307 3
    }
308
309
    /**
310
     * Prepare the attributes of the entity that has to be persisted.
311
     *
312
     * @return array The prepared attributes
313
     */
314 3
    protected function prepareAttributes()
315
    {
316
317
        // load the store ID to use
318 3
        $storeId = $this->getSubject()->getRowStoreId();
0 ignored issues
show
Bug introduced by
The method getRowStoreId() does not exist on TechDivision\Import\Subjects\SubjectInterface. Did you maybe mean getRow()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
319
320
        // load the category to create the URL rewrite for
321 3
        $category = $this->getCategory($this->categoryId);
322
323
        // initialize the values
324 3
        $requestPath = $this->prepareRequestPath($category);
325 3
        $targetPath = $this->prepareTargetPath($category);
326 3
        $metadata = serialize($this->prepareMetadata($category));
327
328
        // return the prepared URL rewrite
329 3
        return $this->initializeEntity(
330
            array(
331 3
                MemberNames::ENTITY_TYPE      => UrlRewriteObserver::ENTITY_TYPE,
332 3
                MemberNames::ENTITY_ID        => $this->entityId,
333 3
                MemberNames::REQUEST_PATH     => $requestPath,
334 3
                MemberNames::TARGET_PATH      => $targetPath,
335 3
                MemberNames::REDIRECT_TYPE    => 0,
336 3
                MemberNames::STORE_ID         => $storeId,
337 3
                MemberNames::DESCRIPTION      => null,
338 3
                MemberNames::IS_AUTOGENERATED => 1,
339 3
                MemberNames::METADATA         => $metadata
340
            )
341
        );
342
    }
343
344
    /**
345
     * Prepare's the URL rewrite product => category relation attributes.
346
     *
347
     * @return array The prepared attributes
348
     */
349 3
    protected function prepareUrlRewriteProductCategoryAttributes()
350
    {
351
352
        // return the prepared product
353 3
        return $this->initializeEntity(
354
            array(
355 3
                MemberNames::PRODUCT_ID => $this->entityId,
356 3
                MemberNames::CATEGORY_ID => $this->categoryId,
357 3
                MemberNames::URL_REWRITE_ID => $this->urlRewriteId
358
            )
359
        );
360
    }
361
362
    /**
363
     * Prepare's the target path for a URL rewrite.
364
     *
365
     * @param array $category The categroy with the URL path
366
     *
367
     * @return string The target path
368
     */
369 3
    protected function prepareTargetPath(array $category)
370
    {
371
372
        // load the actual entity ID
373 3
        $lastEntityId = $this->getLastEntityId();
0 ignored issues
show
Deprecated Code introduced by
The method TechDivision\Import\Obse...rver::getLastEntityId() has been deprecated with message: Will be removed with version 1.0.0, use subject method instead

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
374
375
        // query whether or not, the category is the root category
376 3
        if ($this->isRootCategory($category)) {
377 3
            $targetPath = sprintf('catalog/product/view/id/%d', $lastEntityId);
378
        } else {
379 2
            $targetPath = sprintf('catalog/product/view/id/%d/category/%d', $lastEntityId, $category[MemberNames::ENTITY_ID]);
380
        }
381
382
        // return the target path
383 3
        return $targetPath;
384
    }
385
386
    /**
387
     * Prepare's the request path for a URL rewrite or the target path for a 301 redirect.
388
     *
389
     * @param array $category The categroy with the URL path
390
     *
391
     * @return string The request path
392
     * @throws \RuntimeException Is thrown, if the passed category has no or an empty value for attribute "url_path"
393
     */
394 3
    protected function prepareRequestPath(array $category)
395
    {
396
397
        // load the product URL suffix to use
398 3
        $urlSuffix = $this->getCoreConfigData(CoreConfigDataKeys::CATALOG_SEO_PRODUCT_URL_SUFFIX, '.html');
0 ignored issues
show
Deprecated Code introduced by
The method TechDivision\Import\Obse...er::getCoreConfigData() has been deprecated with message: Will be removed with version 1.0.0, use subject method instead

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
399
400
        // create a unique URL key, if this is a new URL rewrite
401 3
        $this->urlKey = $this->makeUrlKeyUnique($this->urlKey);
402
403
        // query whether or not, the category is the root category
404 3
        if ($this->isRootCategory($category)) {
405 3
            return sprintf('%s%s', $this->urlKey, $urlSuffix);
406
        } else {
407
            // query whether or not the category's "url_path" attribute, necessary to create a valid "request_path", is available
408 2
            if (isset($category[MemberNames::URL_PATH]) && $category[MemberNames::URL_PATH]) {
409 2
                return sprintf('%s/%s%s', $category[MemberNames::URL_PATH], $this->urlKey, $urlSuffix);
410
            }
411
        }
412
413
        // throw an exception if the category's "url_path" attribute is NOT available
414
        throw new \RuntimeException(
415
            sprintf(
416
                'Can\'t find mandatory attribute "%s" for category ID "%d", necessary to build a valid "request_path"',
417
                MemberNames::URL_PATH,
418
                $category[MemberNames::ENTITY_ID]
419
            )
420
        );
421
    }
422
423
    /**
424
     * Prepare's the URL rewrite's metadata with the passed category values.
425
     *
426
     * @param array $category The category used for preparation
427
     *
428
     * @return array The metadata
429
     */
430 3
    protected function prepareMetadata(array $category)
431
    {
432
433
        // initialize the metadata
434 3
        $metadata = array();
435
436
        // query whether or not, the passed category IS the root category
437 3
        if ($this->isRootCategory($category)) {
438 3
            return $metadata;
439
        }
440
441
        // if not, set the category ID in the metadata
442 2
        $metadata[UrlRewriteObserver::CATEGORY_ID] = $category[MemberNames::ENTITY_ID];
443
444
        // return the metadata
445 2
        return $metadata;
446
    }
447
448
    /**
449
     * Make's the passed URL key unique by adding the next number to the end.
450
     *
451
     * @param string $urlKey The URL key to make unique
452
     *
453
     * @return string The unique URL key
454
     */
455 3
    protected function makeUrlKeyUnique($urlKey)
456
    {
457
458
        // initialize the entity type ID
459 3
        $entityType = $this->getEntityType();
460 3
        $entityTypeId = $entityType[MemberNames::ENTITY_TYPE_ID];
461
462
        // initialize the query parameters
463 3
        $storeId = $this->getRowStoreId(StoreViewCodes::ADMIN);
0 ignored issues
show
Deprecated Code introduced by
The method TechDivision\Import\Obse...server::getRowStoreId() has been deprecated with message: Will be removed with version 1.0.0, use subject method instead

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
464
465
        // initialize the counter
466 3
        $counter = 0;
467
468
        // initialize the counters
469 3
        $matchingCounters = array();
470 3
        $notMatchingCounters = array();
471
472
        // pre-initialze the URL key to query for
473 3
        $value = $urlKey;
474
475
        do {
476
            // try to load the attribute
477 3
            $productVarcharAttribute = $this->getProductBunchProcessor()
478 3
                                            ->loadProductVarcharAttributeByAttributeCodeAndEntityTypeIdAndStoreIdAndValue(
479 3
                                                MemberNames::URL_KEY,
480 3
                                                $entityTypeId,
481 3
                                                $storeId,
482 3
                                                $value
483
                                            );
484
485
            // try to load the product's URL key
486 3
            if ($productVarcharAttribute) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $productVarcharAttribute of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
487
                // this IS the URL key of the passed entity
488
                if ($this->isUrlKeyOf($productVarcharAttribute)) {
489
                    $matchingCounters[] = $counter;
490
                } else {
491
                    $notMatchingCounters[] = $counter;
492
                }
493
494
                // prepare the next URL key to query for
495
                $value = sprintf('%s-%d', $urlKey, ++$counter);
496
            }
497
0 ignored issues
show
Coding Style introduced by
Blank line found at end of control structure
Loading history...
498 3
        } while ($productVarcharAttribute);
0 ignored issues
show
Bug Best Practice introduced by
The expression $productVarcharAttribute of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
499
500
        // sort the array ascending according to the counter
501 3
        asort($matchingCounters);
502 3
        asort($notMatchingCounters);
503
504
        // this IS the URL key of the passed entity => we've an UPDATE
505 3
        if (sizeof($matchingCounters) > 0) {
506
            // load highest counter
507
            $counter = end($matchingCounters);
508
            // if the counter is > 0, we've to append it to the new URL key
509
            if ($counter > 0) {
510
                $urlKey = sprintf('%s-%d', $urlKey, $counter);
511
            }
512 3
        } elseif (sizeof($notMatchingCounters) > 0) {
513
            // create a new URL key by raising the counter
514
            $newCounter = end($notMatchingCounters);
515
            $urlKey = sprintf('%s-%d', $urlKey, ++$newCounter);
516
        }
517
518
        // return the passed URL key, if NOT
519 3
        return $urlKey;
520
    }
521
522 3
    protected function isNotVisible()
0 ignored issues
show
Coding Style introduced by
Missing function doc comment
Loading history...
523
    {
524 3
        return $this->getVisibilityIdMapping() === VisibilityKeys::VISIBILITY_NOT_VISIBLE;
525
    }
526
527
    /**
528
     * Return's the visibility for the passed entity ID, if it already has been mapped. The mapping will be created
529
     * by calling <code>\TechDivision\Import\Product\Subjects\BunchSubject::getVisibilityIdByValue</code> which will
530
     * be done by the <code>\TechDivision\Import\Product\Callbacks\VisibilityCallback</code>.
531
     *
532
     * @return integer The visibility ID
533
     * @throws \Exception Is thrown, if the entity ID has not been mapped
534
     */
535 3
    protected function getVisibilityIdMapping()
536
    {
537 3
        return $this->getSubject()->getVisibilityIdMapping();
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 getVisibilityIdMapping() does only exist in the following implementations of said interface: TechDivision\Import\Product\Subjects\BunchSubject.

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...
538
    }
539
540
    /**
541
     * Return's TRUE, if the passed URL key varchar value IS related with the actual PK.
542
     *
543
     * @param array $productVarcharAttribute The varchar value to check
544
     *
545
     * @return boolean TRUE if the URL key is related, else FALSE
546
     */
547
    protected function isUrlKeyOf(array $productVarcharAttribute)
548
    {
549
        return $this->getSubject()->isUrlKeyOf($productVarcharAttribute);
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 isUrlKeyOf() does only exist in the following implementations of said interface: TechDivision\Import\Product\Subjects\BunchSubject.

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...
550
    }
551
552
    /**
553
     * Return's the entity type for the configured entity type code.
554
     *
555
     * @return array The requested entity type
556
     * @throws \Exception Is thrown, if the requested entity type is not available
557
     */
558 3
    protected function getEntityType()
559
    {
560 3
        return $this->getSubject()->getEntityType();
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 getEntityType() does only exist in the following implementations of said interface: TechDivision\Import\Product\Subjects\BunchSubject.

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...
561
    }
562
563
    /**
564
     * Return's the root category for the actual view store.
565
     *
566
     * @return array The store's root category
567
     * @throws \Exception Is thrown if the root category for the passed store code is NOT available
568
     */
569 3
    protected function getRootCategory()
570
    {
571 3
        return $this->getSubject()->getRootCategory();
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 getRootCategory() does only exist in the following implementations of said interface: TechDivision\Import\Prod...\AbstractProductSubject, TechDivision\Import\Product\Subjects\BunchSubject, TechDivision\Import\Subjects\AbstractEavSubject, TechDivision\Import\Subjects\AbstractSubject, TechDivision\Import\Subjects\MoveFilesSubject.

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...
572
    }
573
574
    /**
575
     * Return's TRUE if the passed category IS the root category, else FALSE.
576
     *
577
     * @param array $category The category to query
578
     *
579
     * @return boolean TRUE if the passed category IS the root category
580
     */
581 3
    protected function isRootCategory(array $category)
582
    {
583
584
        // load the root category
585 3
        $rootCategory = $this->getRootCategory();
586
587
        // compare the entity IDs and return the result
588 3
        return $rootCategory[MemberNames::ENTITY_ID] === $category[MemberNames::ENTITY_ID];
589
    }
590
591
    /**
592
     * Return's the list with category IDs the product is related with.
593
     *
594
     * @return array The product's category IDs
595
     */
596 3
    protected function getProductCategoryIds()
597
    {
598 3
        return $this->getSubject()->getProductCategoryIds();
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 getProductCategoryIds() does only exist in the following implementations of said interface: TechDivision\Import\Product\Subjects\BunchSubject.

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...
599
    }
600
601
    /**
602
     * Return's the category with the passed ID.
603
     *
604
     * @param integer $categoryId The ID of the category to return
605
     *
606
     * @return array The category data
607
     */
608 2
    protected function getCategory($categoryId)
609
    {
610 2
        return $this->getSubject()->getCategory($categoryId);
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 getCategory() does only exist in the following implementations of said interface: TechDivision\Import\Prod...\AbstractProductSubject, TechDivision\Import\Product\Subjects\BunchSubject.

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...
611
    }
612
613
    /**
614
     * Persist's the URL rewrite with the passed data.
615
     *
616
     * @param array $row The URL rewrite to persist
617
     *
618
     * @return string The ID of the persisted entity
619
     */
620 3
    protected function persistUrlRewrite($row)
621
    {
622 3
        return $this->getProductBunchProcessor()->persistUrlRewrite($row);
623
    }
624
625
    /**
626
     * Persist's the URL rewrite product => category relation with the passed data.
627
     *
628
     * @param array $row The URL rewrite product => category relation to persist
629
     *
630
     * @return void
631
     */
632 3
    protected function persistUrlRewriteProductCategory($row)
633
    {
634 3
        return $this->getProductBunchProcessor()->persistUrlRewriteProductCategory($row);
635
    }
636
637
    /**
638
     * Return's the column name that contains the primary key.
639
     *
640
     * @return string the column name that contains the primary key
641
     */
642 3
    protected function getPrimaryKeyColumnName()
643
    {
644 3
        return ColumnKeys::SKU;
645
    }
646
647
    /**
648
     * Queries whether or not the passed SKU and store view code has already been processed.
649
     *
650
     * @param string $sku           The SKU to check been processed
651
     * @param string $storeViewCode The store view code to check been processed
652
     *
653
     * @return boolean TRUE if the SKU and store view code has been processed, else FALSE
654
     */
655 3
    protected function storeViewHasBeenProcessed($sku, $storeViewCode)
656
    {
657 3
        return $this->getSubject()->storeViewHasBeenProcessed($sku, $storeViewCode);
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 storeViewHasBeenProcessed() does only exist in the following implementations of said interface: TechDivision\Import\Prod...\AbstractProductSubject, TechDivision\Import\Product\Subjects\BunchSubject.

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...
658
    }
659
}
660