Completed
Pull Request — master (#9)
by
unknown
14:25
created

UrlRewriteUpdateObserver::getExistingUrlRewrite()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 6
ccs 0
cts 4
cp 0
rs 9.4285
cc 2
eloc 3
nc 2
nop 1
crap 6
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
                $targetPath = $this->prepareRequestPath($category);
112
113
                // skip update of url rewrite, if resulting url rewrite would be invalid
114 1
                if ($targetPath == $attr[MemberNames::REQUEST_PATH]) {
115
                    continue;
116
                }
117
118
                $attr[MemberNames::TARGET_PATH] = $targetPath;
119
120
                // merge and return the prepared URL rewrite
121
                $existingUrlRewrite = $this->mergeEntity($existingUrlRewrite, $attr);
122
123
                // create the URL rewrite
124
                $this->persistUrlRewrite($existingUrlRewrite);
125
126
            } else {
127
                // query whether or not the URL rewrite has to be removed
128
                if ($this->getSubject()->getConfiguration()->hasParam(ConfigurationKeys::CLEAN_UP_URL_REWRITES) &&
129
                    $this->getSubject()->getConfiguration()->getParam(ConfigurationKeys::CLEAN_UP_URL_REWRITES)
130
                ) {
131
                    // delete the existing URL rewrite
132
                    $this->deleteUrlRewrite($existingUrlRewrite);
133
134
                    // log a message, that old URL rewrites have been cleaned-up
135
                    $this->getSubject()
136
                        ->getSystemLogger()
137
                        ->warning(
138
                            sprintf(
139
                                'Cleaned-up %d URL rewrite "%s" for product with SKU "%s"',
140
                                $existingUrlRewrite[MemberNames::REQUEST_PATH],
141
                                $this->getValue(ColumnKeys::SKU)
142
                            )
143
                        );
144
                }
145
            }
146
        }
147
    }
148
149
    /**
150
     * Remove's the passed URL rewrite from the existing one's.
151
     *
152
     * @param array $urlRewrite The URL rewrite to remove
153
     *
154
     * @return void
155
     */
156
    protected function removeExistingUrlRewrite(array $urlRewrite)
157
    {
158
159
        // load request path
160
        $requestPath = $urlRewrite[MemberNames::REQUEST_PATH];
161
162
        // query whether or not the URL rewrite exists and remove it, if available
163
        if (isset($this->existingUrlRewrites[$requestPath])) {
164
            unset($this->existingUrlRewrites[$requestPath]);
165
        }
166
    }
167
168
    /**
169
     * Prepare's the URL rewrites that has to be created/updated.
170
     *
171
     * @return void
172
     * @see \TechDivision\Import\Product\UrlRewrite\Observers\UrlRewriteObserver::prepareUrlRewrites()
173
     */
174 1
    protected function prepareUrlRewrites()
175
    {
176
177
        // (re-)initialize the array for the existing URL rewrites
178 1
        $this->existingUrlRewrites = array();
179
180
        // prepare the new URL rewrites first
181 1
        parent::prepareUrlRewrites();
182
183
        // load the store ID to use
184 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...
185
186
        // load the existing URL rewrites of the actual entity
187 1
        $existingUrlRewrites = $this->getUrlRewritesByEntityTypeAndEntityIdAndStoreId(
188 1
            UrlRewriteObserver::ENTITY_TYPE,
189 1
            $this->entityId,
190 1
            $storeId
191
        );
192
193
        // prepare the existing URL rewrites to improve searching them by request path
194 1
        foreach ($existingUrlRewrites as $existingUrlRewrite) {
195 1
            $this->existingUrlRewrites[$existingUrlRewrite[MemberNames::REQUEST_PATH]] = $existingUrlRewrite;
196
        }
197 1
    }
198
199
    /**
200
     * Initialize the category product with the passed attributes and returns an instance.
201
     *
202
     * @param array $attr The category product attributes
203
     *
204
     * @return array The initialized category product
205
     */
206 1
    protected function initializeUrlRewrite(array $attr)
207
    {
208
209
        // load the category ID of the passed URL rewrite entity
210 1
        $categoryId = $this->getCategoryIdFromMetadata($attr);
211
212
        // iterate over the available URL rewrites to find the one that matches the category ID
213 1
        foreach ($this->existingUrlRewrites as $urlRewrite) {
214
            // compare the category IDs AND the request path
215 1
            if ($categoryId === $this->getCategoryIdFromMetadata($urlRewrite) &&
216 1
                $attr[MemberNames::REQUEST_PATH] === $urlRewrite[MemberNames::REQUEST_PATH]
217
            ) {
218
                // if a URL rewrite has been found, do NOT create a redirect
219
                $this->removeExistingUrlRewrite($urlRewrite);
220
221
                // if the found URL rewrite has been created manually
222
                if ((integer) $urlRewrite[MemberNames::IS_AUTOGENERATED] === 0) {
223
                    // do NOT update it nor create another redirect
224
                    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...
225
                }
226
227
                // if the found URL rewrite has been autogenerated, then update it
228 1
                return $this->mergeEntity($urlRewrite, $attr);
229
            }
230
        }
231
232
        // simple return the attributes
233 1
        return $attr;
234
    }
