Completed
Push — 22.x ( d7197a )
by Tim
03:35
created

BundleOptionObserver::getProductBundleProcessor()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 0
cts 4
cp 0
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 0
crap 2
1
<?php
2
3
/**
4
 * TechDivision\Import\Product\Bundle\Observers\BundleOptionObserver
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-bundle
18
 * @link      http://www.techdivision.com
19
 */
20
21
namespace TechDivision\Import\Product\Bundle\Observers;
22
23
use TechDivision\Import\Utils\StoreViewCodes;
24
use TechDivision\Import\Observers\StateDetectorInterface;
25
use TechDivision\Import\Observers\AttributeLoaderInterface;
26
use TechDivision\Import\Product\Bundle\Utils\ColumnKeys;
27
use TechDivision\Import\Product\Bundle\Utils\MemberNames;
28
use TechDivision\Import\Product\Observers\AbstractProductImportObserver;
29
use TechDivision\Import\Product\Bundle\Services\ProductBundleProcessorInterface;
30
use TechDivision\Import\Product\Bundle\Utils\EntityTypeCodes;
31
32
/**
33
 * Oberserver that provides functionality for the bundle option replace operation.
34
 *
35
 * @author    Tim Wagner <[email protected]>
36
 * @copyright 2016 TechDivision GmbH <[email protected]>
37
 * @license   http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
38
 * @link      https://github.com/techdivision/import-product-bundle
39
 * @link      http://www.techdivision.com
40
 */
