Completed
Pull Request — 24.x (#161)
by Tim
11:12 queued 09:52
created

UrlKeyObserver::setIds()   A

Complexity

Conditions 2
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 0
cts 4
cp 0
rs 10
c 0
b 0
f 0
cc 2
nc 1
nop 1
crap 6
1
<?php
2
3
/**
4
 * TechDivision\Import\Product\Observers\UrlKeyObserver
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\ConfigurationKeys;
24
use Zend\Filter\FilterInterface;
25
use TechDivision\Import\Utils\StoreViewCodes;
26
use TechDivision\Import\Product\Utils\MemberNames;
27
use TechDivision\Import\Product\Utils\ColumnKeys;
28
use TechDivision\Import\Utils\Filter\UrlKeyFilterTrait;
29
use TechDivision\Import\Product\Services\ProductBunchProcessorInterface;
30
use TechDivision\Import\Utils\UrlKeyUtilInterface;
31
use TechDivision\Import\Subjects\UrlKeyAwareSubjectInterface;
32
33
/**
34
 * Observer that extracts the URL key from the product name and adds a two new columns
35
 * with the their values.
36
 *
37
 * @author    Tim Wagner <[email protected]>
38
 * @copyright 2016 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-product
41
 * @link      http://www.techdivision.com
42
 */
43
class UrlKeyObserver extends AbstractProductImportObserver
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 product bunch processor instance.
62
     *
63
     * @var \TechDivision\Import\Product\Services\ProductBunchProcessorInterface
64
     */
65
    protected $productBunchProcessor;
66
67
    /**
68
     * Initialize the observer with the passed product bunch processor and filter instance.
69
     *
70
     * @param \TechDivision\Import\Product\Services\ProductBunchProcessorInterface $productBunchProcessor   The product 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
        ProductBunchProcessorInterface $productBunchProcessor,
76
        FilterInterface $convertLiteralUrlFilter,
77
        UrlKeyUtilInterface $urlKeyUtil
78
    ) {
79
        $this->productBunchProcessor = $productBunchProcessor;
80
        $this->convertLiteralUrlFilter = $convertLiteralUrlFilter;
81
        $this->urlKeyUtil = $urlKeyUtil;
82
    }
83
84
    /**
85
     * Return's the product bunch processor instance.
86
     *
87
     * @return \TechDivision\Import\Product\Services\ProductBunchProcessorInterface The product bunch processor instance
88
     */
89
    protected function getProductBunchProcessor()
90
    {
91
        return $this->productBunchProcessor;
92
    }
93
94
    /**
95
     * Process the observer's business logic.
96
     *
97
     * @return void
98
     * @throws \Exception Is thrown, if either column "url_key" or "name" have a value set
99
     */
100
    protected function process()
101
    {
102
103
        // prepare the store view code
104
        $this->getSubject()->prepareStoreViewCode();
105
106
        // set the entity ID for the product with the passed SKU
107
        if ($product = $this->loadProduct($this->getValue(ColumnKeys::SKU))) {
108
            $this->setIds($product);
109
        } else {
110
            $this->setIds(array());
111
        }
112
113
        // query whether or not the URL key column has a value
114
        if ($this->hasValue(ColumnKeys::URL_KEY)) {
115
            return;
116
        }
117
118
        // query whether or not an existing product `url_key` should recalc from product name
119
        if ($product &&
0 ignored issues
show
Bug Best Practice introduced by
The expression $product 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...
120
            !$this->getSubject()->getConfiguration()->getParam(ConfigurationKeys::UPDATE_URL_KEY_FROM_NAME, true)
121
        ) {
122
            // product already exists and NO recalc from product key,
123
            // so we search origin url_key from product
124
            $urlKey = $this->loadUrlKey(
125
                $this->getSubject(),
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...
126
                $this->getPrimaryKey()
127
            );
128
129
            // and let the `url_key` has a value
130
            if ($urlKey) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $urlKey of type string|null is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
131
                $this->setValue(
132
                    ColumnKeys::URL_KEY,
133
                    $urlKey
134
                );
135
                return;
136
            }
137
        }
138
139
        // query whether or not a product name is available
140
        if ($this->hasValue(ColumnKeys::NAME)) {
141
            $this->setValue(
142
                ColumnKeys::URL_KEY,
143
                $this->makeUnique(
144
                    $this->getSubject(),
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...
145
                    $this->convertNameToUrlKey($this->getValue(ColumnKeys::NAME))
146
                )
147
            );
148
            return;
149
        }
150
151
        // throw an exception, that the URL key can not be initialized and we're in admin store view
152
        if ($this->getSubject()->getStoreViewCode(StoreViewCodes::ADMIN) === StoreViewCodes::ADMIN) {
153
            throw new \Exception('Can\'t initialize the URL key because either columns "url_key" or "name" have a value set for default store view');
154
        }
155
    }
