Completed
Push — master ( 3dd64b...2f28bf )
by Tim
11s
created

UrlRewriteObserver::prepareUrlRewrites()   B

Complexity

Conditions 3
Paths 4

Size

Total Lines 29
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 12
CRAP Score 3

Importance

Changes 0
Metric Value
dl 0
loc 29
ccs 12
cts 12
cp 1
rs 8.8571
c 0
b 0
f 0
cc 3
eloc 11
nc 4
nop 0
crap 3
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\Observers\AbstractProductImportObserver;
28
use TechDivision\Import\Product\Services\ProductBunchProcessorInterface;
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 URL key from the CSV file column that has to be processed by the observer.
51
     *
52
     * @var string
53
     */
54
    protected $urlKey;
55
56
    /**
57
     * The actual category ID to process.
58
     *
59
     * @var integer
60
     */
61
    protected $categoryId;
62
63
    /**
64
     * The actual entity ID to process.
65
     *
66
     * @var integer
67
     */
68
    protected $entityId;
69
70
    /**
71
     * The array with the URL rewrites that has to be created.
72
     *
73
     * @var array
74
     */
75
    protected $urlRewrites = array();
76
77
    /**
78
     * The product bunch processor instance.
79
     *
80
     * @var \TechDivision\Import\Product\Services\ProductBunchProcessorInterface
81
     */
82
    protected $productBunchProcessor;
83
84
    /**
85
     * Initialize the observer with the passed product bunch processor instance.
86
     *
87
     * @param \TechDivision\Import\Product\Services\ProductBunchProcessorInterface $productBunchProcessor The product bunch processor instance
88
     */
89 3
    public function __construct(ProductBunchProcessorInterface $productBunchProcessor)
90
    {
91 3
        $this->productBunchProcessor = $productBunchProcessor;
92 3
    }
93
94
    /**
95
     * Return's the product bunch processor instance.
96
     *
97
     * @return \TechDivision\Import\Services\ProductBunchProcessorInterface The product bunch processor instance
98
     */
99 3
    protected function getProductBunchProcessor()
100
    {
101 3
        return $this->productBunchProcessor;
102
    }
103
104
    /**
105
     * Process the observer's business logic.
106
     *
107
     * @return void
108
     */
109 3
    protected function process()
110
    {
111
112
        // query whether or not, we've found a new SKU => means we've found a new product
113 3
        if ($this->hasBeenProcessed($this->getValue(ColumnKeys::SKU))) {
114
            return;
115
        }
116
117
        // try to load the URL key, return immediately if not possible
118 3
        if ($this->hasValue(ColumnKeys::URL_KEY)) {
119 3
            $this->urlKey = $urlKey = $this->getValue(ColumnKeys::URL_KEY);
120
        } else {
121
            return;
122
        }
123
124
        // initialize the store view code
125 3
        $this->prepareStoreViewCode();
126
127
        // prepare the URL rewrites
128 3
        $this->prepareUrlRewrites();
129
130
        // iterate over the categories and create the URL rewrites
131 3
        foreach ($this->urlRewrites as $categoryId => $urlRewrite) {
132
            // initialize and persist the URL rewrite
133 3
            if ($urlRewrite = $this->initializeUrlRewrite($urlRewrite)) {
134
                // initialize URL rewrite and catagory ID
135 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...
136 3
                $this->entityId = $urlRewrite[MemberNames::ENTITY_ID];
137 3
                $this->urlRewriteId = $this->persistUrlRewrite($urlRewrite);
0 ignored issues
show
Bug introduced by
The property urlRewriteId does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
138
139
                // initialize and persist the URL rewrite product => category relation
140 3
                $urlRewriteProductCategory = $this->initializeUrlRewriteProductCategory(
141 3
                    $this->prepareUrlRewriteProductCategoryAttributes()
142
                );
143
144
                // persist the URL rewrite product category relation
145 3
                $this->persistUrlRewriteProductCategory($urlRewriteProductCategory);
146
            }
147
        }
148
149
        // if changed, override the URL key with the new one
150 3
        if ($urlKey !== $this->urlKey) {
151
            $this->setValue(ColumnKeys::URL_KEY, $this->urlKey);
152
        }
153 3
    }
154
155
    /**
156
     * Initialize the category product with the passed attributes and returns an instance.
157
     *
158
     * @param array $attr The category product attributes
159
     *
160
     * @return array The initialized category product
161
     */
