Completed
Push — master ( 6a5528...b7892c )
by
unknown
13s
created

UrlRewriteUpdateObserver   A

Complexity

Total Complexity 32

Size/Duplication

Total Lines 329
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 5

Test Coverage

Coverage 63.33%

Importance

Changes 0
Metric Value
wmc 32
lcom 1
cbo 5
dl 0
loc 329
ccs 57
cts 90
cp 0.6333
rs 9.6
c 0
b 0
f 0

12 Methods

Rating   Name   Duplication   Size   Complexity  
C process() 0 88 11
A getExistingUrlRewrite() 0 6 2
A removeExistingUrlRewrite() 0 11 2
B prepareUrlRewrites() 0 24 2
B initializeUrlRewrite() 0 29 5
A getCategoryIdFromMetadata() 0 9 1
A initializeUrlRewriteProductCategory() 0 11 2
B getMetadata() 0 24 3
A getCategory() 0 4 1
A getUrlRewritesByEntityTypeAndEntityIdAndStoreId() 0 4 1
A loadUrlRewriteProductCategory() 0 4 1
A deleteUrlRewrite() 0 4 1
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
        // stop processing if the store is NOT active
60 1
        if (!$this->isStoreViewActive) {
61
            return;
62
        }
63
64
        // load the root category
65 1
        $rootCategory = $this->getRootCategory();
66
67
        // create redirect URL rewrites for the existing URL rewrites
68 1
        foreach ($this->existingUrlRewrites as $existingUrlRewrite) {
69
            // if the URL rewrite has been created manually
70 1
            if ((integer) $existingUrlRewrite[MemberNames::IS_AUTOGENERATED] === 0) {
71
                // do NOTHING, because someone really WANTED to create THIS redirect
72
                continue;
73
            }
74
75
            // query whether or not 301 redirects have to be created, so don't create redirects
76
            // if the product is NOT visible or the rewrite history has been deactivated
77 1
            if ($this->isVisible() && $this->getSubject()->getCoreConfigData(CoreConfigDataKeys::CATALOG_SEO_SAVE_REWRITES_HISTORY, true)) {
78
                // if the URL rewrite already IS a redirect
79 1
                if ((integer) $existingUrlRewrite[MemberNames::REDIRECT_TYPE] !== 0) {
80
                    // do NOT create another redirect or update the actual one
81
                    continue;
82
                }
83
84
                // initialize the data with the URL rewrites new 301 configuration
85 1
                $attr = array(MemberNames::REDIRECT_TYPE => 301);
86
87
                // initialize the category with the root category
88 1
                $category = $rootCategory;
89
90
                // load the metadata from the existing URL rewrite
91 1
                $metadata = $this->getMetadata($existingUrlRewrite);
92
93
                // query whether or not the URL key of the existing URL rewrite has changed
94 1
                if (isset($this->urlRewrites[$metadata[UrlRewriteObserver::CATEGORY_ID]])) {
95
                    try {
96
                        // if yes, try to load the original category and OVERRIDE the default category
97 1
                        $category = $this->getCategory($metadata[UrlRewriteObserver::CATEGORY_ID]);
98
                    } catch (\Exception $e) {
99
                        // if the old category can NOT be loaded, override the metadata
100
                        // of the category with the data of the default category
101
                        $attr[MemberNames::METADATA] = serialize(array());
102
103
                        // finally log a warning that the old category is not available ony more
104
                        $this->getSubject()
105
                            ->getSystemLogger()
106
                            ->warning(sprintf('Category with ID %d is not longer available', $metadata[UrlRewriteObserver::CATEGORY_ID]));
107
                    }
108
                }
109
110
                // load target path/metadata for the actual category
111 1
                $attr[MemberNames::TARGET_PATH] = $this->prepareRequestPath($category);
112
113
                // merge and return the prepared URL rewrite
114 1
                $existingUrlRewrite = $this->mergeEntity($existingUrlRewrite, $attr);
115
116
                // create the URL rewrite
117 1
                $this->persistUrlRewrite($existingUrlRewrite);
118
119
            } else {
120
                // query whether or not the URL rewrite has to be removed
121
                if ($this->getSubject()->getConfiguration()->hasParam(ConfigurationKeys::CLEAN_UP_URL_REWRITES) &&
122
                    $this->getSubject()->getConfiguration()->getParam(ConfigurationKeys::CLEAN_UP_URL_REWRITES)
123
                ) {
124
                    // delete the existing URL rewrite
125
                    $this->deleteUrlRewrite($existingUrlRewrite);
126
127
                    // log a message, that old URL rewrites have been cleaned-up
128
                    $this->getSubject()
129
                        ->getSystemLogger()
130
                        ->warning(
131
                            sprintf(
132
                                'Cleaned-up %d URL rewrite "%s" for product with SKU "%s"',
133
                                $existingUrlRewrite[MemberNames::REQUEST_PATH],
134 1
                                $this->getValue(ColumnKeys::SKU)
135
                            )
136
                        );
137
                }
138
            }
139
        }
