Completed
Push — master ( 4dbc66...04642e )
by Tim
11s
created

UrlRewriteUpdateObserver::prepareUrlRewrites()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 22
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 22
ccs 10
cts 10
cp 1
rs 9.2
c 0
b 0
f 0
cc 2
eloc 8
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 1
                }
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 1
                );
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 1
            }
139 1
        }
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 the existing URL rewrites of the actual entity
158 1
        $existingUrlRewrites = $this->getUrlRewritesByEntityTypeAndEntityId(UrlRewriteObserver::ENTITY_TYPE, $this->getLastEntityId());
159
160
        // prepare the existing URL rewrites to improve searching them by store ID/request path
161 1
        foreach ($existingUrlRewrites as $existingUrlRewrite) {
162
            // load store ID and request path from the existing URL rewrite
163 1
            $storeId = (integer) $existingUrlRewrite[MemberNames::STORE_ID];
164 1
            $requestPath = $existingUrlRewrite[MemberNames::REQUEST_PATH];
165
166
            // append the URL rewrite with its store ID/request path
167 1
            $this->existingUrlRewrites[$storeId][$requestPath] = $existingUrlRewrite;
168 1
        }
169 1
    }
170
171
    /**
172
     * Initialize the category product with the passed attributes and returns an instance.
173
     *
174
     * @param array $attr The category product attributes
175
     *
176
     * @return array The initialized category product
177
     */
178 1
    protected function initializeUrlRewrite(array $attr)
179
    {
180
181
        // load store ID and request path
182 1
        $storeId = $attr[MemberNames::STORE_ID];
183 1
        $requestPath = $attr[MemberNames::REQUEST_PATH];
184
185
        // try to load the URL rewrite for the store ID and request path
186 1
        if ($urlRewrite = $this->getExistingUrlRewrite($storeId, $requestPath)) {
187
            // if a URL rewrite has been found, do NOT create a redirect
188
            $this->removeExistingUrlRewrite($urlRewrite);
189
190
            // if the found URL rewrite has been created manually
191
            if ((integer) $urlRewrite[MemberNames::IS_AUTOGENERATED] === 0) {
192
                // do NOT update it nor create a another redirect
193
                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...
194
            }
195
196
            // if the found URL rewrite has been autogenerated, then update it
197
            return $this->mergeEntity($urlRewrite, $attr);
198
        }
199
200
        // simple return the attributes
201 1
        return $attr;
202
    }
203
204
    /**
205
     * Initialize the URL rewrite product => category relation with the passed attributes
206
     * and returns an instance.
207
     *
208
     * @param array $attr The URL rewrite product => category relation attributes
209
     *
210
     * @return array|null The initialized URL rewrite product => category relation
211
     */
212 1
    protected function initializeUrlRewriteProductCategory($attr)
213
    {
214
215
        // initialize product and category ID
216 1
        $productId = $attr[MemberNames::PRODUCT_ID];
217 1
        $categoryId = $attr[MemberNames::CATEGORY_ID];
218
219
        // try to load the URL rewrite product category relation for the product/category ID
220 1
        if ($urlRewriteProductCategory = $this->loadUrlRewriteProductCategory($productId, $categoryId)) {
221
            return $this->mergeEntity($urlRewriteProductCategory, $attr);
222
        }
223
224
        // simple return the URL rewrite product category
225 1
        return $attr;
226
    }
227
228
    /**
229
     * Return's the unserialized metadata of the passed URL rewrite. If the
230
     * metadata doesn't contain a category ID, the category ID of the root
231
     * category will be added.
232
     *
233
     * @param array $urlRewrite The URL rewrite to return the metadata for
234
     *
235
     * @return array The metadata of the passed URL rewrite
236
     */
237 1
    protected function getMetadata($urlRewrite)
238
    {
239
240
        // initialize the array with the metaddata
241 1
        $metadata = array();
242
243
        // try to unserialize the metadata from the passed URL rewrite
244 1
        if (isset($urlRewrite[MemberNames::METADATA])) {
245 1
            $metadata = unserialize($urlRewrite[MemberNames::METADATA]);
246 1
        }
247
248
        // query whether or not a category ID has been found
249 1
        if (isset($metadata['category_id'])) {
250
            // if yes, return the metadata
251 1
            return $metadata;
252
        }
253
254
        // if not, append the ID of the root category
255 1
        $rootCategory = $this->getRootCategory();
256 1
        $metadata['category_id'] = $rootCategory[MemberNames::ENTITY_ID];
257
258
        // and return the metadata
259 1
        return $metadata;
260
    }
261
262
    /**
263
     * Return's the category with the passed ID.
264
     *
265
     * @param integer $categoryId The ID of the category to return
266
     *
267
     * @return array The category data
268
     */
269 1
    protected function getCategory($categoryId)
270
    {
271 1
        return $this->getSubject()->getCategory($categoryId);
272
    }
273
274
    /**
275
     * Return's the URL rewrites for the passed URL entity type and ID.
276
     *
277
     * @param string  $entityType The entity type to load the URL rewrites for
278
     * @param integer $entityId   The entity ID to laod the rewrites for
279
     *
280
     * @return array The URL rewrites
281
     */
282 1
    protected function getUrlRewritesByEntityTypeAndEntityId($entityType, $entityId)
283
    {
284 1
        return $this->getSubject()->getUrlRewritesByEntityTypeAndEntityId($entityType, $entityId);
285
    }
286
287
    /**
288
     * Return's the URL rewrite product category relation for the passed
289
     * product and category ID.
290
     *
291
     * @param integer $productId  The product ID to load the URL rewrite product category relation for
292
     * @param integer $categoryId The category ID to load the URL rewrite product category relation for
293
     *
294
     * @return array|false The URL rewrite product category relations
295
     */
296 1
    protected function loadUrlRewriteProductCategory($productId, $categoryId)
297
    {
298 1
        return $this->getSubject()->loadUrlRewriteProductCategory($productId, $categoryId);
299
    }
300
}
301