Completed
Push — pac-307--update-url-key-from-n... ( 619bcb )
by
unknown
01:33
created

UrlKeyAndPathObserver::process()   C

Complexity

Conditions 10
Paths 62

Size

Total Lines 70

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 70
rs 6.7878
c 0
b 0
f 0
cc 10
nc 62
nop 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
/**
4
 * TechDivision\Import\Category\Observers\UrlKeyAndPathObserver
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\Product\Utils\ConfigurationKeys;
24
use Zend\Filter\FilterInterface;
25
use TechDivision\Import\Category\Utils\ColumnKeys;
26
use TechDivision\Import\Category\Utils\MemberNames;
27
use TechDivision\Import\Utils\StoreViewCodes;
28
use TechDivision\Import\Utils\UrlKeyUtilInterface;
29
use TechDivision\Import\Utils\Filter\UrlKeyFilterTrait;
30
use TechDivision\Import\Subjects\UrlKeyAwareSubjectInterface;
31
use TechDivision\Import\Category\Services\CategoryBunchProcessorInterface;
32
33
/**
34
 * Observer that extracts the URL key/path from the category path
35
 * and adds them as two new columns with the their values.
36
 *
37
 * @author    Tim Wagner <[email protected]>
38
 * @copyright 2019 TechDivision GmbH <[email protected]>
39
 * @license   http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
40
 * @link      https://github.com/techdivision/import-category
41
 * @link      http://www.techdivision.com
42
 */
