Completed
Push — master ( baa810...02b974 )
by Tim
10s
created

UrlRewriteObserver::convertNameToUrlKey()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 0
cts 2
cp 0
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 1
crap 2
1
<?php
2
3
/**
4
 * TechDivision\Import\Product\Observers\UrlRewriteObserver
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\ColumnKeys;
24
use TechDivision\Import\Product\Utils\MemberNames;
25
use TechDivision\Import\Utils\Filter\ConvertLiteralUrl;
26
use TechDivision\Import\Product\Observers\AbstractProductImportObserver;
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
35
 * @link      http://www.techdivision.com
36
 */
37
class UrlRewriteObserver extends AbstractProductImportObserver
38
{
39
40
    /**
41
     * The entity type to load the URL rewrites for.
42
     *
43
     * @var string
44
     */
45
    const ENTITY_TYPE = 'product';
46
47
    /**
48
     * The URL key from the CSV file column that has to be processed by the observer.
49
     *
50
     * @var string
51
     */
52
    protected $urlKey;
53
54
    /**
55
     * The actual category ID to process.
56
     *
57
     * @var integer
58
     */
59
    protected $categoryId;
60
61
    /**
62
     * The actual entity ID to process.
63
     *
64
     * @var integer
65
     */
66
    protected $entityId;
67
68
    /**
69
     * The array with the URL rewrites that has to be created.
70
     *
71
     * @var array
72
     */
73
    protected $urlRewrites = array();
74
75
    /**
76
     * Process the observer's business logic.
77
     *
78
     * @return void
79
     */
80 3
    protected function process()
81
    {
82
83
        // query whether or not, we've found a new SKU => means we've found a new product
84 3
        if ($this->hasBeenProcessed($this->getValue(ColumnKeys::SKU))) {
85
            return;
86
        }
87
88
        // try to load the URL key, return immediately if not possible
89 3
        if ($this->hasValue(ColumnKeys::URL_KEY)) {
90 3
            $this->urlKey = $this->getValue(ColumnKeys::URL_KEY);
91
        } else {
92
            return;
93
        }
94
95
        // initialize the store view code
96 3
        $this->prepareStoreViewCode();
97
98
        // prepare the URL rewrites
99 3
        $this->prepareUrlRewrites();
100
101
        // iterate over the categories and create the URL rewrites
102 3
        foreach ($this->urlRewrites as $categoryId => $urlRewrite) {
103
            // initialize and persist the URL rewrite
104 3
            if ($urlRewrite = $this->initializeUrlRewrite($urlRewrite)) {
105
                // initialize URL rewrite and catagory ID
106 3
                $this->categoryId = $categoryId;
0 ignored issues
show
Documentation Bug introduced by
It seems like $categoryId can also be of type string. However, the property $categoryId is declared as type integer. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
107 3
                $this->entityId = $urlRewrite[MemberNames::ENTITY_ID];
108 3
                $this->urlRewriteId = $this->persistUrlRewrite($urlRewrite);
0 ignored issues
show
Bug introduced by
The property urlRewriteId does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
109
110
                // initialize and persist the URL rewrite product => category relation
111 3
                $urlRewriteProductCategory = $this->initializeUrlRewriteProductCategory(
112 3
                    $this->prepareUrlRewriteProductCategoryAttributes()
113
                );
114
115
                // create a URL rewrite product category relation, if not available yet
116 3
                if ($urlRewriteProductCategory === null) {
117
                    continue;
118
                }
119
120
                // persist the URL rewrite product category relation
121 3
                $this->persistUrlRewriteProductCategory($urlRewriteProductCategory);
122
            }
123
        }
124 3
    }
125
126
    /**
127
     * Initialize the category product with the passed attributes and returns an instance.
128
     *
129
     * @param array $attr The category product attributes
130
     *
131
     * @return array The initialized category product
132
     */
133 2
    protected function initializeUrlRewrite(array $attr)
134
    {
135 2
        return $attr;
136
    }
137
138
    /**
139
     * Initialize the URL rewrite product => category relation with the passed attributes
140
     * and returns an instance.
141
     *
142
     * @param array $attr The URL rewrite product => category relation attributes
143
     *
144
     * @return array The initialized URL rewrite product => category relation
145
     */
146 2
    protected function initializeUrlRewriteProductCategory($attr)
147
    {
148 2
        return $attr;
149
    }
150
151
    /**
152
     * Prepare's the URL rewrites that has to be created/updated.
153
     *
154
     * @return void
155
     */
156 3
    protected function prepareUrlRewrites()
157
    {
158
159
        // (re-)initialize the array for the URL rewrites
160 3
        $this->urlRewrites = array();
161
162
        // load the root category, because we need that to create the default product URL rewrite
163 3
        $rootCategory = $this->getRootCategory();
164
165
        // add the root category ID to the category => product relations
166 3
        $productCategoryIds = $this->getProductCategoryIds();
167 3
        $productCategoryIds[$rootCategory[MemberNames::ENTITY_ID]] = $this->getLastEntityId();
168
169
        // prepare the URL rewrites
170 3
        foreach ($productCategoryIds as $categoryId => $entityId) {
171
            // set category/entity ID
172 3
            $this->categoryId = $categoryId;
173 3
            $this->entityId = $entityId;
0 ignored issues
show
Documentation Bug introduced by
The property $entityId was declared of type integer, but $entityId is of type string. Maybe add a type cast?

This check looks for assignments to scalar types that may be of the wrong type.

To ensure the code behaves as expected, it may be a good idea to add an explicit type cast.

$answer = 42;

$correct = false;

$correct = (bool) $answer;
Loading history...
174
175
            // prepare the attributes for each URL rewrite
176 3
            $this->urlRewrites[$categoryId] = $this->prepareAttributes();
177
        }
178 3
    }
179
180
    /**
181
     * Prepare the attributes of the entity that has to be persisted.
182
     *
183
     * @return array The prepared attributes
184
     */
185 3
    protected function prepareAttributes()
186
    {
187
188
        // load the store ID to use
189 3
        $storeId = $this->getRowStoreId();
190
191
        // load the category to create the URL rewrite for
192 3
        $category = $this->getCategory($this->categoryId);
193
194
        // initialize the values
195 3
        $requestPath = $this->prepareRequestPath($category);
196 3
        $targetPath = $this->prepareTargetPath($category);
197 3
        $metadata = serialize($this->prepareMetadata($category));
198
199
        // return the prepared URL rewrite
200 3
        return $this->initializeEntity(
201
            array(
202 3
                MemberNames::ENTITY_TYPE      => UrlRewriteObserver::ENTITY_TYPE,
203 3
                MemberNames::ENTITY_ID        => $this->entityId,
204 3
                MemberNames::REQUEST_PATH     => $requestPath,
205 3
                MemberNames::TARGET_PATH      => $targetPath,
206 3
                MemberNames::REDIRECT_TYPE    => 0,
207 3
                MemberNames::STORE_ID         => $storeId,
208 3
                MemberNames::DESCRIPTION      => null,
209 3
                MemberNames::IS_AUTOGENERATED => 1,
210 3
                MemberNames::METADATA         => $metadata
211
            )
212
        );
213
    }
214
215
    /**
216
     * Prepare's the URL rewrite product => category relation attributes.
217
     *
218
     * @return arry The prepared attributes
219
     */
220 3
    protected function prepareUrlRewriteProductCategoryAttributes()
221
    {
222
223
        // return the prepared product
224 3
        return $this->initializeEntity(
225
            array(
226 3
                MemberNames::PRODUCT_ID => $this->entityId,
227 3
                MemberNames::CATEGORY_ID => $this->categoryId,
228 3
                MemberNames::URL_REWRITE_ID => $this->urlRewriteId
229
            )
230
        );
231
    }
232
233
    /**
234
     * Prepare's the target path for a URL rewrite.
235
     *
236
     * @param array $category The categroy with the URL path
237
     *
238
     * @return string The target path
239
     */
240 3
    protected function prepareTargetPath(array $category)
241
    {
242
243
        // load the actual entity ID
244 3
        $lastEntityId = $this->getPrimaryKey();
245
246
        // query whether or not, the category is the root category
247 3
        if ($this->isRootCategory($category)) {
248 3
            $targetPath = sprintf('catalog/product/view/id/%d', $lastEntityId);
249
        } else {
250 2
            $targetPath = sprintf('catalog/product/view/id/%d/category/%d', $lastEntityId, $category[MemberNames::ENTITY_ID]);
251
        }
252
253
        // return the target path
254 3
        return $targetPath;
255
    }
256
257
    /**
258
     * Prepare's the request path for a URL rewrite or the target path for a 301 redirect.
259
     *
260
     * @param array $category The categroy with the URL path
261
     *
262
     * @return string The request path
263
     */
264 3
    protected function prepareRequestPath(array $category)
265
    {
266
267
        // query whether or not, the category is the root category
268 3
        if ($this->isRootCategory($category)) {
269 3
            $requestPath = sprintf('%s.html', $this->urlKey);
270
        } else {
271 2
            $requestPath = sprintf('%s/%s.html', $category[MemberNames::URL_PATH], $this->urlKey);
272
        }
273
274
        // return the request path
275 3
        return $requestPath;
276
    }
277
278
    /**
279
     * Prepare's the URL rewrite's metadata with the passed category values.
280
     *
281
     * @param array $category The category used for preparation
282
     *
283
     * @return array The metadata
284
     */
285 3
    protected function prepareMetadata(array $category)
286
    {
287
288
        // initialize the metadata
289 3
        $metadata = array();
290
291
        // query whether or not, the passed category IS the root category
292 3
        if ($this->isRootCategory($category)) {
293 3
            return $metadata;
294
        }
295
296
        // if not, set the category ID in the metadata
297 2
        $metadata['category_id'] = $category[MemberNames::ENTITY_ID];
298
299
        // return the metadata
300 2
        return $metadata;
301
    }
302
303
    /**
304
     * Initialize's and return's the URL key filter.
305
     *
306
     * @return \TechDivision\Import\Utils\ConvertLiteralUrl The URL key filter
307
     */
308
    protected function getUrlKeyFilter()
309
    {
310
        return new ConvertLiteralUrl();
311
    }
312
313
    /**
314
     * Convert's the passed string into a valid URL key.
315
     *
316
     * @param string $string The string to be converted, e. g. the product name
317
     *
318
     * @return string The converted string as valid URL key
319
     */
320
    protected function convertNameToUrlKey($string)
321
    {
322
        return $this->getUrlKeyFilter()->filter($string);
323
    }
324
325
    /**
326
     * Return's the root category for the actual view store.
327
     *
328
     * @return array The store's root category
329
     * @throws \Exception Is thrown if the root category for the passed store code is NOT available
330
     */
331 3
    protected function getRootCategory()
332
    {
333 3
        return $this->getSubject()->getRootCategory();
334
    }
335
336
    /**
337
     * Return's TRUE if the passed category IS the root category, else FALSE.
338
     *
339
     * @param array $category The category to query
340
     *
341
     * @return boolean TRUE if the passed category IS the root category
342
     */
343 3
    protected function isRootCategory(array $category)
344
    {
345
346
        // load the root category
347 3
        $rootCategory = $this->getRootCategory();
348
349
        // compare the entity IDs and return the result
350 3
        return $rootCategory[MemberNames::ENTITY_ID] === $category[MemberNames::ENTITY_ID];
351
    }
352
353
    /**
354
     * Return's the store ID of the actual row, or of the default store
355
     * if no store view code is set in the CSV file.
356
     *
357
     * @param string|null $default The default store view code to use, if no store view code is set in the CSV file
358
     *
359
     * @return integer The ID of the actual store
360
     * @throws \Exception Is thrown, if the store with the actual code is not available
361
     */
362 3
    protected function getRowStoreId($default = null)
363
    {
364 3
        return $this->getSubject()->getRowStoreId($default);
365
    }
366
367
    /**
368
     * Return's the list with category IDs the product is related with.
369
     *
370
     * @return array The product's category IDs
371
     */
372 3
    protected function getProductCategoryIds()
373
    {
374 3
        return $this->getSubject()->getProductCategoryIds();
375
    }
376
377
    /**
378
     * Return's the category with the passed ID.
379
     *
380
     * @param integer $categoryId The ID of the category to return
381
     *
382
     * @return array The category data
383
     */
384 3
    protected function getCategory($categoryId)
385
    {
386 3
        return $this->getSubject()->getCategory($categoryId);
387
    }
388
389
    /**
390
     * Persist's the URL rewrite with the passed data.
391
     *
392
     * @param array $row The URL rewrite to persist
393
     *
394
     * @return string The ID of the persisted entity
395
     */
396 3
    protected function persistUrlRewrite($row)
397
    {
398 3
        return $this->getSubject()->persistUrlRewrite($row);
399
    }
400
401
    /**
402
     * Persist's the URL rewrite product => category relation with the passed data.
403
     *
404
     * @param array $row The URL rewrite product => category relation to persist
405
     *
406
     * @return void
407
     */
408 3
    protected function persistUrlRewriteProductCategory($row)
409
    {
410 3
        return $this->getSubject()->persistUrlRewriteProductCategory($row);
411
    }
412
413
    /**
414
     * Return's the PK to create the product => attribute relation.
415
     *
416
     * @return integer The PK to create the relation with
417
     */
418 3
    protected function getPrimaryKey()
419
    {
420 3
        return $this->getLastEntityId();
421
    }
422
}
423