Completed
Push — 19.x ( 239dba...3864f1 )
by Tim
01:48
created

getAttributeBunchProcessor()   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\Attribute\Observers\AttributeOptionObserver
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-attribute
18
 * @link      http://www.techdivision.com
19
 */
20
21
namespace TechDivision\Import\Attribute\Observers;
22
23
use TechDivision\Import\Utils\EntityStatus;
24
use TechDivision\Import\Utils\BackendTypeKeys;
25
use TechDivision\Import\Attribute\Utils\ColumnKeys;
26
use TechDivision\Import\Attribute\Utils\MemberNames;
27
use TechDivision\Import\Attribute\Utils\EntityTypeCodes;
28
use TechDivision\Import\Attribute\Services\AttributeBunchProcessorInterface;
29
use TechDivision\Import\Observers\StateDetectorInterface;
30
use TechDivision\Import\Observers\AttributeLoaderInterface;
31
use TechDivision\Import\Observers\DynamicAttributeObserverInterface;
32
use TechDivision\Import\Observers\EntityMergers\EntityMergerInterface;
33
34
/**
35
 * Observer that create's the attribute options found in the additional CSV file.
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-attribute
41
 * @link      http://www.techdivision.com
42
 */
43
class AttributeOptionObserver extends AbstractAttributeImportObserver implements DynamicAttributeObserverInterface
44
{
45
46
    /**
47
     * The attribute processor instance.
48
     *
49
     * @var \TechDivision\Import\Attribute\Services\AttributeBunchProcessorInterface
50
     */
51
    protected $attributeBunchProcessor;
52
53
    /**
54
     * The attribute loader instance.
55
     *
56
     * @var \TechDivision\Import\Observers\AttributeLoaderInterface
57
     */
58
    protected $attributeLoader;
59
60
    /**
61
     * The collection with entity merger instances.
62
     *
63
     * @var \Doctrine\Common\Collections\Collection
64
     */
65
    protected $entityMergers;
66
67
    /**
68
     * Initialize the dedicated column.
69
     *
70
     * @var array
71
     */
72
    protected $columns = array(MemberNames::SORT_ORDER => array(ColumnKeys::SORT_ORDER, BackendTypeKeys::BACKEND_TYPE_INT));
73
74
    /**
75
     * Initializes the observer with the passed subject instance.
76
     *
77
     * @param \TechDivision\Import\Attribute\Services\AttributeBunchProcessorInterface $attributeBunchProcessor The attribute bunch processor instance
78
     * @param \TechDivision\Import\Observers\AttributeLoaderInterface                  $attributeLoader         The attribute loader instance
79
     * @param \TechDivision\Import\Observers\EntityMergers\EntityMergerInterface       $entityMerger            The entity merger instance
80
     * @param \TechDivision\Import\Observers\StateDetectorInterface|null               $stateDetector           The state detector instance to use
81
     */
82 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...
83
        AttributeBunchProcessorInterface $attributeBunchProcessor,
84
        AttributeLoaderInterface $attributeLoader = null,
85
        EntityMergerInterface $entityMerger = null,
86
        StateDetectorInterface $stateDetector = null
87
    ) {
88
89
            // initialize the bunch processor, the attribute loader and the entity merger instance
90
        $this->attributeBunchProcessor = $attributeBunchProcessor;
91
        $this->attributeLoader = $attributeLoader;
92
        $this->entityMerger = $entityMerger;
0 ignored issues
show
Bug introduced by
The property entityMerger does not seem to exist. Did you mean entityMergers?

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
93
94
        // pass the state detector to the parent method
95
        parent::__construct($stateDetector);
96
    }
97
98
    /**
99
     * Process the observer's business logic.
100
     *
101
     * @return void
102
     */
103
    protected function process()
104
    {
105
106
        // query whether or not, we've found a new attribute code => means we've found a new attribute
107
        if ($this->hasBeenProcessed($this->getValue(ColumnKeys::ATTRIBUTE_CODE), $this->getValue(ColumnKeys::VALUE))) {
108
            return;
109
        }
110
111
        // prepare the store view code
112
        $this->prepareStoreViewCode();
113
114
        // prepare the attribue values
115
        $attributeOption = $this->initializeAttribute($this->prepareDynamicAttributes());
116
117
        // insert the attribute option and set the option ID
118
        $this->setLastOptionId($this->persistAttributeOption($attributeOption));
119
    }
120
121
    /**
122
     * Merge's and return's the entity with the passed attributes and set's the
123
     * passed status.
124
     *
125
     * @param array       $entity        The entity to merge the attributes into
126
     * @param array       $attr          The attributes to be merged
127
     * @param string|null $changeSetName The change set name to use
128
     *
129
     * @return array The merged entity
130
     * @todo https://github.com/techdivision/import/issues/179
131
     */
