Completed
Push — pac-307--update-url-key-from-n... ( a116f0 )
by
unknown
08:52
created

ProductUrlRewriteObserver::process()   C

Complexity

Conditions 9
Paths 8

Size

Total Lines 82

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 82
rs 6.8371
c 0
b 0
f 0
cc 9
nc 8
nop 0

How to fix   Long Method   

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\Product\UrlRewrite\Observers\ProductUrlRewriteObserver
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-url-rewrite
18
 * @link      http://www.techdivision.com
19
 */
20
21
namespace TechDivision\Import\Product\UrlRewrite\Observers;
22
23
use TechDivision\Import\Utils\StoreViewCodes;
24
use TechDivision\Import\Product\UrlRewrite\Utils\ColumnKeys;
25
use TechDivision\Import\Product\Observers\AbstractProductImportObserver;
26
27
/**
28
 * Observer that extracts the URL rewrite data to a specific CSV file.
29
 *
30
 * @author    Tim Wagner <[email protected]>
31
 * @copyright 2016 TechDivision GmbH <[email protected]>
32
 * @license   http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
33
 * @link      https://github.com/techdivision/import-product-url-rewrite
34
 * @link      http://www.techdivision.com
35
 */
36
class ProductUrlRewriteObserver extends AbstractProductImportObserver
37
{
38
39
    /**
40
     * The artefact type.
41
     *
42
     * @var string
43
     */
44
    const ARTEFACT_TYPE = 'url-rewrite';
45
46
    /**
47
     * The image artefacts that has to be exported.
48
     *
49
     * @var array
50
     */
51
    protected $artefacts = array();
52
53
    /**
54
     * Process the observer's business logic.
55
     *
56
     * @return array The processed row
57
     */
58
    protected function process()
59
    {
60
61
        // do nothing if the column `url_key` is empty
62
        if ($this->hasValue(ColumnKeys::URL_KEY) === false) {
63
            return;
64
        }
65
66
        // initialize the array for the artefacts and the store view codes
67
        $this->artefacts = array();
68
        $storeViewCodes = array();
69
70
        // load the SKU from the row
71
        $sku = $this->getValue(ColumnKeys::SKU);
72
73
        // prepare the store view code
74
        $this->getSubject()->prepareStoreViewCode();
75
76
        // try to load the store view code
77
        $storeViewCode = $this->getSubject()->getStoreViewCode(StoreViewCodes::ADMIN);
78
79
        // query whether or not we've a store view code
80
        if ($storeViewCode === StoreViewCodes::ADMIN) {
81
            // if not, load the websites the product is related with
82
            $websiteCodes = $this->getValue(ColumnKeys::PRODUCT_WEBSITES, array(), array($this, 'explode'));
83
84
            // load the store view codes of all websites
85
            foreach ($websiteCodes as $websiteCode) {
86
                $storeViewCodes = array_merge($storeViewCodes, $this->getStoreViewCodesByWebsiteCode($websiteCode));
87
            }
88
        } else {
89
            array_push($storeViewCodes, $storeViewCode);
90
        }
91
92
        // iterate over the available image fields
93
        foreach ($storeViewCodes as $storeViewCode) {
94
            // iterate over the store view codes and query if artefacts are already available
95
            if ($this->hasArtefactsByTypeAndEntityId(ProductUrlRewriteObserver::ARTEFACT_TYPE, $lastEntityId = $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\Prod...jects\UrlRewriteSubject, 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...
96
                // if yes, load the artefacs
97
                $this->artefacts = $this->getArtefactsByTypeAndEntityId(ProductUrlRewriteObserver::ARTEFACT_TYPE, $lastEntityId);
98
99
                // override the existing data with the store view specific one
100
                for ($i = 0; $i < sizeof($this->artefacts); $i++) {
0 ignored issues
show
Performance Best Practice introduced by
It seems like you are calling the size function sizeof() as part of the test condition. You might want to compute the size beforehand, and not on each iteration.

If the size of the collection does not change during the iteration, it is generally a good practice to compute it beforehand, and not on each iteration:

for ($i=0; $i<count($array); $i++) { // calls count() on each iteration
}

// Better
for ($i=0, $c=count($array); $i<$c; $i++) { // calls count() just once
}
Loading history...
101
                    // query whether or not a URL key has be specfied and the store view codes are equal
102
                    if ($this->hasValue(ColumnKeys::URL_KEY) && $this->artefacts[$i][ColumnKeys::STORE_VIEW_CODE] === $storeViewCode) {
103
                        // update the URL key
104
                        $this->artefacts[$i][ColumnKeys::URL_KEY] = $this->getValue(ColumnKeys::URL_KEY);
105
106
                        // also update filename and line number
107
                        $this->artefacts[$i][ColumnKeys::ORIGINAL_DATA][ColumnKeys::ORIGINAL_FILENAME] = $this->getSubject()->getFilename();
108
                        $this->artefacts[$i][ColumnKeys::ORIGINAL_DATA][ColumnKeys::ORIGINAL_LINE_NUMBER] = $this->getSubject()->getLineNumber();
109
                    }
110
                }
111
            } else {
112
                // if no arefacts are available, append new data
113
                $artefact = $this->newArtefact(
114
                    array(
115
                        ColumnKeys::SKU                => $sku,
116
                        ColumnKeys::STORE_VIEW_CODE    => $storeViewCode,
117
                        ColumnKeys::CATEGORIES         => $this->getValue(ColumnKeys::CATEGORIES),
118
                        ColumnKeys::PRODUCT_WEBSITES   => $this->getValue(ColumnKeys::PRODUCT_WEBSITES),
119
                        ColumnKeys::VISIBILITY         => $this->getValue(ColumnKeys::VISIBILITY),
120
                        ColumnKeys::URL_KEY            => $this->getValue(ColumnKeys::URL_KEY)
121
                    ),
122
                    array(
123
                        ColumnKeys::SKU                => ColumnKeys::SKU,
124
                        ColumnKeys::STORE_VIEW_CODE    => ColumnKeys::STORE_VIEW_CODE,
125
                        ColumnKeys::CATEGORIES         => ColumnKeys::CATEGORIES,
126
                        ColumnKeys::PRODUCT_WEBSITES   => ColumnKeys::PRODUCT_WEBSITES,
127
                        ColumnKeys::VISIBILITY         => ColumnKeys::VISIBILITY,
128
                        ColumnKeys::URL_KEY            => ColumnKeys::URL_KEY,
129
                    )
130
                );
131
132
                // append the base image to the artefacts
133
                $this->artefacts[] = $artefact;
134
            }
135
        }
136
137
        // append the artefacts that has to be exported to the subject
138
        $this->addArtefacts($this->artefacts);
139
    }
140
141
    /**
142
     * Returns an array with the codes of the store views related with the passed website code.
143
     *
144
     * @param string $websiteCode The code of the website to return the store view codes for
145
     *
146
     * @return array The array with the matching store view codes
147
     */
148
    protected function getStoreViewCodesByWebsiteCode($websiteCode)
149
    {
150
        return $this->getSubject()->getStoreViewCodesByWebsiteCode($websiteCode);
0 ignored issues
show
Bug introduced by
The method getStoreViewCodesByWebsiteCode() does not exist on TechDivision\Import\Subjects\SubjectInterface. Did you maybe mean getStoreViewCode()?

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...
151
    }
152
153
    /**
154
     * Queries whether or not artefacts for the passed type and entity ID are available.
155
     *
156
     * @param string $type     The artefact type, e. g. configurable
157
     * @param string $entityId The entity ID to return the artefacts for
158
     *
159
     * @return boolean TRUE if artefacts are available, else FALSE
160
     */
161
    protected function hasArtefactsByTypeAndEntityId($type, $entityId)
162
    {
163
        return $this->getSubject()->hasArtefactsByTypeAndEntityId($type, $entityId);
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 hasArtefactsByTypeAndEntityId() does only exist in the following implementations of said interface: 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...
164
    }
165
166
    /**
167
     * Return the artefacts for the passed type and entity ID.
168
     *
169
     * @param string $type     The artefact type, e. g. configurable
170
     * @param string $entityId The entity ID to return the artefacts for
171
     *
172
     * @return array The array with the artefacts
173
     * @throws \Exception Is thrown, if no artefacts are available
174
     */
175
    protected function getArtefactsByTypeAndEntityId($type, $entityId)
176
    {
177
        return $this->getSubject()->getArtefactsByTypeAndEntityId($type, $entityId);
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 getArtefactsByTypeAndEntityId() does only exist in the following implementations of said interface: TechDivision\Import\Plugins\ExportableSubjectImpl, 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...
178
    }
179
180
    /**
181
     * Create's and return's a new empty artefact entity.
182
     *
183
     * @param array $columns             The array with the column data
184
     * @param array $originalColumnNames The array with a mapping from the old to the new column names
185
     *
186
     * @return array The new artefact entity
187
     */
188
    protected function newArtefact(array $columns, array $originalColumnNames)
189
    {
190
        return $this->getSubject()->newArtefact($columns, $originalColumnNames);
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 newArtefact() does only exist in the following implementations of said interface: TechDivision\Import\Plugins\ExportableSubjectImpl, 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...
191
    }
192
193
    /**
194
     * Add the passed product type artefacts to the product with the
195
     * last entity ID.
196
     *
197
     * @param array $artefacts The product type artefacts
198
     *
199
     * @return void
200
     * @uses \TechDivision\Import\Product\Media\Subjects\MediaSubject::getLastEntityId()
201
     */
202
    protected function addArtefacts(array $artefacts)
203
    {
204
        $this->getSubject()->addArtefacts(ProductUrlRewriteObserver::ARTEFACT_TYPE, $artefacts);
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 addArtefacts() does only exist in the following implementations of said interface: TechDivision\Import\Plugins\ExportableSubjectImpl, 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...
205
    }
206
}
207