162 2
    protected function initializeUrlRewrite(array $attr)
163
    {
164 2
        return $attr;
165
    }
166
167
    /**
168
     * Initialize the URL rewrite product => category relation with the passed attributes
169
     * and returns an instance.
170
     *
171
     * @param array $attr The URL rewrite product => category relation attributes
172
     *
173
     * @return array The initialized URL rewrite product => category relation
174
     */
175 2
    protected function initializeUrlRewriteProductCategory($attr)
176
    {
177 2
        return $attr;
178
    }
179
180
    /**
181
     * Prepare's the URL rewrites that has to be created/updated.
182
     *
183
     * @return void
184
     */
185 3
    protected function prepareUrlRewrites()
186
    {
187
188
        // (re-)initialize the array for the URL rewrites
189 3
        $this->urlRewrites = array();
190
191
        // load the root category, because we need that to create the default product URL rewrite
192 3
        $rootCategory = $this->getRootCategory();
193
194
        // query whether or not categories has to be used as product URL suffix
195 3
        $productCategoryIds = array();
196 3
        if ($this->getCoreConfigData(CoreConfigDataKeys::CATALOG_SEO_PRODUCT_USE_CATEGORIES, false)) {
197
            // if yes, add the category IDs of the products
198 3
            $productCategoryIds = $this->getProductCategoryIds();
199
        }
200
201
        // at least, add the root category ID to the category => product relations
202 3
        $productCategoryIds[$rootCategory[MemberNames::ENTITY_ID]] = $this->getLastEntityId();
203
204
        // prepare the URL rewrites
205 3
        foreach ($productCategoryIds as $categoryId => $entityId) {
206
            // set category/entity ID
207 3
            $this->categoryId = $categoryId;
208 3
            $this->entityId = $entityId;
0 ignored issues
show
Documentation Bug introduced by
The property $entityId was declared of type integer, but $entityId 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...
209
210
            // prepare the attributes for each URL rewrite
211 3
            $this->urlRewrites[$categoryId] = $this->prepareAttributes();
212
        }
213 3
    }
214
215
    /**
216
     * Prepare the attributes of the entity that has to be persisted.
217
     *
218
     * @return array The prepared attributes
219
     */
220 3
    protected function prepareAttributes()
221
    {
222
223
        // load the store ID to use
224 3
        $storeId = $this->getRowStoreId(StoreViewCodes::ADMIN);
225
226
        // load the category to create the URL rewrite for
227 3
        $category = $this->getCategory($this->categoryId);
228
229
        // initialize the values
230 3
        $requestPath = $this->prepareRequestPath($category);
231 3
        $targetPath = $this->prepareTargetPath($category);
232 3
        $metadata = serialize($this->prepareMetadata($category));
233
234
        // return the prepared URL rewrite
235 3
        return $this->initializeEntity(
236
            array(
237 3
                MemberNames::ENTITY_TYPE      => UrlRewriteObserver::ENTITY_TYPE,
238 3
                MemberNames::ENTITY_ID        => $this->entityId,
239 3
                MemberNames::REQUEST_PATH     => $requestPath,
240 3
                MemberNames::TARGET_PATH      => $targetPath,
241 3
                MemberNames::REDIRECT_TYPE    => 0,
242 3
                MemberNames::STORE_ID         => $storeId,
243 3
                MemberNames::DESCRIPTION      => null,
244 3
                MemberNames::IS_AUTOGENERATED => 1,
245 3
                MemberNames::METADATA         => $metadata
246
            )
247
        );
248
    }
249
250
    /**
251
     * Prepare's the URL rewrite product => category relation attributes.
252
     *
253
     * @return arry The prepared attributes
254
     */
255 3
    protected function prepareUrlRewriteProductCategoryAttributes()
256
    {
257
258
        // return the prepared product
259 3
        return $this->initializeEntity(
260
            array(
261 3
                MemberNames::PRODUCT_ID => $this->entityId,
262 3
                MemberNames::CATEGORY_ID => $this->categoryId,
263 3
                MemberNames::URL_REWRITE_ID => $this->urlRewriteId
264
            )
265
        );
266
    }
267
268
    /**
269
     * Prepare's the target path for a URL rewrite.
270
     *
271
     * @param array $category The categroy with the URL path
272
     *
273
     * @return string The target path
274
     */