132 View Code Duplication
    protected function mergeEntity(array $entity, array $attr, $changeSetName = null)
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...
133
    {
134
        return array_merge(
135
            $entity,
136
            $this->entityMerger ? $this->entityMerger->merge($this, $entity, $attr) : $attr,
0 ignored issues
show
Bug introduced by
The property entityMerger does not seem to exist. Did you mean entityMergers?

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
137
            array(EntityStatus::MEMBER_NAME => $this->detectState($entity, $attr, $changeSetName))
138
        );
139
    }
140
141
    /**
142
     * Appends the dynamic to the static attributes for the EAV attribute
143
     * and returns them.
144
     *
145
     * @return array The array with all available attributes
146
     */
147
    protected function prepareDynamicAttributes()
148
    {
149
        return array_merge($this->prepareAttributes(), $this->attributeLoader ? $this->attributeLoader->load($this, $this->columns) : array());
150
    }
151
152
    /**
153
     * Prepare the attributes of the entity that has to be persisted.
154
     *
155
     * @return array The prepared attributes
156
     */
157 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...
158
    {
159
160
        // load the attribute ID
161
        $attribute = $this->loadAttributeByEntityTypeIdAndAttributeCode($this->getEntityTypeId(), $this->getValue(ColumnKeys::ATTRIBUTE_CODE));
162
        $attributeId = $attribute[MemberNames::ATTRIBUTE_ID];
163
164
        // return the prepared attribute option
165
        return $this->initializeEntity(
166
            $this->loadRawEntity(
167
                array(MemberNames::ATTRIBUTE_ID => $attributeId)
168
            )
169
        );
170
    }
171
172
    /**
173
     * Load's and return's a raw customer entity without primary key but the mandatory members only and nulled values.
174
     *
175
     * @param array $data An array with data that will be used to initialize the raw entity with
176
     *
177
     * @return array The initialized entity
178
     */
179
    protected function loadRawEntity(array $data = array())
180
    {
181
        return $this->getAttributeBunchProcessor()->loadRawEntity(EntityTypeCodes::EAV_ATTRIBUTE_OPTION, $data);
182
    }
183
184
    /**
185
     * Initialize the EAV attribute option with the passed attributes and returns an instance.
186
     *
187
     * @param array $attr The EAV attribute option attributes
188
     *
189
     * @return array The initialized EAV attribute option
190
     */
191
    protected function initializeAttribute(array $attr)
192
    {
193
        return $attr;
194
    }
195
196
    /**
197
     * Return's the attribute bunch processor instance.
198
     *
199
     * @return \TechDivision\Import\Attribute\Services\AttributeBunchProcessorInterface The attribute bunch processor instance
200
     */
201
    protected function getAttributeBunchProcessor()
202
    {
203
        return $this->attributeBunchProcessor;
204
    }
205
206
    /**
207
     * Queries whether or not the attribute with the passed code/value has already been processed.
208
     *
209
     * @param string $attributeCode The attribute code to check
210
     * @param string $value         The option value to check
211
     *
212
     * @return boolean TRUE if the path has been processed, else FALSE
213
     */
214
    protected function hasBeenProcessed($attributeCode, $value)
215
    {
216
        return $this->getSubject()->hasBeenProcessed($attributeCode, $value);
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 hasBeenProcessed() does only exist in the following implementations of said interface: TechDivision\Import\Attr...rs\AttributeSubjectImpl, TechDivision\Import\Attr...e\Subjects\BunchSubject, TechDivision\Import\Attr...\Subjects\OptionSubject.

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...
217
    }
218
219
    /**
220
     * Set's the ID of the option that has been created recently.
221
     *
222
     * @param integer $lastOptionId The option ID
223
     *
224
     * @return void
225
     */
226
    protected function setLastOptionId($lastOptionId)
227
    {
228
        $this->getSubject()->setLastOptionId($lastOptionId);
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 setLastOptionId() does only exist in the following implementations of said interface: TechDivision\Import\Attr...\Subjects\OptionSubject.

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
     * Return's the EAV attribute with the passed entity type ID and code.
233
     *
234
     * @param integer $entityTypeId  The entity type ID of the EAV attribute to return
235
     * @param string  $attributeCode The code of the EAV attribute to return
236
     *
237
     * @return array The EAV attribute
238
     */
239
    public function loadAttributeByEntityTypeIdAndAttributeCode($entityTypeId, $attributeCode)
240
    {
241
        return $this->getAttributeBunchProcessor()->loadAttributeByEntityTypeIdAndAttributeCode($entityTypeId, $attributeCode);
242
    }
243
244
    /**
245
     * Persist the passed attribute option.
246
     *
247
     * @param array $attributeOption The attribute option to persist
248
     *
249
     * @return void
250
     */
251
    protected function persistAttributeOption(array $attributeOption)
252
    {
253
        return $this->getAttributeBunchProcessor()->persistAttributeOption($attributeOption);
254
    }
255
}
256