Completed
Push — master ( de89b2...4a1c34 )
by Tim
10s
created

UrlRewriteUpdateObserver   A

Complexity

Total Complexity 22

Size/Duplication

Total Lines 260
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1

Test Coverage

Coverage 80.28%

Importance

Changes 0
Metric Value
wmc 22
lcom 1
cbo 1
dl 0
loc 260
ccs 57
cts 71
cp 0.8028
rs 10
c 0
b 0
f 0

9 Methods

Rating   Name   Duplication   Size   Complexity  
A getExistingUrlRewrite() 0 6 2
A removeExistingUrlRewrite() 0 12 2
B process() 0 56 6
B prepareUrlRewrites() 0 26 2
B initializeUrlRewrite() 0 26 3
A initializeUrlRewriteProductCategory() 0 15 2
B getMetadata() 0 24 3
A getUrlRewritesByEntityTypeAndEntityId() 0 4 1
A loadUrlRewriteProductCategory() 0 4 1
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
0 ignored issues
show
Coding Style introduced by
Blank line found at end of control structure
Loading history...
203
        }
204
205
        // simple return the attributes
206 1
        return $attr;
207
    }
208
209
    /**
210
     * Initialize the URL rewrite product => category relation with the passed attributes
211
     * and returns an instance.
212
     *
213
     * @param array $attr The URL rewrite product => category relation attributes
214
     *
215
     * @return array|null The initialized URL rewrite product => category relation
216
     */
217 1
    protected function initializeUrlRewriteProductCategory($attr)
218
    {
219
220
        // initialize product and category ID
221 1
        $productId = $attr[MemberNames::PRODUCT_ID];
222 1
        $categoryId = $attr[MemberNames::CATEGORY_ID];
223
224
        // try to load the URL rewrite product category relation for the product/category ID
225 1
        if ($urlRewriteProductCategory = $this->loadUrlRewriteProductCategory($productId, $categoryId)) {
226
            return $this->mergeEntity($urlRewriteProductCategory, $attr);
227
        }
228
229
        // simple return the URL rewrite product category
230 1
        return $attr;
231
    }
232
233
    /**
234
     * Return's the unserialized metadata of the passed URL rewrite. If the
235
     * metadata doesn't contain a category ID, the category ID of the root
236
     * category will be added.
237
     *
238
     * @param array $urlRewrite The URL rewrite to return the metadata for
239
     *
240
     * @return array The metadata of the passed URL rewrite
241
     */
242 1
    protected function getMetadata($urlRewrite)
243
    {
244
245
        // initialize the array with the metaddata
246 1
        $metadata = array();
247
248
        // try to unserialize the metadata from the passed URL rewrite
249 1
        if (isset($urlRewrite[MemberNames::METADATA])) {
250 1
            $metadata = unserialize($urlRewrite[MemberNames::METADATA]);
251
        }
252
253
        // query whether or not a category ID has been found
254 1
        if (isset($metadata['category_id'])) {
255
            // if yes, return the metadata
256 1
            return $metadata;
257
        }
258
259
        // if not, append the ID of the root category
260 1
        $rootCategory = $this->getRootCategory();
261 1
        $metadata['category_id'] = $rootCategory[MemberNames::ENTITY_ID];
262
263
        // and return the metadata
264 1
        return $metadata;
265
    }
266
267
    /**
268
     * Return's the URL rewrites for the passed URL entity type and ID.
269
     *
270
     * @param string  $entityType The entity type to load the URL rewrites for
271
     * @param integer $entityId   The entity ID to laod the rewrites for
272
     *
273
     * @return array The URL rewrites
274
     */
275 1
    protected function getUrlRewritesByEntityTypeAndEntityId($entityType, $entityId)
276
    {
277 1
        return $this->getSubject()->getUrlRewritesByEntityTypeAndEntityId($entityType, $entityId);
278
    }
279
280
    /**
281
     * Return's the URL rewrite product category relation for the passed
282
     * product and category ID.
283
     *
284
     * @param integer $productId  The product ID to load the URL rewrite product category relation for
285
     * @param integer $categoryId The category ID to load the URL rewrite product category relation for
286
     *
287
     * @return array|false The URL rewrite product category relations
288
     */
289 1
    protected function loadUrlRewriteProductCategory($productId, $categoryId)
290
    {
291 1
        return $this->getSubject()->loadUrlRewriteProductCategory($productId, $categoryId);
292
    }
293
}
294