140 1
    }
141
142
    /**
143
     * Return's the URL rewrite for the passed request path.
144
     *
145
     * @param string $requestPath The request path to return the URL rewrite for
146
     *
147
     * @return array|null The URL rewrite
148
     */
149
    protected function getExistingUrlRewrite($requestPath)
150
    {
151
        if (isset($this->existingUrlRewrites[$requestPath])) {
152
            return $this->existingUrlRewrites[$requestPath];
153
        }
154
    }
155
156
    /**
157
     * Remove's the passed URL rewrite from the existing one's.
158
     *
159
     * @param array $urlRewrite The URL rewrite to remove
160
     *
161
     * @return void
162
     */
163
    protected function removeExistingUrlRewrite(array $urlRewrite)
164
    {
165
166
        // load request path
167
        $requestPath = $urlRewrite[MemberNames::REQUEST_PATH];
168
169
        // query whether or not the URL rewrite exists and remove it, if available
170
        if (isset($this->existingUrlRewrites[$requestPath])) {
171
            unset($this->existingUrlRewrites[$requestPath]);
172
        }
173
    }
174
175
    /**
176
     * Prepare's the URL rewrites that has to be created/updated.
177
     *
178
     * @return void
179
     * @see \TechDivision\Import\Product\UrlRewrite\Observers\UrlRewriteObserver::prepareUrlRewrites()
180
     */
181 1
    protected function prepareUrlRewrites()
182
    {
183
184
        // (re-)initialize the array for the existing URL rewrites
185 1
        $this->existingUrlRewrites = array();
186
187
        // prepare the new URL rewrites first
188 1
        parent::prepareUrlRewrites();
189
190
        // load the store ID to use
191 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...
192
193
        // load the existing URL rewrites of the actual entity
194 1
        $existingUrlRewrites = $this->getUrlRewritesByEntityTypeAndEntityIdAndStoreId(
195 1
            UrlRewriteObserver::ENTITY_TYPE,
196 1
            $this->entityId,
197 1
            $storeId
198
        );
199
200
        // prepare the existing URL rewrites to improve searching them by request path
201 1
        foreach ($existingUrlRewrites as $existingUrlRewrite) {
202 1
            $this->existingUrlRewrites[$existingUrlRewrite[MemberNames::REQUEST_PATH]] = $existingUrlRewrite;
203
        }
204 1
    }
205
206
    /**
207
     * Initialize the category product with the passed attributes and returns an instance.
208
     *
209
     * @param array $attr The category product attributes
210
     *
211
     * @return array The initialized category product
212
     */
213 1
    protected function initializeUrlRewrite(array $attr)
214
    {
215
216
        // load the category ID of the passed URL rewrite entity
217 1
        $categoryId = $this->getCategoryIdFromMetadata($attr);
218
219
        // iterate over the available URL rewrites to find the one that matches the category ID
220 1
        foreach ($this->existingUrlRewrites as $urlRewrite) {
221
            // compare the category IDs AND the request path
222 1
            if ($categoryId === $this->getCategoryIdFromMetadata($urlRewrite) &&
223 1
                $attr[MemberNames::REQUEST_PATH] === $urlRewrite[MemberNames::REQUEST_PATH]
224
            ) {
225
                // if a URL rewrite has been found, do NOT create a redirect
226
                $this->removeExistingUrlRewrite($urlRewrite);
227
228
                // if the found URL rewrite has been created manually
229
                if ((integer) $urlRewrite[MemberNames::IS_AUTOGENERATED] === 0) {
230
                    // do NOT update it nor create another redirect
231
                    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...
232
                }
233
234
                // if the found URL rewrite has been autogenerated, then update it
235 1
                return $this->mergeEntity($urlRewrite, $attr);
236
            }
237
        }
238
239
        // simple return the attributes
240 1
        return $attr;
241
    }