275 3
    protected function prepareTargetPath(array $category)
276
    {
277
278
        // load the actual entity ID
279 3
        $lastEntityId = $this->getLastEntityId();
280
281
        // query whether or not, the category is the root category
282 3
        if ($this->isRootCategory($category)) {
283 3
            $targetPath = sprintf('catalog/product/view/id/%d', $lastEntityId);
284
        } else {
285 2
            $targetPath = sprintf('catalog/product/view/id/%d/category/%d', $lastEntityId, $category[MemberNames::ENTITY_ID]);
286
        }
287
288
        // return the target path
289 3
        return $targetPath;
290
    }
291
292
    /**
293
     * Prepare's the request path for a URL rewrite or the target path for a 301 redirect.
294
     *
295
     * @param array $category The categroy with the URL path
296
     *
297
     * @return string The request path
298
     * @throws \RuntimeException Is thrown, if the passed category has no or an empty value for attribute "url_path"
299
     */
300 3
    protected function prepareRequestPath(array $category)
301
    {
302
303
        // load the product URL suffix to use
304 3
        $urlSuffix = $this->getCoreConfigData(CoreConfigDataKeys::CATALOG_SEO_PRODUCT_URL_SUFFIX, '.html');
305
306
        // create a unique URL key, if this is a new URL rewrite
307 3
        $this->urlKey = $this->makeUrlKeyUnique($this->urlKey);
308
309
        // query whether or not, the category is the root category
310 3
        if ($this->isRootCategory($category)) {
311 3
            return sprintf('%s%s', $this->urlKey, $urlSuffix);
312
        } else {
313
            // query whether or not the category's "url_path" attribute, necessary to create a valid "request_path", is available
314 2
            if (isset($category[MemberNames::URL_PATH]) && $category[MemberNames::URL_PATH]) {
315 2
                return sprintf('%s/%s%s', $category[MemberNames::URL_PATH], $this->urlKey, $urlSuffix);
316
            }
317
        }
318
319
        // throw an exception if the category's "url_path" attribute is NOT available
320
        throw new \RuntimeException(
321
            sprintf(
322
                'Can\'t find mandatory attribute "%s" for category ID "%d", necessary to build a valid "request_path"',
323
                MemberNames::URL_PATH,
324
                $category[MemberNames::ENTITY_ID]
325
            )
326
        );
327
    }
328
329
    /**
330
     * Prepare's the URL rewrite's metadata with the passed category values.
331
     *
332
     * @param array $category The category used for preparation
333
     *
334
     * @return array The metadata
335
     */
336 3
    protected function prepareMetadata(array $category)
337
    {
338
339
        // initialize the metadata
340 3
        $metadata = array();
341
342
        // query whether or not, the passed category IS the root category
343 3
        if ($this->isRootCategory($category)) {
344 3
            return $metadata;
345
        }
346
347
        // if not, set the category ID in the metadata
348 2
        $metadata['category_id'] = $category[MemberNames::ENTITY_ID];
349
350
        // return the metadata
351 2
        return $metadata;
352
    }
353
354
    /**
355
     * Make's the passed URL key unique by adding the next number to the end.
356
     *
357
     * @param string $urlKey The URL key to make unique
358
     *
359
     * @return string The unique URL key
360
     */
361 3
    protected function makeUrlKeyUnique($urlKey)
