Completed
Push — 9.x ( 6e4dfb )
by Tim
03:49
created

UrlRewriteUpdateObserver::initializeUrlRewrite()   B

Complexity

Conditions 6
Paths 4

Size

Total Lines 30

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 30
rs 8.8177
c 0
b 0
f 0
cc 6
nc 4
nop 1
1
<?php
2
3
/**
4
 * TechDivision\Import\Category\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 2019 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-category
18
 * @link      http://www.techdivision.com
19
 */
20
21
namespace TechDivision\Import\Category\Observers;
22
23
use TechDivision\Import\Category\Utils\MemberNames;
24
use TechDivision\Import\Category\Utils\CoreConfigDataKeys;
25
use TechDivision\Import\Category\Utils\ColumnKeys;
26
use TechDivision\Import\Category\Utils\ConfigurationKeys;
27
28
/**
29
 * Observer that creates/updates the category's URL rewrites.
30
 *
31
 * @author    Tim Wagner <[email protected]>
32
 * @copyright 2019 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-category
35
 * @link      http://www.techdivision.com
36
 */
37
class UrlRewriteUpdateObserver extends UrlRewriteObserver
38
{
39
40
    /**
41
     * Array with the existing URL rewrites of the actual category.
42
     *
43
     * @var array
44
     */
45
    protected $existingUrlRewrites = array();
46
47
    /**
48
     * Return's the URL rewrite for the passed request path.
49
     *
50
     * @param string $requestPath The request path to return the URL rewrite for
51
     *
52
     * @return array|null The URL rewrite
53
     */
54
    protected function getExistingUrlRewrite($requestPath)
55
    {
56
        if (isset($this->existingUrlRewrites[$requestPath])) {
57
            return $this->existingUrlRewrites[$requestPath];
58
        }
59
    }
60
61
    /**
62
     * Remove's the passed URL rewrite from the existing one's.
63
     *
64
     * @param array $urlRewrite The URL rewrite to remove
65
     *
66
     * @return void
67
     */
68
    protected function removeExistingUrlRewrite(array $urlRewrite)
69
    {
70
71
        // load store ID and request path
72
        $requestPath = $urlRewrite[MemberNames::REQUEST_PATH];
73
74
        // query whether or not the URL rewrite exists and remove it, if available
75
        if (isset($this->existingUrlRewrites[$requestPath])) {
76
            unset($this->existingUrlRewrites[$requestPath]);
77
        }
78
    }
79
80
    /**
81
     * Process the observer's business logic.
82
     *
83
     * @return void
84
     */
85
    protected function process()
86
    {
87
88
        // process the new URL rewrites first
89
        parent::process();
90
91
        // create redirect URL rewrites for the existing URL rewrites
92
        foreach ($this->existingUrlRewrites as $existingUrlRewrite) {
93
            // query whether or not 301 redirects have to be created, so don't
94
            // create redirects if the the rewrite history has been deactivated
95
            if ($this->getSubject()->getCoreConfigData(CoreConfigDataKeys::CATALOG_SEO_SAVE_REWRITES_HISTORY, true)) {
96
                // if the URL rewrite already IS a redirect
97
                if ((integer) $existingUrlRewrite[MemberNames::REDIRECT_TYPE] !== 0 &&
98
                    (integer) $existingUrlRewrite[MemberNames::IS_AUTOGENERATED] === 0
99
                ) {
100
                    // do NOT create another redirect
101
                    continue;
102
                }
103
104
                // load target path
105
                $targetPath = $this->prepareRequestPath();
106
107
                // override data with the 301 configuration
108
                $attr = array(
109
                    MemberNames::REDIRECT_TYPE    => 301,
110
                    MemberNames::TARGET_PATH      => $targetPath,
111
                    MemberNames::IS_AUTOGENERATED => 0
112
                );
113
114
                // merge and return the prepared URL rewrite
115
                $existingUrlRewrite = $this->mergeEntity($existingUrlRewrite, $attr);
116
117
                // create the URL rewrite
118
                $this->persistUrlRewrite($existingUrlRewrite);
119
            } else {
120
                // query whether or not the URL rewrite has to be removed
121
                if ($this->getSubject()->getConfiguration()->hasParam(ConfigurationKeys::CLEAN_UP_URL_REWRITES) &&
122
                    $this->getSubject()->getConfiguration()->getParam(ConfigurationKeys::CLEAN_UP_URL_REWRITES)
123
                ) {
124
                    // delete the existing URL rewrite
125
                    $this->deleteUrlRewrite($existingUrlRewrite);
126
127
                    // log a message, that old URL rewrites have been cleaned-up
128
                    $this->getSubject()
129
                         ->getSystemLogger()
130
                         ->warning(
131
                             sprintf(
132
                                 'Cleaned-up %d URL rewrite "%s" for category with path "%s"',
133
                                 $existingUrlRewrite[MemberNames::REQUEST_PATH],
134
                                 $this->getValue(ColumnKeys::PATH)
135
                             )
136
                         );
137
                }
138
            }
139
        }
140
    }
141
142
    /**
143
     * Prepare's the URL rewrites that has to be created/updated.
144
     *
145
     * @return void
146
     */
147
    protected function prepareUrlRewrites()
148
    {
149
150
        // call the parent method
151
        parent::prepareUrlRewrites();
152
153
        // (re-)initialize the array for the existing URL rewrites
154
        $this->existingUrlRewrites = array();
155
156
        // load primary key and entity type
157
        $pk = $this->getPrimaryKey();
158
        $entityType = UrlRewriteObserver::ENTITY_TYPE;
159
160
        // load the store ID to use
161
        $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...
162
163
        // load the existing URL rewrites of the actual entity
164
        $existingUrlRewrites = $this->getUrlRewritesByEntityTypeAndEntityIdAndStoreId($entityType, $pk, $storeId);
165
166
        // prepare the existing URL rewrites to improve searching them by store ID/request path
167
        foreach ($existingUrlRewrites as $existingUrlRewrite) {
168
            // load the request path from the existing URL rewrite
169
            $requestPath = $existingUrlRewrite[MemberNames::REQUEST_PATH];
170
171
            // append the URL rewrite with its store ID/request path
172
            $this->existingUrlRewrites[$requestPath] = $existingUrlRewrite;
173
        }
174
    }
175
176
    /**
177
     * Initialize the URL rewrite with the passed attributes and returns an instance.
178
     *
179
     * @param array $attr The URL rewrite attributes
180
     *
181
     * @return array The initialized URL rewrite
182
     */
183
    protected function initializeUrlRewrite(array $attr)
184
    {
185
186
        // load store ID and request path
187
        $categoryId = $attr[MemberNames::ENTITY_ID];
188
        $requestPath = $attr[MemberNames::REQUEST_PATH];
189
190
        // iterate over the available URL rewrites to find the one that matches the category ID
191
        foreach ($this->existingUrlRewrites as $urlRewrite) {
192
            // compare the category IDs AND the request path
193
            if ($categoryId === $urlRewrite[MemberNames::ENTITY_ID] &&
194
                $requestPath === $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 && (integer) $urlRewrite[MemberNames::REDIRECT_TYPE] === 0) {
201
                    // do NOT update it nor create a 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\Cate...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
                return $this->mergeEntity($urlRewrite, $attr);
207
            }
208
        }
209
210
        // simple return the attributes
211
        return $attr;
212
    }
213
214
    /**
215
     * Return's the category with the passed ID.
216
     *
217
     * @param integer $categoryId The ID of the category to return
218
     *
219
     * @return array The category data
220
     * @throws \Exception Is thrown, if the category is not available
221
     * @deprecated Since 7.0.0
222
     */
223
    protected function getCategory($categoryId)
224
    {
225
        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\Cate...AbstractCategorySubject, TechDivision\Import\Category\Subjects\BunchSubject.

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...
226
    }
227
228
    /**
229
     * Return's the URL rewrites for the passed URL entity type and ID.
230
     *
231
     * @param string  $entityType The entity type to load the URL rewrites for
232
     * @param integer $entityId   The entity ID to load the URL rewrites for
233
     * @param integer $storeId    The store ID to load the URL rewrites for
234
     *
235
     * @return array The URL rewrites
236
     */
237
    protected function getUrlRewritesByEntityTypeAndEntityIdAndStoreId($entityType, $entityId, $storeId)
238
    {
239
        return $this->getCategoryBunchProcessor()->getUrlRewritesByEntityTypeAndEntityIdAndStoreId($entityType, $entityId, $storeId);
240
    }
241
242
    /**
243
     * Delete's the URL rewrite with the passed attributes.
244
     *
245
     * @param array       $row  The attributes of the entity to delete
246
     * @param string|null $name The name of the prepared statement that has to be executed
247
     *
248
     * @return void
249
     */
250
    protected function deleteUrlRewrite($row, $name = null)
251
    {
252
        $this->getCategoryBunchProcessor()->deleteUrlRewrite($row, $name);
253
    }
254
}
255