156
157
    /**
158
     * Temporarily persist's the IDs of the passed product.
159
     *
160
     * @param array $product The product to temporarily persist the IDs for
161
     *
162
     * @return void
163
     */
164
    protected function setIds(array $product)
165
    {
166
        $this->setLastEntityId(isset($product[MemberNames::ENTITY_ID]) ? $product[MemberNames::ENTITY_ID] : null);
167
    }
168
169
    /**
170
     * Set's the ID of the product that has been created recently.
171
     *
172
     * @param string $lastEntityId The entity ID
173
     *
174
     * @return void
175
     */
176
    protected function setLastEntityId($lastEntityId)
177
    {
178
        $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\Plugins\ExportableSubjectImpl, TechDivision\Import\Prod...\AbstractProductSubject, TechDivision\Import\Product\Subjects\BunchSubject, 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...
179
    }
180
181
    /**
182
     * Return's the PK to of the product.
183
     *
184
     * @return integer The PK to create the relation with
185
     */
186
    protected function getPrimaryKey()
187
    {
188
        $this->getSubject()->getLastEntityId();
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 getLastEntityId() does only exist in the following implementations of said interface: TechDivision\Import\Observers\EntitySubjectImpl, TechDivision\Import\Plugins\ExportableSubjectImpl, TechDivision\Import\Prod...\AbstractProductSubject, TechDivision\Import\Product\Subjects\BunchSubject, 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...
189
    }
190
191
192
    /**
193
     * Load's and return's the product with the passed SKU.
194
     *
195
     * @param string $sku The SKU of the product to load
196
     *
197
     * @return array The product
198
     */
199
    protected function loadProduct($sku)
200
    {
201
        return $this->getProductBunchProcessor()->loadProduct($sku);
202
    }
203
204
    /**
205
     * Load's and return's the url_key with the passed primary ID.
206
     *
207
     * @param \TechDivision\Import\Subjects\UrlKeyAwareSubjectInterface $subject      The subject to load the URL key
208
     * @param int                                                       $primaryKeyId The ID from product
209
     *
210
     * @return string|null url_key or null
211
     */
212
    protected function loadUrlKey(UrlKeyAwareSubjectInterface $subject, $primaryKeyId)
213
    {
214
        return $this->getUrlKeyUtil()->loadUrlKey($subject, $primaryKeyId);
0 ignored issues
show
Bug introduced by
The method loadUrlKey() does not seem to exist on object<TechDivision\Impo...ls\UrlKeyUtilInterface>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
215
    }
216
217
    /**
218
     * Returns the URL key utility instance.
219
     *
220
     * @return \TechDivision\Import\Utils\UrlKeyUtilInterface The URL key utility instance
221
     */
222
    protected function getUrlKeyUtil()
223
    {
224
        return $this->urlKeyUtil;
225
    }
226
227
    /**
228
     * Make's the passed URL key unique by adding the next number to the end.
229
     *
230
     * @param \TechDivision\Import\Subjects\UrlKeyAwareSubjectInterface $subject The subject to make the URL key unique for
231
     * @param string                                                    $urlKey  The URL key to make unique
232
     *
233
     * @return string The unique URL key
234
     */
235
    protected function makeUnique(UrlKeyAwareSubjectInterface $subject, $urlKey)
236
    {
237
        return $this->getUrlKeyUtil()->makeUnique($subject, $urlKey);
238
    }
239
}
240