Completed
Pull Request — master (#10)
by Tim
02:23
created

UrlRewriteUpdateObserver::process()   D

Complexity

Conditions 13
Paths 13

Size

Total Lines 111
Code Lines 49

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 20
CRAP Score 46.5399

Importance

Changes 0
Metric Value
dl 0
loc 111
ccs 20
cts 48
cp 0.4167
rs 4.9922
c 0
b 0
f 0
cc 13
eloc 49
nc 13
nop 0
crap 46.5399

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\Product\Utils\CoreConfigDataKeys;
24
use TechDivision\Import\Product\UrlRewrite\Utils\MemberNames;
25
use TechDivision\Import\Product\UrlRewrite\Utils\ColumnKeys;
26
use TechDivision\Import\Product\UrlRewrite\Utils\ConfigurationKeys;
27
28
/**
29
 * Observer that creates/updates the product's URL rewrites.
30
 *
31
 * @author    Tim Wagner <[email protected]>
32
 * @copyright 2016 TechDivision GmbH <[email protected]>
33
 * @license   http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
34
 * @link      https://github.com/techdivision/import-product-url-rewrite
35
 * @link      http://www.techdivision.com
36
 */
37
class UrlRewriteUpdateObserver extends UrlRewriteObserver
38
{
39
40
    /**
41
     * Array with the existing URL rewrites of the actual product.
42
     *
43
     * @var array
44
     */
45
    protected $existingUrlRewrites = array();
46
47
    /**
48
     * Process the observer's business logic.
49
     *
50
     * @return void
51
     * @see \TechDivision\Import\Product\UrlRewrite\Observers\UrlRewriteObserver::process()
52
     */
53 1
    protected function process()
54
    {
55
56
        // process the new URL rewrites first
57 1
        parent::process();
58
59
        // load the root category
60 1
        $rootCategory = $this->getRootCategory();
61
62
        // create redirect URL rewrites for the existing URL rewrites
63 1
        foreach ($this->existingUrlRewrites as $existingUrlRewrite) {
64
            // if the URL rewrite has been created manually
65 1
            if ((integer) $existingUrlRewrite[MemberNames::IS_AUTOGENERATED] === 0) {
66
                // do NOTHING, because someone really WANTED to create THIS redirect
67
                continue;
68
            }
69
70
            // query whether or not 301 redirects have to be created, so don't create redirects
71
            // if the product is NOT visible or the rewrite history has been deactivated
72 1
            if ($this->isVisible() && $this->getSubject()->getCoreConfigData(CoreConfigDataKeys::CATALOG_SEO_SAVE_REWRITES_HISTORY, true)) {
73
                // if the URL rewrite already IS a redirect
74 1
                if ((integer) $existingUrlRewrite[MemberNames::REDIRECT_TYPE] !== 0) {
75
                    // do NOT create another redirect or update the actual one
76
                    continue;
77
                }
78
79
                // initialize the data with the URL rewrites new 301 configuration
80 1
                $attr = array(MemberNames::REDIRECT_TYPE => 301);
81
82
                // initialize the category with the root category
83 1
                $category = $rootCategory;
84
85
                // load the metadata from the existing URL rewrite
86 1
                $metadata = $this->getMetadata($existingUrlRewrite);
87
88
                // query whether or not the URL key of the existing URL rewrite has changed
89 1
                if (is_array($metadata) && isset($metadata[UrlRewriteObserver::CATEGORY_ID])) {
90 1
                    if (isset($this->urlRewrites[$metadata[UrlRewriteObserver::CATEGORY_ID]])) {
91
                        try {
92
                            // if yes, try to load the original category and OVERRIDE the default category
93 1
                            $category = $this->getCategory($metadata[UrlRewriteObserver::CATEGORY_ID]);
94
                        } catch (\Exception $e) {
95
                            // if the old category can NOT be loaded, remove the
96
                            // category ID from the URL rewrites metadata
97
                            $attr[MemberNames::METADATA] = null;
98
99
                            // finally log a warning that the old category is not available ony more
100
                            $this->getSubject()
101
                                 ->getSystemLogger()
102
                                 ->warning(
103
                                     sprintf(
104
                                         'Category with ID "%d" is not longer available for URL rewrite with ID "%d"',
105
                                         $metadata[UrlRewriteObserver::CATEGORY_ID],
106
                                         $existingUrlRewrite[MemberNames::URL_REWRITE_ID]
107
                                     )
108
                                 );
109
                        }
110
                    }
111
                }
112
113
                // load target path/metadata for the actual category
114 1
                $targetPath = $this->prepareRequestPath($category);
115
116
                // skip update of URL rewrite, if resulting new target path EQUALS old request path
117 1
                if ($targetPath === $existingUrlRewrite[MemberNames::REQUEST_PATH]) {
118
                    // finally log a warning that the old category is not available ony more
119
                    $this->getSubject()
120
                         ->getSystemLogger()
121
                         ->warning(
122
                             sprintf(
123
                                 'New target path "%s" eqals request path for URL rewrite with ID "%d"',
124
                                 $existingUrlRewrite[MemberNames::REQUEST_PATH],
125
                                 $existingUrlRewrite[MemberNames::URL_REWRITE_ID]
126
                             )
127
                         );
128
129
                    // stop processing the URL rewrite
130
                    continue;
131
                }
132
133
                // set the target path
134 1
                $attr[MemberNames::TARGET_PATH] = $targetPath;
135
136
                // merge and return the prepared URL rewrite
137 1
                $existingUrlRewrite = $this->mergeEntity($existingUrlRewrite, $attr);
138
139
                // create the URL rewrite
140 1
                $this->persistUrlRewrite($existingUrlRewrite);
141
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 1
                                 $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 1
            $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 1
                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 = unserialize($urlRewrite[MemberNames::METADATA]);
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
     *
328
     * @return array The category data
329
     */
330 1
    protected function getCategory($categoryId)
331
    {
332 1
        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, 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...
333
    }
334
335
    /**
336
     * Return's the URL rewrites for the passed URL entity type and ID.
337
     *
338
     * @param string  $entityType The entity type to load the URL rewrites for
339
     * @param integer $entityId   The entity ID to load the URL rewrites for
340
     * @param integer $storeId    The store ID to load the URL rewrites for
341
     *
342
     * @return array The URL rewrites
343
     */
344 1
    protected function getUrlRewritesByEntityTypeAndEntityIdAndStoreId($entityType, $entityId, $storeId)
345
    {
346 1
        return $this->getProductUrlRewriteProcessor()->getUrlRewritesByEntityTypeAndEntityIdAndStoreId($entityType, $entityId, $storeId);
347
    }
348
349
    /**
350
     * Return's the URL rewrite product category relation for the passed
351
     * URL rewrite ID.
352
     *
353
     * @param integer $urlRewriteId The URL rewrite ID to load the URL rewrite product category relation for
354
     *
355
     * @return array|false The URL rewrite product category relations
356
     */
357 1
    protected function loadUrlRewriteProductCategory($urlRewriteId)
358
    {
359 1
        return $this->getProductUrlRewriteProcessor()->loadUrlRewriteProductCategory($urlRewriteId);
360
    }
361
362
    /**
363
     * Delete's the URL rewrite with the passed attributes.
364
     *
365
     * @param array       $row  The attributes of the entity to delete
366
     * @param string|null $name The name of the prepared statement that has to be executed
367
     *
368
     * @return void
369
     */
370
    protected function deleteUrlRewrite($row, $name = null)
371
    {
372
        $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...
373
    }
374
}
375