43
class UrlKeyAndPathObserver extends AbstractCategoryImportObserver
44
{
45
46
    /**
47
     * The trait that provides string => URL key conversion functionality.
48
     *
49
     * @var \TechDivision\Import\Utils\Filter\UrlKeyFilterTrait
50
     */
51
    use UrlKeyFilterTrait;
52
53
    /**
54
     * The URL key utility instance.
55
     *
56
     * @var \TechDivision\Import\Utils\UrlKeyUtilInterface
57
     */
58
    protected $urlKeyUtil;
59
60
    /**
61
     * The category bunch processor instance.
62
     *
63
     * @var \TechDivision\Import\Category\Services\CategoryBunchProcessorInterface
64
     */
65
    protected $categoryBunchProcessor;
66
67
    /**
68
     * Initialize the observer with the passed product bunch processor instance.
69
     *
70
     * @param \TechDivision\Import\Category\Services\CategoryBunchProcessorInterface $categoryBunchProcessor  The category bunch processor instance
71
     * @param \Zend\Filter\FilterInterface                                           $convertLiteralUrlFilter The URL filter instance
72
     * @param \TechDivision\Import\Utils\UrlKeyUtilInterface                         $urlKeyUtil              The URL key utility instance
73
     */
74
    public function __construct(
75
        CategoryBunchProcessorInterface $categoryBunchProcessor,
76
        FilterInterface $convertLiteralUrlFilter,
77
        UrlKeyUtilInterface $urlKeyUtil
78
    ) {
79
80
        // set the processor and the URL filter instance
81
        $this->categoryBunchProcessor = $categoryBunchProcessor;
82
        $this->convertLiteralUrlFilter = $convertLiteralUrlFilter;
83
        $this->urlKeyUtil = $urlKeyUtil;
84
    }
85
86
    /**
87
     * Process the observer's business logic.
88
     *
89
     * @return void
90
     */
91
    protected function process()
92
    {
93
94
        // initialize the URL key and array for the categories
95
        $urlKey = null;
0 ignored issues
show
Unused Code introduced by
$urlKey is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
96
        $categories = array();
0 ignored issues
show
Unused Code introduced by
$categories is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
97
        $category = array();
98
99
        // set the entity ID for the category with the passed path
100
        try {
101
            $this->setIds($category = $this->getCategoryByPath($this->getValue(ColumnKeys::PATH)));
102
        } catch (\Exception $e) {
103
            $this->setIds(array());
104
        }
105
106
        // query whether or not the URL key column has a value
107
        if ($this->hasValue(ColumnKeys::URL_KEY)) {
108
            $urlKey = $this->makeUnique($this->getSubject(), $this->getValue(ColumnKeys::URL_KEY));
0 ignored issues
show
Documentation introduced by
$this->getSubject() is of type object<TechDivision\Impo...jects\SubjectInterface>, but the function expects a object<TechDivision\Impo...yAwareSubjectInterface>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
109
        } else {
110
            // query whether or not the column `url_key` has a value
111
            if ($category &&
0 ignored issues
show
Bug Best Practice introduced by
The expression $category of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
112
                !$this->getSubject()->getConfiguration()->getParam(ConfigurationKeys::UPDATE_URL_KEY_FROM_NAME, true)
113
            ) {
114
                // product already exists and NO new URL key
115
                // has been specified in column `url_key`, so
116
                // we stop processing here
117
                return;
118
            }
119
            $this->setValue(
120
                ColumnKeys::URL_KEY,
121
                $urlKey = $this->makeUnique($this->getSubject(), $this->convertNameToUrlKey($this->getValue(ColumnKeys::NAME)))
0 ignored issues
show
Documentation introduced by
$this->getSubject() is of type object<TechDivision\Impo...jects\SubjectInterface>, but the function expects a object<TechDivision\Impo...yAwareSubjectInterface>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
122
            );
123
        }
124
125
        // explode the path into the category names
126
        if ($categories = $this->explode($this->getValue(ColumnKeys::PATH), '/')) {
127
            // initialize the category with the actual category's URL key
128
            $categoryPaths = array($urlKey);
129
            // prepare the store view code
130
            $this->prepareStoreViewCode();
131
            // load ID of the actual store view
132
            $storeId = $this->getRowStoreId(StoreViewCodes::ADMIN);
133
134
            // iterate over the category names and try to load the category therefore
135
            for ($i = sizeof($categories) - 1; $i > 1; $i--) {
136
                try {
137
                    // prepare the expected category name
138
                    $categoryPath = implode('/', array_slice($categories, 0, $i));
139
                    // load the existing category and prepend the URL key the array with the category URL keys
140
                    $existingCategory = $this->getCategoryByPkAndStoreId($this->mapPath($categoryPath), $storeId);
141
                    // query whether or not an URL key is available or not
142
                    if (isset($existingCategory[MemberNames::URL_KEY])) {
143
                        array_unshift($categoryPaths, $existingCategory[MemberNames::URL_KEY]);
144
                    } else {
145
                        $this->getSystemLogger()->debug(sprintf('Can\'t find URL key for category %s', $categoryPath));
146
                    }
147
                } catch (\Exception $e) {
148
                    $this->getSystemLogger()->debug(sprintf('Can\'t load parent category %s', $categoryPath));
149
                }
150
            }
151
152
            // create the header for the URL path
153
            if (!$this->hasHeader(ColumnKeys::URL_PATH)) {
154
                $this->addHeader(ColumnKeys::URL_PATH);
155
            }
156
157
            // set the URL path
158
            $this->setValue(ColumnKeys::URL_PATH, implode('/', $categoryPaths));
159
        }
160
    }
161
162
    /**
163
     * Return the primary key member name.
164
     *
165
     * @return string The primary key member name
166
     */
167
    protected function getPkMemberName()
168
    {
169
        return MemberNames::ENTITY_ID;
170
    }
171
172
    /**
173
     * Returns the category bunch processor instance.
174
     *
175
     * @return \TechDivision\Import\Category\Services\CategoryBunchProcessorInterface The category bunch processor instance
176
     */
177
    protected function getCategoryBunchProcessor()
178
    {
179
        return $this->categoryBunchProcessor;
180
    }
181
182
    /**
183
     * Returns the URL key utility instance.
184
     *
185
     * @return \TechDivision\Import\Utils\UrlKeyUtilInterface The URL key utility instance
186
     */
187
    protected function getUrlKeyUtil()
188
    {
189
        return $this->urlKeyUtil;
190
    }
191
192
    /**
193
     * Return's the category with the passed path.
194
     *
195
     * @param string $path The path of the category to return
196
     *
197
     * @return array The category
198
     * @throws \Exception Is thrown, if the requested category is not available
199
     */
200
    protected function getCategoryByPath($path)
201
    {
202
        return $this->getSubject()->getCategoryByPath($path);
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 getCategoryByPath() does only exist in the following implementations of said interface: TechDivision\Import\Cate...AbstractCategorySubject, TechDivision\Import\Category\Subjects\BunchSubject, TechDivision\Import\Cate...ts\SortableBunchSubject.

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...
203
    }
204
205
    /**
206
     * Returns the category with the passed primary key and the attribute values for the passed store ID.
207
     *
208
     * @param string  $pk      The primary key of the category to return
209
     * @param integer $storeId The store ID of the category values
210
     *
211
     * @return array|null The category data
212
     */
213
    protected function getCategoryByPkAndStoreId($pk, $storeId)
214
    {
215
        return $this->getCategoryBunchProcessor()->getCategoryByPkAndStoreId($pk, $storeId);
216
    }
217
218
    /**
219
     * Temporarily persist's the IDs of the passed category.
220
     *
221
     * @param array $category The category to temporarily persist the IDs for
222
     *
223
     * @return void
224
     */
225
    protected function setIds(array $category)
226
    {
227
        $this->setLastEntityId(isset($category[$this->getPkMemberName()]) ? $category[$this->getPkMemberName()] : null);
228
    }
229
230
    /**
231
     * Set's the ID of the category that has been created recently.
232
     *
233
     * @param string $lastEntityId The entity ID
234
     *
235
     * @return void
236
     */
237
    protected function setLastEntityId($lastEntityId)
238
    {
239
        $this->getSubject()->setLastEntityId($lastEntityId);
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 setLastEntityId() does only exist in the following implementations of said interface: TechDivision\Import\Cate...AbstractCategorySubject, TechDivision\Import\Category\Subjects\BunchSubject, TechDivision\Import\Cate...ts\SortableBunchSubject, TechDivision\Import\Plugins\ExportableSubjectImpl, TechDivision\Import\Subjects\ExportableTraitImpl.

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...
240
    }
241
242
    /**
243
     * Make's the passed URL key unique by adding the next number to the end.
244
     *
245
     * @param \TechDivision\Import\Subjects\UrlKeyAwareSubjectInterface $subject The subject to make the URL key unique for
246
     * @param string                                                    $urlKey  The URL key to make unique
247
     *
248
     * @return string The unique URL key
249
     */
250
    protected function makeUnique(UrlKeyAwareSubjectInterface $subject, $urlKey)
251
    {
252
        return $this->getUrlKeyUtil()->makeUnique($subject, $urlKey);
253
    }
254
}
255