242
243
    /**
244
     * Extracts the category ID of the passed URL rewrite entity, if available, and return's it.
245
     *
246
     * @param array $attr The URL rewrite entity to extract and return the category ID for
247
     *
248
     * @return integer|null The category ID if available, else NULL
249
     */
250 1
    protected function getCategoryIdFromMetadata(array $attr)
251
    {
252
253
        // load the metadata of the passed URL rewrite entity
254 1
        $metadata = $this->getMetadata($attr);
255
256
        // return the category ID from the metadata
257 1
        return $metadata[UrlRewriteObserver::CATEGORY_ID];
258
    }
259
260
    /**
261
     * Initialize the URL rewrite product => category relation with the passed attributes
262
     * and returns an instance.
263
     *
264
     * @param array $attr The URL rewrite product => category relation attributes
265
     *
266
     * @return array|null The initialized URL rewrite product => category relation
267
     */
268 1
    protected function initializeUrlRewriteProductCategory($attr)
269
    {
270
271
        // try to load the URL rewrite product category relation
272 1
        if ($urlRewriteProductCategory = $this->loadUrlRewriteProductCategory($attr[MemberNames::URL_REWRITE_ID])) {
273
            return $this->mergeEntity($urlRewriteProductCategory, $attr);
274
        }
275
276
        // simple return the URL rewrite product category
277 1
        return $attr;
278
    }
279
280
    /**
281
     * Return's the unserialized metadata of the passed URL rewrite. If the
282
     * metadata doesn't contain a category ID, the category ID of the root
283
     * category will be added.
284
     *
285
     * @param array $urlRewrite The URL rewrite to return the metadata for
286
     *
287
     * @return array The metadata of the passed URL rewrite
288
     */
289 1
    protected function getMetadata($urlRewrite)
290
    {
291
292
        // initialize the array with the metaddata
293 1
        $metadata = array();
294
295
        // try to unserialize the metadata from the passed URL rewrite
296 1
        if (isset($urlRewrite[MemberNames::METADATA])) {
297 1
            $metadata = unserialize($urlRewrite[MemberNames::METADATA]);
298
        }
299
300
        // query whether or not a category ID has been found
301 1
        if (isset($metadata[UrlRewriteObserver::CATEGORY_ID])) {
302
            // if yes, return the metadata
303 1
            return $metadata;
304
        }
305
306
        // if not, append the ID of the root category
307 1
        $rootCategory = $this->getRootCategory();
308 1
        $metadata[UrlRewriteObserver::CATEGORY_ID] = $rootCategory[MemberNames::ENTITY_ID];
309
310
        // and return the metadata
311 1
        return $metadata;
312
    }
313
314
    /**
315
     * Return's the category with the passed ID.
316
     *
317
     * @param integer $categoryId The ID of the category to return
318
     *
319
     * @return array The category data
320
     */
321 1
    protected function getCategory($categoryId)
322
    {
323 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...
324
    }
325
326
    /**
327
     * Return's the URL rewrites for the passed URL entity type and ID.
328
     *
329
     * @param string  $entityType The entity type to load the URL rewrites for
330
     * @param integer $entityId   The entity ID to load the URL rewrites for
331
     * @param integer $storeId    The store ID to load the URL rewrites for
332
     *
333
     * @return array The URL rewrites
334
     */
335 1
    protected function getUrlRewritesByEntityTypeAndEntityIdAndStoreId($entityType, $entityId, $storeId)
336
    {
337 1
        return $this->getProductUrlRewriteProcessor()->getUrlRewritesByEntityTypeAndEntityIdAndStoreId($entityType, $entityId, $storeId);
338
    }
339
340
    /**
341
     * Return's the URL rewrite product category relation for the passed
342
     * URL rewrite ID.
343
     *
344
     * @param integer $urlRewriteId The URL rewrite ID to load the URL rewrite product category relation for
345
     *
346
     * @return array|false The URL rewrite product category relations
347
     */
348 1
    protected function loadUrlRewriteProductCategory($urlRewriteId)
349
    {
350 1
        return $this->getProductUrlRewriteProcessor()->loadUrlRewriteProductCategory($urlRewriteId);
351
    }
352
353
    /**
354
     * Delete's the URL rewrite with the passed attributes.
355
     *
356
     * @param array       $row  The attributes of the entity to delete
357
     * @param string|null $name The name of the prepared statement that has to be executed
358
     *
359
     * @return void
360
     */
361
    protected function deleteUrlRewrite($row, $name = null)
362
    {
363
        $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...
364
    }
365
}
366