Completed
Push — 17.x ( e764b3 )
by Tim
03:33
created

UrlRewriteUpdateObserver::process()   C

Complexity

Conditions 13
Paths 13

Size

Total Lines 110

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 19
CRAP Score 50.2759

Importance

Changes 0
Metric Value
dl 0
loc 110
rs 5.2933
c 0
b 0
f 0
ccs 19
cts 48
cp 0.3958
cc 13
nc 13
nop 0
crap 50.2759

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
/**
4
 * TechDivision\Import\Product\UrlRewrite\Observers\UrlRewriteUpdateObserver
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-url-rewrite
18
 * @link      http://www.techdivision.com
19
 */
20
21
namespace TechDivision\Import\Product\UrlRewrite\Observers;
22
23
use TechDivision\Import\Utils\StoreViewCodes;
24
use TechDivision\Import\Product\Utils\CoreConfigDataKeys;
25
use TechDivision\Import\Product\UrlRewrite\Utils\MemberNames;
26
use TechDivision\Import\Product\UrlRewrite\Utils\ColumnKeys;
27
use TechDivision\Import\Product\UrlRewrite\Utils\ConfigurationKeys;
28
29
/**
30
 * Observer that creates/updates the product's URL rewrites.
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-url-rewrite
36
 * @link      http://www.techdivision.com
37
 */
