Completed
Push — master ( 5bcafe...c5dea9 )
by Tim
13s
created

UrlRewriteUpdateObserver::prepareUrlRewrites()   B

Complexity

Conditions 2
Paths 2

Size

Total Lines 24
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 2

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 24
ccs 10
cts 10
cp 1
rs 8.9713
cc 2
eloc 10
nc 2
nop 0
crap 2
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
26
/**
27
 * Observer that creates/updates the product's URL rewrites.
28
 *
29
 * @author    Tim Wagner <[email protected]>
30
 * @copyright 2016 TechDivision GmbH <[email protected]>
31
 * @license   http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
32
 * @link      https://github.com/techdivision/import-product-url-rewrite
33
 * @link      http://www.techdivision.com
34
 */
35
class UrlRewriteUpdateObserver extends UrlRewriteObserver
36
{
37
38
    /**
39
     * Array with the existing URL rewrites of the actual product.
40
     *
41
     * @var array
42
     */
43
    protected $existingUrlRewrites = array();
44
45
    /**
46
     * Process the observer's business logic.
47
     *
48
     * @return void
49
     * @see \TechDivision\Import\Product\Observers\UrlRewriteObserver::process()
50
     */
51 1
    protected function process()
52
    {
53
54
        // process the new URL rewrites first
55 1
        parent::process();
56
57
        // load the root category
58 1
        $rootCategory = $this->getRootCategory();
59
60
        // create redirect URL rewrites for the existing URL rewrites
61 1
        foreach ($this->existingUrlRewrites as $existingUrlRewrite) {
62
            // if the URL rewrite has been created manually
63 1
            if ((integer) $existingUrlRewrite[MemberNames::IS_AUTOGENERATED] === 0) {
64
                // do NOTHING, because someone really WANTED to create THIS redirect
65
                continue;
66
            }
67
68
            // query whether or not 301 redirects have to be created, so don't create redirects
69
            // if the product is NOT visible or the rewrite history has been deactivated
70 1
            if ($this->isVisible() && $this->getSubject()->getCoreConfigData(CoreConfigDataKeys::CATALOG_SEO_SAVE_REWRITES_HISTORY, true)) {
71
                // if the URL rewrite already IS a redirect
72 1
                if ((integer) $existingUrlRewrite[MemberNames::REDIRECT_TYPE] !== 0) {
73
                    // do NOT create another redirect or update the actual one
74
                    continue;
75
                }
76
77
                // load the metadata from the existing URL rewrite
78 1
                $metadata = $this->getMetadata($existingUrlRewrite);
79
80
                // initialize the category with the root category
81 1
                $category = $rootCategory;
82
83
                // query whether or not, the existing URL rewrite has been replaced
84 1
                if (isset($this->urlRewrites[$metadata[UrlRewriteObserver::CATEGORY_ID]])) {
85
                    // if yes, load the category of the original one
86 1
                    $category = $this->getCategory($metadata[UrlRewriteObserver::CATEGORY_ID]);
87
                }
88
89
                // load target path/metadata for the actual category
90 1
                $targetPath = $this->prepareRequestPath($category);
91 1
                $metadata = serialize($this->prepareMetadata($category));
92
93
                // override data with the 301 configuration
94
                $attr = array(
95 1
                    MemberNames::REDIRECT_TYPE    => 301,
96 1
                    MemberNames::METADATA         => $metadata,
97 1
                    MemberNames::TARGET_PATH      => $targetPath,
98
                );
99
100
                // merge and return the prepared URL rewrite
101 1
                $existingUrlRewrite = $this->mergeEntity($existingUrlRewrite, $attr);
102
103
                // create the URL rewrite
104 1
                $this->persistUrlRewrite($existingUrlRewrite);
105
106
            } else {
107
                // delete the existing URL rewrite
108 1
                $this->deleteUrlRewrite($existingUrlRewrite);
109
            }
110
        }
111 1
    }
112
113
    /**
114
     * Return's the URL rewrite for the passed request path.
115
     *
116
     * @param string $requestPath The request path to return the URL rewrite for
117
     *
118
     * @return array|null The URL rewrite
119
     */
120
    protected function getExistingUrlRewrite($requestPath)
121
    {
122
        if (isset($this->existingUrlRewrites[$requestPath])) {
123
            return $this->existingUrlRewrites[$requestPath];
124
        }
125
    }
126
127
    /**
128
     * Remove's the passed URL rewrite from the existing one's.
129
     *
130
     * @param array $urlRewrite The URL rewrite to remove
131
     *
132
     * @return void
133
     */
134
    protected function removeExistingUrlRewrite(array $urlRewrite)
135
    {
136
137
        // load request path
138
        $requestPath = $urlRewrite[MemberNames::REQUEST_PATH];
139
140
        // query whether or not the URL rewrite exists and remove it, if available
141
        if (isset($this->existingUrlRewrites[$requestPath])) {
142
            unset($this->existingUrlRewrites[$requestPath]);
143
        }
144
    }
145
146
    /**
147
     * Prepare's the URL rewrites that has to be created/updated.
148
     *
149
     * @return void
150
     * @see \TechDivision\Import\Product\Observers\UrlRewriteObserver::prepareUrlRewrites()
151
     */
152 1
    protected function prepareUrlRewrites()
153
    {
154
155
        // (re-)initialize the array for the existing URL rewrites
156 1
        $this->existingUrlRewrites = array();
157
158
        // prepare the new URL rewrites first
159 1
        parent::prepareUrlRewrites();
160
161
        // load the store ID to use
162 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...
163
164
        // load the existing URL rewrites of the actual entity
165 1
        $existingUrlRewrites = $this->getUrlRewritesByEntityTypeAndEntityIdAndStoreId(
166 1
            UrlRewriteObserver::ENTITY_TYPE,
167 1
            $this->entityId,
168
            $storeId
169
        );
170
171
        // prepare the existing URL rewrites to improve searching them by request path
172 1
        foreach ($existingUrlRewrites as $existingUrlRewrite) {
173 1
            $this->existingUrlRewrites[$existingUrlRewrite[MemberNames::REQUEST_PATH]] = $existingUrlRewrite;
174
        }
175 1
    }
176
177
    /**
178
     * Initialize the category product with the passed attributes and returns an instance.
179
     *
180
     * @param array $attr The category product attributes
181
     *
182
     * @return array The initialized category product
183
     */
184 1
    protected function initializeUrlRewrite(array $attr)
185
    {
186
187
        // load the category ID of the passed URL rewrite entity
188 1
        $categoryId = $this->getCategoryIdFromMetadata($attr);
189
190
        // iterate over the availabel URL rewrites to find the one that matches the category ID
191 1
        foreach ($this->existingUrlRewrites as $urlRewrite) {
192
            // compare the category IDs AND the request path
193 1
            if ($categoryId === $this->getCategoryIdFromMetadata($urlRewrite) &&
194 1
                $attr[MemberNames::REQUEST_PATH] === $urlRewrite[MemberNames::REQUEST_PATH]
195
            ) {
196
                // if a URL rewrite has been found, do NOT create a redirect
197
                $this->removeExistingUrlRewrite($urlRewrite);
198
199
                // if the found URL rewrite has been created manually
200
                if ((integer) $urlRewrite[MemberNames::IS_AUTOGENERATED] === 0) {
201
                    // do NOT update it nor create another redirect
202
                    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...
203
                }
204
205
                // if the found URL rewrite has been autogenerated, then update it
206 1
                return $this->mergeEntity($urlRewrite, $attr);
207
            }
208
        }
209
210
        // simple return the attributes
211 1
        return $attr;
212
    }
213
214
    /**
215
     * Extracts the category ID of the passed URL rewrite entity, if available, and return's it.
216
     *
217
     * @param array $attr The URL rewrite entity to extract and return the category ID for
218
     *
219
     * @return integer|null The category ID if available, else NULL
220
     */
221 1
    protected function getCategoryIdFromMetadata(array $attr)
222
    {
223
224
        // load the metadata of the passed URL rewrite entity
225 1
        $metadata = $this->getMetadata($attr);
226
227
        // return the category ID from the metadata
228 1
        return $metadata[UrlRewriteObserver::CATEGORY_ID];
229
    }
230
231
    /**
232
     * Initialize the URL rewrite product => category relation with the passed attributes
233
     * and returns an instance.
234
     *
235
     * @param array $attr The URL rewrite product => category relation attributes
236
     *
237
     * @return array|null The initialized URL rewrite product => category relation
238
     */
239 1
    protected function initializeUrlRewriteProductCategory($attr)
240
    {
241
242
        // try to load the URL rewrite product category relation
243 1
        if ($urlRewriteProductCategory = $this->loadUrlRewriteProductCategory($attr[MemberNames::URL_REWRITE_ID])) {
244
            return $this->mergeEntity($urlRewriteProductCategory, $attr);
245
        }
246
247
        // simple return the URL rewrite product category
248 1
        return $attr;
249
    }
250
251
    /**
252
     * Return's the unserialized metadata of the passed URL rewrite. If the
253
     * metadata doesn't contain a category ID, the category ID of the root
254
     * category will be added.
255
     *
256
     * @param array $urlRewrite The URL rewrite to return the metadata for
257
     *
258
     * @return array The metadata of the passed URL rewrite
259
     */
260 1
    protected function getMetadata($urlRewrite)
261
    {
262
263
        // initialize the array with the metaddata
264 1
        $metadata = array();
265
266
        // try to unserialize the metadata from the passed URL rewrite
267 1
        if (isset($urlRewrite[MemberNames::METADATA])) {
268 1
            $metadata = unserialize($urlRewrite[MemberNames::METADATA]);
269
        }
270
271
        // query whether or not a category ID has been found
272 1
        if (isset($metadata[UrlRewriteObserver::CATEGORY_ID])) {
273
            // if yes, return the metadata
274 1
            return $metadata;
275
        }
276
277
        // if not, append the ID of the root category
278 1
        $rootCategory = $this->getRootCategory();
279 1
        $metadata[UrlRewriteObserver::CATEGORY_ID] = $rootCategory[MemberNames::ENTITY_ID];
280
281
        // and return the metadata
282 1
        return $metadata;
283
    }
284
285
    /**
286
     * Return's the category with the passed ID.
287
     *
288
     * @param integer $categoryId The ID of the category to return
289
     *
290
     * @return array The category data
291
     */
292 1
    protected function getCategory($categoryId)
293
    {
294 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...
295
    }
296
297
    /**
298
     * Return's the URL rewrites for the passed URL entity type and ID.
299
     *
300
     * @param string  $entityType The entity type to load the URL rewrites for
301
     * @param integer $entityId   The entity ID to load the URL rewrites for
302
     * @param integer $storeId    The store ID to load the URL rewrites for
303
     *
304
     * @return array The URL rewrites
305
     */
306 1
    public function getUrlRewritesByEntityTypeAndEntityIdAndStoreId($entityType, $entityId, $storeId)
307
    {
308 1
        return $this->getProductUrlRewriteProcessor()->getUrlRewritesByEntityTypeAndEntityIdAndStoreId($entityType, $entityId, $storeId);
309
    }
310
311
    /**
312
     * Return's the URL rewrite product category relation for the passed
313
     * URL rewrite ID.
314
     *
315
     * @param integer $urlRewriteId The URL rewrite ID to load the URL rewrite product category relation for
316
     *
317
     * @return array|false The URL rewrite product category relations
318
     */
319 1
    protected function loadUrlRewriteProductCategory($urlRewriteId)
320
    {
321 1
        return $this->getProductUrlRewriteProcessor()->loadUrlRewriteProductCategory($urlRewriteId);
322
    }
323
324
    /**
325
     * Delete's the URL rewrite with the passed attributes.
326
     *
327
     * @param array       $row  The attributes of the entity to delete
328
     * @param string|null $name The name of the prepared statement that has to be executed
329
     *
330
     * @return void
331
     */
332
    protected function deleteUrlRewrite($row, $name = null)
333
    {
334
        $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...
335
    }
336
}
337