Completed
Push — 17.x ( 980e44...452257 )
by Tim
01:57
created

UrlKeyAndPathObserver::setIds()   A

Complexity

Conditions 2
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 2
nc 1
nop 1
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 Zend\Filter\FilterInterface;
24
use TechDivision\Import\Category\Utils\ColumnKeys;
25
use TechDivision\Import\Category\Utils\MemberNames;
26
use TechDivision\Import\Utils\UrlKeyUtilInterface;
27
use TechDivision\Import\Utils\Filter\UrlKeyFilterTrait;
28
use TechDivision\Import\Utils\StoreViewCodes;
29
use TechDivision\Import\Category\Services\CategoryBunchProcessorInterface;
30
use TechDivision\Import\Subjects\UrlKeyAwareSubjectInterface;
31
32
/**
33
 * Observer that extracts the URL key/path from the category path
34
 * and adds them as two new columns with the their values.
35
 *
36
 * @author    Tim Wagner <[email protected]>
37
 * @copyright 2019 TechDivision GmbH <[email protected]>
38
 * @license   http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
39
 * @link      https://github.com/techdivision/import-category
40
 * @link      http://www.techdivision.com
41
 */
42
class UrlKeyAndPathObserver extends AbstractCategoryImportObserver
43
{
44
45
    /**
46
     * The trait that provides string => URL key conversion functionality.
47
     *
48
     * @var \TechDivision\Import\Utils\Filter\UrlKeyFilterTrait
49
     */
50
    use UrlKeyFilterTrait;
51
52
    /**
53
     * The URL key utility instance.
54
     *
55
     * @var \TechDivision\Import\Utils\UrlKeyUtilInterface
56
     */
57
    protected $urlKeyUtil;
58
59
    /**
60
     * The category bunch processor instance.
61
     *
62
     * @var \TechDivision\Import\Category\Services\CategoryBunchProcessorInterface
63
     */
64
    protected $categoryBunchProcessor;
65
66
    /**
67
     * Initialize the observer with the passed product bunch processor instance.
68
     *
69
     * @param \TechDivision\Import\Category\Services\CategoryBunchProcessorInterface $categoryBunchProcessor  The category bunch processor instance
70
     * @param \Zend\Filter\FilterInterface                                           $convertLiteralUrlFilter The URL filter instance
71
     * @param \TechDivision\Import\Utils\UrlKeyUtilInterface                         $urlKeyUtil              The URL key utility instance
72
     */
73
    public function __construct(
74
        CategoryBunchProcessorInterface $categoryBunchProcessor,
75
        FilterInterface $convertLiteralUrlFilter,
76
        UrlKeyUtilInterface $urlKeyUtil
77
    ) {
78
79
        // set the processor and the URL filter instance
80
        $this->categoryBunchProcessor = $categoryBunchProcessor;
81
        $this->convertLiteralUrlFilter = $convertLiteralUrlFilter;
82
        $this->urlKeyUtil = $urlKeyUtil;
83
    }
84
85
    /**
86
     * Process the observer's business logic.
87
     *
88
     * @return void
89
     */
90
    protected function process()
91
    {
92
93
        // initialize the URL key and array for the categories
94
        $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...
95
        $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...
96
97
        // set the entity ID for the category with the passed path
98
        try {
99
            $this->setIds($this->getCategoryByPath($this->getValue(ColumnKeys::PATH)));
100
        } catch (\Exception $e) {
101
            $this->setIds(array());
102
        }
103
104
        // query whether or not the URL key column has a value
105
        if ($this->hasValue(ColumnKeys::URL_KEY)) {
106
            $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...
107
        } else {
108
            $this->setValue(
109
                ColumnKeys::URL_KEY,
110
                $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...
111
            );
112
        }
113
114
        // explode the path into the category names
115
        if ($categories = $this->explode($this->getValue(ColumnKeys::PATH), '/')) {
116
            // initialize the category with the actual category's URL key
117
            $categoryPaths = array($urlKey);
118
            // prepare the store view code
119
            $this->prepareStoreViewCode();
120
            // load ID of the actual store view
121
            $storeId = $this->getRowStoreId(StoreViewCodes::ADMIN);
122
123
            // iterate over the category names and try to load the category therefore
124
            for ($i = sizeof($categories) - 1; $i > 1; $i--) {
125
                try {
126
                    // prepare the expected category name
127
                    $categoryPath = implode('/', array_slice($categories, 0, $i));
128
                    // load the existing category and prepend the URL key the array with the category URL keys
129
                    $existingCategory = $this->getCategoryByPkAndStoreId($this->mapPath($categoryPath), $storeId);
130
                    // query whether or not an URL key is available or not
131
                    if (isset($existingCategory[MemberNames::URL_KEY])) {
132
                        array_unshift($categoryPaths, $existingCategory[MemberNames::URL_KEY]);
133
                    } else {
134
                        $this->getSystemLogger()->debug(sprintf('Can\'t find URL key for category %s', $categoryPath));
135
                    }
136
                } catch (\Exception $e) {
137
                    $this->getSystemLogger()->debug(sprintf('Can\'t load parent category %s', $categoryPath));
138
                }
139
            }
140
141
            // create the header for the URL path
142
            if (!$this->hasHeader(ColumnKeys::URL_PATH)) {
143
                $this->addHeader(ColumnKeys::URL_PATH);
144
            }
145
146
            // set the URL path
147
            $this->setValue(ColumnKeys::URL_PATH, implode('/', $categoryPaths));
148
        }
149
    }
150
151
    /**
152
     * Return the primary key member name.
153
     *
154
     * @return string The primary key member name
155
     */
156
    protected function getPkMemberName()
157
    {
158
        return MemberNames::ENTITY_ID;
159
    }
160
161
    /**
162
     * Returns the category bunch processor instance.
163
     *
164
     * @return \TechDivision\Import\Category\Services\CategoryBunchProcessorInterface The category bunch processor instance
165
     */
166
    protected function getCategoryBunchProcessor()
167
    {
168
        return $this->categoryBunchProcessor;
169
    }
170
171
    /**
172
     * Returns the URL key utility instance.
173
     *
174
     * @return \TechDivision\Import\Utils\UrlKeyUtilInterface The URL key utility instance
175
     */
176
    protected function getUrlKeyUtil()
177
    {
178
        return $this->urlKeyUtil;
179
    }
180
181
    /**
182
     * Return's the category with the passed path.
183
     *
184
     * @param string $path The path of the category to return
185
     *
186
     * @return array The category
187
     * @throws \Exception Is thrown, if the requested category is not available
188
     */
189
    protected function getCategoryByPath($path)
190
    {
191
        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.

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...
192
    }
193
194
    /**
195
     * Returns the category with the passed primary key and the attribute values for the passed store ID.
196
     *
197
     * @param string  $pk      The primary key of the category to return
198
     * @param integer $storeId The store ID of the category values
199
     *
200
     * @return array|null The category data
201
     */
202
    protected function getCategoryByPkAndStoreId($pk, $storeId)
203
    {
204
        return $this->getCategoryBunchProcessor()->getCategoryByPkAndStoreId($pk, $storeId);
205
    }
206
207
    /**
208
     * Temporarily persist's the IDs of the passed category.
209
     *
210
     * @param array $category The category to temporarily persist the IDs for
211
     *
212
     * @return void
213
     */
214
    protected function setIds(array $category)
215
    {
216
        $this->setLastEntityId(isset($category[$this->getPkMemberName()]) ? $category[$this->getPkMemberName()] : null);
217
    }
218
219
    /**
220
     * Set's the ID of the category that has been created recently.
221
     *
222
     * @param string $lastEntityId The entity ID
223
     *
224
     * @return void
225
     */
226
    protected function setLastEntityId($lastEntityId)
227
    {
228
        $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\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...
229
    }
230
231
    /**
232
     * Make's the passed URL key unique by adding the next number to the end.
233
     *
234
     * @param string $urlKey The URL key to make unique
235
     *
236
     * @return string The unique URL key
237
     */
238
    protected function makeUnique(UrlKeyAwareSubjectInterface $subject, $urlKey)
239
    {
240
        return $this->getUrlKeyUtil()->makeUnique($subject, $urlKey);
241
    }
242
}
243