38
class UrlRewriteUpdateObserver extends UrlRewriteObserver
39
{
40
41
    /**
42
     * Array with the existing URL rewrites of the actual product.
43
     *
44
     * @var array
45
     */
46
    protected $existingUrlRewrites = array();
47
48
    /**
49
     * Process the observer's business logic.
50
     *
51
     * @return void
52
     * @see \TechDivision\Import\Product\UrlRewrite\Observers\UrlRewriteObserver::process()
53
     */
54 1
    protected function process()
55
    {
56
57
        // process the new URL rewrites first
58 1
        parent::process();
59
60
        // load the root category
61 1
        $rootCategory = $this->getRootCategory();
62
63
        // create redirect URL rewrites for the existing URL rewrites
64 1
        foreach ($this->existingUrlRewrites as $existingUrlRewrite) {
65
            // if the URL rewrite has been created manually
66 1
            if ((integer) $existingUrlRewrite[MemberNames::IS_AUTOGENERATED] === 0) {
67
                // do NOTHING, because someone really WANTED to create THIS redirect
68
                continue;
69
            }
70
71
            // query whether or not 301 redirects have to be created, so don't create redirects
72
            // if the product is NOT visible or the rewrite history has been deactivated
73 1
            if ($this->isVisible() && $this->getSubject()->getCoreConfigData(CoreConfigDataKeys::CATALOG_SEO_SAVE_REWRITES_HISTORY, true)) {
74
                // if the URL rewrite already IS a redirect
75 1
                if ((integer) $existingUrlRewrite[MemberNames::REDIRECT_TYPE] !== 0) {
76
                    // do NOT create another redirect or update the actual one
77
                    continue;
78
                }
79
80
                // initialize the data with the URL rewrites new 301 configuration
81 1
                $attr = array(MemberNames::REDIRECT_TYPE => 301);
82
83
                // initialize the category with the root category
84 1
                $category = $rootCategory;
85
86
                // load the metadata from the existing URL rewrite
87 1
                $metadata = $this->getMetadata($existingUrlRewrite);
88
89
                // query whether or not the URL key of the existing URL rewrite has changed
90 1
                if (is_array($metadata) && isset($metadata[UrlRewriteObserver::CATEGORY_ID])) {
91 1
                    if (isset($this->urlRewrites[$metadata[UrlRewriteObserver::CATEGORY_ID]])) {
92
                        try {
93
                            // if yes, try to load the original category and OVERRIDE the default category
94 1
                            $category = $this->getCategory($metadata[UrlRewriteObserver::CATEGORY_ID], $this->getValue(ColumnKeys::STORE_VIEW_CODE));
95
                        } catch (\Exception $e) {
96
                            // if the old category can NOT be loaded, remove the
97
                            // category ID from the URL rewrites metadata
98
                            $attr[MemberNames::METADATA] = null;
99
100
                            // finally log a warning that the old category is not available ony more
101
                            $this->getSubject()
102
                                 ->getSystemLogger()
103
                                 ->warning(
104
                                     sprintf(
105
                                         'Category with ID "%d" is not longer available for URL rewrite with ID "%d"',
106
                                         $metadata[UrlRewriteObserver::CATEGORY_ID],
107
                                         $existingUrlRewrite[MemberNames::URL_REWRITE_ID]
108
                                     )
109
                                 );
110
                        }
111
                    }
112
                }
113
114
                // load target path/metadata for the actual category
115 1
                $targetPath = $this->prepareRequestPath($category);
116
117
                // skip update of URL rewrite, if resulting new target path EQUALS old request path
118 1
                if ($targetPath === $existingUrlRewrite[MemberNames::REQUEST_PATH]) {
119
                    // finally log a warning that the old category is not available ony more
120
                    $this->getSubject()
121
                         ->getSystemLogger()
122
                         ->warning(
123
                             sprintf(
124
                                 'New target path "%s" eqals request path for URL rewrite with ID "%d"',
125
                                 $existingUrlRewrite[MemberNames::REQUEST_PATH],
126
                                 $existingUrlRewrite[MemberNames::URL_REWRITE_ID]
127
                             )
128
                         );
129
130
                    // stop processing the URL rewrite
131
                    continue;
132
                }
133
134
                // set the target path
135 1
                $attr[MemberNames::TARGET_PATH] = $targetPath;
136
137
                // merge and return the prepared URL rewrite
138 1
                $existingUrlRewrite = $this->mergeEntity($existingUrlRewrite, $attr);
139
140
                // create the URL rewrite
141 1
                $this->persistUrlRewrite($existingUrlRewrite);
142
            } else {
143
                // query whether or not the URL rewrite has to be removed
144
                if ($this->getSubject()->getConfiguration()->hasParam(ConfigurationKeys::CLEAN_UP_URL_REWRITES) &&
145
                    $this->getSubject()->getConfiguration()->getParam(ConfigurationKeys::CLEAN_UP_URL_REWRITES)
146
                ) {
147
                    // delete the existing URL rewrite
148
                    $this->deleteUrlRewrite($existingUrlRewrite);
149
150
                    // log a message, that old URL rewrites have been cleaned-up
151
                    $this->getSubject()
152
                         ->getSystemLogger()
153
                         ->warning(
154
                             sprintf(
155
                                 'Cleaned-up %d URL rewrite "%s" for product with SKU "%s"',
156
                                 $existingUrlRewrite[MemberNames::REQUEST_PATH],
157
                                 $this->getValue(ColumnKeys::SKU)
158
                             )
159
                         );
160
                }
161
            }
162
        }
163 1
    }
164
165
    /**
166
     * Remove's the passed URL rewrite from the existing one's.
167
     *
168
     * @param array $urlRewrite The URL rewrite to remove
169
     *
170
     * @return void
171
     */
172
    protected function removeExistingUrlRewrite(array $urlRewrite)
173
    {
174
175
        // load request path
176
        $requestPath = $urlRewrite[MemberNames::REQUEST_PATH];
177
178
        // query whether or not the URL rewrite exists and remove it, if available
179
        if (isset($this->existingUrlRewrites[$requestPath])) {
180
            unset($this->existingUrlRewrites[$requestPath]);
181
        }
182
    }
183
184
    /**
185
     * Prepare's the URL rewrites that has to be created/updated.
186
     *
187
     * @return void
188
     * @see \TechDivision\Import\Product\UrlRewrite\Observers\UrlRewriteObserver::prepareUrlRewrites()
189
     */
190 1
    protected function prepareUrlRewrites()
191
    {
192
193
        // (re-)initialize the array for the existing URL rewrites
194 1
        $this->existingUrlRewrites = array();
195
196
        // prepare the new URL rewrites first
197 1
        parent::prepareUrlRewrites();
198
199
        // load the store ID to use
200 1
        $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...
201
202
        // load the existing URL rewrites of the actual entity
203 1
        $existingUrlRewrites = $this->getUrlRewritesByEntityTypeAndEntityIdAndStoreId(
204 1
            UrlRewriteObserver::ENTITY_TYPE,
205 1
            $this->entityId,
206
            $storeId
207
        );
208
209
        // prepare the existing URL rewrites to improve searching them by request path
210 1
        foreach ($existingUrlRewrites as $existingUrlRewrite) {
211 1
            $this->existingUrlRewrites[$existingUrlRewrite[MemberNames::REQUEST_PATH]] = $existingUrlRewrite;
212
        }
213 1
    }
214
215
    /**
216
     * Initialize the category product with the passed attributes and returns an instance.
217
     *
218
     * @param array $attr The category product attributes
219
     *
220
     * @return array The initialized category product
221
     */
222 1
    protected function initializeUrlRewrite(array $attr)
223
    {
224
225
        // load the category ID of the passed URL rewrite entity
226 1
        $categoryId = $this->getCategoryIdFromMetadata($attr);
227
228
        // iterate over the available URL rewrites to find the one that matches the category ID
229 1
        foreach ($this->existingUrlRewrites as $urlRewrite) {
230
            // compare the category IDs AND the request path
231 1
            if ($categoryId === $this->getCategoryIdFromMetadata($urlRewrite) &&
232 1
                $attr[MemberNames::REQUEST_PATH] === $urlRewrite[MemberNames::REQUEST_PATH]
233
            ) {
234
                // if a URL rewrite has been found, do NOT create OR keep an existing redirect
235
                $this->removeExistingUrlRewrite($urlRewrite);
236
237
                // if the found URL rewrite has been created manually
238
                if ((integer) $urlRewrite[MemberNames::IS_AUTOGENERATED] === 0) {
239
                    // do NOT update it nor create another redirect
240
                    return false;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return false; (false) is incompatible with the return type of the parent method TechDivision\Import\Prod...r::initializeUrlRewrite of type array.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

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

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
241
                }
242
243
                // if the found URL rewrite has been autogenerated, then update it
244
                return $this->mergeEntity($urlRewrite, $attr);
245
            }
246
        }
247
248
        // simple return the attributes
249 1
        return $attr;
250
    }
251
252
    /**
253
     * Extracts the category ID of the passed URL rewrite entity, if available, and return's it.
254
     *
255
     * @param array $attr The URL rewrite entity to extract and return the category ID for
256
     *
257
     * @return integer|null The category ID if available, else NULL
258
     */
259 1
    protected function getCategoryIdFromMetadata(array $attr)
260
    {
261
262
        // load the metadata of the passed URL rewrite entity
263 1
        $metadata = $this->getMetadata($attr);
264
265
        // return the category ID from the metadata
266 1
        return (integer) $metadata[UrlRewriteObserver::CATEGORY_ID];
267
    }
268
269
    /**
270
     * Initialize the URL rewrite product => category relation with the passed attributes
271
     * and returns an instance.
272
     *
273
     * @param array $attr The URL rewrite product => category relation attributes
274
     *
275
     * @return array|null The initialized URL rewrite product => category relation
276
     */
277 1
    protected function initializeUrlRewriteProductCategory($attr)
278
    {
279
280
        // try to load the URL rewrite product category relation
281 1
        if ($urlRewriteProductCategory = $this->loadUrlRewriteProductCategory($attr[MemberNames::URL_REWRITE_ID])) {
282
            return $this->mergeEntity($urlRewriteProductCategory, $attr);
283
        }
284
285
        // simple return the URL rewrite product category
286 1
        return $attr;
287
    }
288
289
    /**
290
     * Return's the unserialized metadata of the passed URL rewrite. If the
291
     * metadata doesn't contain a category ID, the category ID of the root
292
     * category will be added.
293
     *
294
     * @param array $urlRewrite The URL rewrite to return the metadata for
295
     *
296
     * @return array The metadata of the passed URL rewrite
297
     */
298 1
    protected function getMetadata($urlRewrite)
299
    {
300
301
        // initialize the array with the metaddata
302 1
        $metadata = array();
303
304
        // try to unserialize the metadata from the passed URL rewrite
305 1
        if (isset($urlRewrite[MemberNames::METADATA])) {
306 1
            $metadata = json_decode($urlRewrite[MemberNames::METADATA], true);
307
        }
308
309
        // query whether or not a category ID has been found
310 1
        if (isset($metadata[UrlRewriteObserver::CATEGORY_ID])) {
311
            // if yes, return the metadata
312 1
            return $metadata;
313
        }
314
315
        // if not, append the ID of the root category
316 1
        $rootCategory = $this->getRootCategory();
317 1
        $metadata[UrlRewriteObserver::CATEGORY_ID] = (integer) $rootCategory[MemberNames::ENTITY_ID];
318
319
        // and return the metadata
320 1
        return $metadata;
321
    }
322
323
    /**
324
     * Return's the category with the passed ID.
325
     *
326
     * @param integer $categoryId    The ID of the category to return
327
     * @param string  $storeViewCode The store view code of the category to return, defaults to "admin"
328
     *
329
     * @return array The category data
330
     */
331 1
    protected function getCategory($categoryId, $storeViewCode = StoreViewCodes::ADMIN)
332
    {
333 1
        return $this->getSubject()->getCategory($categoryId, $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 getCategory() does only exist in the following implementations of said interface: TechDivision\Import\Prod...\AbstractProductSubject, TechDivision\Import\Product\Subjects\BunchSubject, TechDivision\Import\Prod...jects\UrlRewriteSubject.

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...
334
    }
335
336
    /**
337
     * Return's the URL rewrites for the passed URL entity type and ID.
338
     *
339
     * @param string  $entityType The entity type to load the URL rewrites for
340
     * @param integer $entityId   The entity ID to load the URL rewrites for
341
     * @param integer $storeId    The store ID to load the URL rewrites for
342
     *
343
     * @return array The URL rewrites
344
     */
345 1
    protected function getUrlRewritesByEntityTypeAndEntityIdAndStoreId($entityType, $entityId, $storeId)
346
    {
347 1
        return $this->getProductUrlRewriteProcessor()->getUrlRewritesByEntityTypeAndEntityIdAndStoreId($entityType, $entityId, $storeId);
348
    }
349
350
    /**
351
     * Return's the URL rewrite product category relation for the passed
352
     * URL rewrite ID.
353
     *
354
     * @param integer $urlRewriteId The URL rewrite ID to load the URL rewrite product category relation for
355
     *
356
     * @return array|false The URL rewrite product category relations
357
     */
358 1
    protected function loadUrlRewriteProductCategory($urlRewriteId)
359
    {
360 1
        return $this->getProductUrlRewriteProcessor()->loadUrlRewriteProductCategory($urlRewriteId);
361
    }
362
363
    /**
364
     * Delete's the URL rewrite with the passed attributes.
365
     *
366
     * @param array       $row  The attributes of the entity to delete
367
     * @param string|null $name The name of the prepared statement that has to be executed
368
     *
369
     * @return void
370
     */
371
    protected function deleteUrlRewrite($row, $name = null)
372
    {
373
        $this->getProductUrlRewriteProcessor()->removeUrlRewrite($row, $name);
0 ignored issues
show
Bug introduced by
The method removeUrlRewrite() does not seem to exist on object<TechDivision\Impo...riteProcessorInterface>.

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...
374
    }
375
}
376