235
236
    /**
237
     * Extracts the category ID of the passed URL rewrite entity, if available, and return's it.
238
     *
239
     * @param array $attr The URL rewrite entity to extract and return the category ID for
240
     *
241
     * @return integer|null The category ID if available, else NULL
242
     */
243 1
    protected function getCategoryIdFromMetadata(array $attr)
244
    {
245
246
        // load the metadata of the passed URL rewrite entity
247 1
        $metadata = $this->getMetadata($attr);
248
249
        // return the category ID from the metadata
250 1
        return $metadata[UrlRewriteObserver::CATEGORY_ID];
251
    }
252
253
    /**
254
     * Initialize the URL rewrite product => category relation with the passed attributes
255
     * and returns an instance.
256
     *
257
     * @param array $attr The URL rewrite product => category relation attributes
258
     *
259
     * @return array|null The initialized URL rewrite product => category relation
260
     */
261 1
    protected function initializeUrlRewriteProductCategory($attr)
262
    {
263
264
        // try to load the URL rewrite product category relation
265 1
        if ($urlRewriteProductCategory = $this->loadUrlRewriteProductCategory($attr[MemberNames::URL_REWRITE_ID])) {
266
            return $this->mergeEntity($urlRewriteProductCategory, $attr);
267
        }
268
269
        // simple return the URL rewrite product category
270 1
        return $attr;
271
    }
272
273
    /**
274
     * Return's the unserialized metadata of the passed URL rewrite. If the
275
     * metadata doesn't contain a category ID, the category ID of the root
276
     * category will be added.
277
     *
278
     * @param array $urlRewrite The URL rewrite to return the metadata for
279
     *
280
     * @return array The metadata of the passed URL rewrite
281
     */
282 1
    protected function getMetadata($urlRewrite)
283
    {
284
285
        // initialize the array with the metaddata
286 1
        $metadata = array();
287
288
        // try to unserialize the metadata from the passed URL rewrite
289 1
        if (isset($urlRewrite[MemberNames::METADATA])) {
290 1
            $metadata = unserialize($urlRewrite[MemberNames::METADATA]);
291
        }
292
293
        // query whether or not a category ID has been found
294 1
        if (isset($metadata[UrlRewriteObserver::CATEGORY_ID])) {
295
            // if yes, return the metadata
296 1
            return $metadata;
297
        }
298
299
        // if not, append the ID of the root category
300 1
        $rootCategory = $this->getRootCategory();
301 1
        $metadata[UrlRewriteObserver::CATEGORY_ID] = $rootCategory[MemberNames::ENTITY_ID];
302
303
        // and return the metadata
304 1
        return $metadata;
305
    }
306
307
    /**
308
     * Return's the category with the passed ID.
309
     *
310
     * @param integer $categoryId The ID of the category to return
311
     *
312
     * @return array The category data
313
     */
314 1
    protected function getCategory($categoryId)
315
    {
316 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...
317
    }
318
319
    /**
320
     * Return's the URL rewrites for the passed URL entity type and ID.
321
     *
322
     * @param string  $entityType The entity type to load the URL rewrites for
323
     * @param integer $entityId   The entity ID to load the URL rewrites for
324
     * @param integer $storeId    The store ID to load the URL rewrites for
325
     *
326
     * @return array The URL rewrites
327
     */
328 1
    protected function getUrlRewritesByEntityTypeAndEntityIdAndStoreId($entityType, $entityId, $storeId)
329
    {
330 1
        return $this->getProductUrlRewriteProcessor()->getUrlRewritesByEntityTypeAndEntityIdAndStoreId($entityType, $entityId, $storeId);
331
    }
332
333
    /**
334
     * Return's the URL rewrite product category relation for the passed
335
     * URL rewrite ID.
336
     *
337
     * @param integer $urlRewriteId The URL rewrite ID to load the URL rewrite product category relation for
338
     *
339
     * @return array|false The URL rewrite product category relations
340
     */
341 1
    protected function loadUrlRewriteProductCategory($urlRewriteId)
342
    {
343 1
        return $this->getProductUrlRewriteProcessor()->loadUrlRewriteProductCategory($urlRewriteId);
344
    }
345
346
    /**
347
     * Delete's the URL rewrite with the passed attributes.
348
     *
349
     * @param array       $row  The attributes of the entity to delete
350
     * @param string|null $name The name of the prepared statement that has to be executed
351
     *
352
     * @return void
353
     */
354
    protected function deleteUrlRewrite($row, $name = null)
355
    {
356
        $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...
357
    }
358
}
359