41
class BundleOptionObserver extends AbstractProductImportObserver
42
{
43
44
    /**
45
     * The product bundle processor instance.
46
     *
47
     * @var \TechDivision\Import\Product\Bundle\Services\ProductBundleProcessorInterface
48
     */
49
    protected $productBundleProcessor;
50
51
    /**
52
     * The attribute loader instance.
53
     *
54
     * @var \TechDivision\Import\Observers\AttributeLoaderInterface
55
     */
56
    protected $attributeLoader;
57
58
    /**
59
     * Initialize the observer with the passed product bundle processor instance.
60
     *
61
     * @param \TechDivision\Import\Product\Bundle\Services\ProductBundleProcessorInterface $productBundleProcessor The product bundle processor instance
62
     * @param \TechDivision\Import\Observers\AttributeLoaderInterface|null                 $attributeLoader        The attribute loader instance
63
     * @param \TechDivision\Import\Observers\StateDetectorInterface|null                   $stateDetector          The state detector instance
64
     */
65 View Code Duplication
    public function __construct(
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
66
        ProductBundleProcessorInterface $productBundleProcessor,
67
        AttributeLoaderInterface $attributeLoader = null,
68
        StateDetectorInterface $stateDetector = null
69
    ) {
70
71
        // initialize the product bundle processor and the attribute loader instance
72
        $this->productBundleProcessor = $productBundleProcessor;
73
        $this->attributeLoader = $attributeLoader;
74
75
        // pass the state detector to the parent method
76
        parent::__construct($stateDetector);
77
    }
78
79
    /**
80
     * Return's the product bundle processor instance.
81
     *
82
     * @return \TechDivision\Import\Product\Bundle\Services\ProductBundleProcessorInterface The product bundle processor instance
83
     */
84
    protected function getProductBundleProcessor()
85
    {
86
        return $this->productBundleProcessor;
87
    }
88
89
    /**
90
     * Process the observer's business logic.
91
     *
92
     * @return array The processed row
93
     */
94
    protected function process()
95
    {
96
97
        // prepare the store view code
98
        $this->prepareStoreViewCode($this->getRow());
0 ignored issues
show
Unused Code introduced by
The call to BundleOptionObserver::prepareStoreViewCode() has too many arguments starting with $this->getRow().

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
99
100
        // return immediately if we're have no store view code set
101
        if (StoreViewCodes::ADMIN !== $this->getStoreViewCode(StoreViewCodes::ADMIN)) {
102
            return;
103
        }
104
105
        // load the name and the parent SKU
106
        $name = $this->getValue(ColumnKeys::BUNDLE_VALUE_NAME);
107
        $parentSku = $this->getValue(ColumnKeys::BUNDLE_PARENT_SKU);
108
109
        // query whether or not the option has already been created for the parent SKU
110
        if ($this->exists($parentSku, $name)) {
111
            return;
112
        }
113
114
        // load and persist the product bundle option
115
        $optionId = $this->persistProductBundleOption($this->initializeBundleOption($this->prepareDynamicAttributes()));
116
117
        // store the parent SKU => name mapping
118
        $this->addParentSkuNameMapping(array($parentSku => array($name => $optionId)));
119
    }
120
121
    /**
122
     * Appends the dynamic attributes to the static ones and returns them.
123
     *
124
     * @return array The array with all available attributes
125
     */
126
    protected function prepareDynamicAttributes() : array
127
    {
128
        return array_merge($this->prepareAttributes(), $this->attributeLoader ? $this->attributeLoader->load($this, $this->columns) : array());
0 ignored issues
show
Bug introduced by
The property columns does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
Documentation introduced by
$this is of type this<TechDivision\Import...s\BundleOptionObserver>, but the function expects a object<TechDivision\Impo...ibuteObserverInterface>.

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...
129
    }
130
131
    /**
132
     * Prepare the attributes of the entity that has to be persisted.
133
     *
134
     * @return array The prepared attributes
135
     */
136 View Code Duplication
    protected function prepareAttributes()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
137
    {
138
139
        // reset the position counter for the bundle selection
140
        $this->resetPositionCounter();
141
142
        try {
143
            // load and map the parent SKU
144
            $parentId = $this->mapSku($this->getValue(ColumnKeys::BUNDLE_PARENT_SKU));
145
        } catch (\Exception $e) {
146
            throw $this->wrapException(array(ColumnKeys::BUNDLE_PARENT_SKU), $e);
0 ignored issues
show
Documentation introduced by
array(\TechDivision\Impo...eys::BUNDLE_PARENT_SKU) is of type array<integer,?>, but the function expects a string.

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...
147
        }
148
149
        // extract the parent/child ID as well as type and position
150
        $required = $this->getValue(ColumnKeys::BUNDLE_VALUE_REQUIRED);
151
        $type = $this->getValue(ColumnKeys::BUNDLE_VALUE_TYPE);
152
        $position = 1;
153
154
        // return the prepared product
155
        return $this->initializeEntity(
156
            $this->loadRawEntity(
157
                array(
158
                    MemberNames::PARENT_ID => $parentId,
159
                    MemberNames::REQUIRED  => $required,
160
                    MemberNames::POSITION  => $position,
161
                    MemberNames::TYPE      => $type
162
                )
163
            )
164
        );
165
    }
166
167
    /**
168
     * Load's and return's a raw entity without primary key but the mandatory members only and nulled values.
169
     *
170
     * @param array $data An array with data that will be used to initialize the raw entity with
171
     *
172
     * @return array The initialized entity
173
     */
174
    protected function loadRawEntity(array $data = array())
175
    {
176
        return $this->getProductVariantProcessor()->loadRawEntity(EntityTypeCodes::CATALOG_PRODUCT_BUNDLE_OPTION, $data);
0 ignored issues
show
Bug introduced by
The method getProductVariantProcessor() does not exist on TechDivision\Import\Prod...rs\BundleOptionObserver. Did you maybe mean process()?

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...
177
    }
178
179
    /**
180
     * Initialize the bundle option with the passed attributes and returns an instance.
181
     *
182
     * @param array $attr The bundle option attributes
183
     *
184
     * @return array The initialized bundle option
185
     */
186
    protected function initializeBundleOption(array $attr)
187
    {
188
        return $attr;
189
    }
190
191
    /**
192
     * Reset the position counter to 1.
193
     *
194
     * @return void
195
     */
196
    protected function resetPositionCounter()
197
    {
198
        $this->getSubject()->resetPositionCounter();
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 resetPositionCounter() does only exist in the following implementations of said interface: TechDivision\Import\Prod...\Subjects\BundleSubject.

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...
199
    }
200
201
    /**
202
     * Add's the passed mapping to the subject.
203
     *
204
     * @param array $mapping The mapping to add
205
     *
206
     * @return void
207
     */
208
    protected function addParentSkuNameMapping($mapping = array())
209
    {
210
        $this->getSubject()->addParentSkuNameMapping($mapping);
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 addParentSkuNameMapping() does only exist in the following implementations of said interface: TechDivision\Import\Prod...\Subjects\BundleSubject.

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...
211
    }
212
213
    /**
214
     * Query whether or not the option for the passed parent SKU and name has already been created.
215
     *
216
     * @param string $parentSku The parent SKU to query for
217
     * @param string $name      The option name to query for
218
     *
219
     * @return boolean TRUE if the option already exists, else FALSE
220
     */
221
    protected function exists($parentSku, $name)
222
    {
223
        return $this->getSubject()->exists($parentSku, $name);
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 exists() does only exist in the following implementations of said interface: TechDivision\Import\Prod...\Subjects\BundleSubject.

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...
224
    }
225
226
    /**
227
     * Return the entity ID for the passed SKU.
228
     *
229
     * @param string $sku The SKU to return the entity ID for
230
     *
231
     * @return integer The mapped entity ID
232
     * @throws \Exception Is thrown if the SKU is not mapped yet
233
     */
234
    protected function mapSku($sku)
235
    {
236
        return $this->getSubject()->mapSkuToEntityId($sku);
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 mapSkuToEntityId() does only exist in the following implementations of said interface: TechDivision\Import\Prod...\Subjects\BundleSubject, TechDivision\Import\Prod...\AbstractProductSubject, TechDivision\Import\Product\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...
237
    }
238
239
    /**
240
     * Persist's the passed product bundle option data and return's the ID.
241
     *
242
     * @param array $productBundleOption The product bundle option data to persist
243
     *
244
     * @return string The ID of the persisted entity
245
     */
246
    protected function persistProductBundleOption($productBundleOption)
247
    {
248
        return $this->getProductBundleProcessor()->persistProductBundleOption($productBundleOption);
249
    }
250
}
251