362
    {
363
364
        // initialize the entity type ID
365 3
        $entityType = $this->getEntityType();
366 3
        $entityTypeId = $entityType[MemberNames::ENTITY_TYPE_ID];
367
368
        // initialize the query parameters
369 3
        $storeId = $this->getRowStoreId(StoreViewCodes::ADMIN);
370
371
        // initialize the counter
372 3
        $counter = 0;
373
374
        // initialize the counters
375 3
        $matchingCounters = array();
376 3
        $notMatchingCounters = array();
377
378
        // pre-initialze the URL key to query for
379 3
        $value = $urlKey;
380
381
        do {
382
            // try to load the attribute
383 3
            $productVarcharAttribute = $this->getProductBunchProcessor()
384 3
                                            ->loadProductVarcharAttributeByAttributeCodeAndEntityTypeIdAndStoreIdAndValue(
385 3
                                                MemberNames::URL_KEY,
386 3
                                                $entityTypeId,
387 3
                                                $storeId,
388 3
                                                $value
389
                                            );
390
391
            // try to load the product's URL key
392 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...
393
                // this IS the URL key of the passed entity
394
                if ($this->isUrlKeyOf($productVarcharAttribute)) {
395
                    $matchingCounters[] = $counter;
396
                } else {
397
                    $notMatchingCounters[] = $counter;
398
                }
399
400
                // prepare the next URL key to query for
401
                $value = sprintf('%s-%d', $urlKey, ++$counter);
402
            }
403
0 ignored issues
show
Coding Style introduced by
Blank line found at end of control structure
Loading history...
404 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...
405
406
        // sort the array ascending according to the counter
407 3
        asort($matchingCounters);
408 3
        asort($notMatchingCounters);
409
410
        // this IS the URL key of the passed entity => we've an UPDATE
411 3
        if (sizeof($matchingCounters) > 0) {
412
            // load highest counter
413
            $counter = end($matchingCounters);
414
            // if the counter is > 0, we've to append it to the new URL key
415
            if ($counter > 0) {
416
                $urlKey = sprintf('%s-%d', $urlKey, $counter);
417
            }
418 3
        } elseif (sizeof($notMatchingCounters) > 0) {
419
            // create a new URL key by raising the counter
420
            $newCounter = end($notMatchingCounters);
421
            $urlKey = sprintf('%s-%d', $urlKey, ++$newCounter);
422
        }
423
424
        // return the passed URL key, if NOT
425 3
        return $urlKey;
426
    }
427
428
    /**
429
     * Return's TRUE, if the passed URL key varchar value IS related with the actual PK.
430
     *
431
     * @param array $productVarcharAttribute The varchar value to check
432
     *
433
     * @return boolean TRUE if the URL key is related, else FALSE
434
     */
435
    protected function isUrlKeyOf(array $productVarcharAttribute)
436
    {
437
        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...
438
    }
439
440
    /**
441
     * Return's the entity type for the configured entity type code.
442
     *
443
     * @return array The requested entity type
444
     * @throws \Exception Is thrown, if the requested entity type is not available
445
     */
446 3
    protected function getEntityType()
447
    {
448 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...
449
    }
450
451
    /**
452
     * Return's the root category for the actual view store.
453
     *
454
     * @return array The store's root category
455
     * @throws \Exception Is thrown if the root category for the passed store code is NOT available
456
     */
457 3
    protected function getRootCategory()
458
    {
459 3
        return $this->getSubject()->getRootCategory();
460
    }
461
462
    /**
463
     * Return's TRUE if the passed category IS the root category, else FALSE.
464
     *
465
     * @param array $category The category to query
466
     *
467
     * @return boolean TRUE if the passed category IS the root category
468
     */
469 3
    protected function isRootCategory(array $category)
470
    {
471
472
        // load the root category
473 3
        $rootCategory = $this->getRootCategory();
474
475
        // compare the entity IDs and return the result
476 3
        return $rootCategory[MemberNames::ENTITY_ID] === $category[MemberNames::ENTITY_ID];
477
    }
478
479
    /**
480
     * Return's the list with category IDs the product is related with.
481
     *
482
     * @return array The product's category IDs
483
     */
484 3
    protected function getProductCategoryIds()
485
    {
486 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...
487
    }
488
489
    /**
490
     * Return's the category with the passed ID.
491
     *
492
     * @param integer $categoryId The ID of the category to return
493
     *
494
     * @return array The category data
495
     */
496 2
    protected function getCategory($categoryId)
497
    {
498 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...
499
    }
500
501
    /**
502
     * Persist's the URL rewrite with the passed data.
503
     *
504
     * @param array $row The URL rewrite to persist
505
     *
506
     * @return string The ID of the persisted entity
507
     */
508 3
    protected function persistUrlRewrite($row)
509
    {
510 3
        return $this->getProductBunchProcessor()->persistUrlRewrite($row);
511
    }
512
513
    /**
514
     * Persist's the URL rewrite product => category relation with the passed data.
515
     *
516
     * @param array $row The URL rewrite product => category relation to persist
517
     *
518
     * @return void
519
     */
520 3
    protected function persistUrlRewriteProductCategory($row)
521
    {
522 3
        return $this->getProductBunchProcessor()->persistUrlRewriteProductCategory($row);
523
    }
524
}
525