Completed
Pull Request — master (#51)
by Tim
04:57
created

UrlRewriteUpdateObserver::prepareUrlRewrites()   B

Complexity

Conditions 2
Paths 2

Size

Total Lines 26
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 11
CRAP Score 2

Importance

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