Completed
Push — 19.x ( 24d584 )
by Tim
02:01
created

prepareDynamicAttributes()   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 0
crap 6
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\BackendTypeKeys;
24
use TechDivision\Import\Attribute\Utils\ColumnKeys;
25
use TechDivision\Import\Attribute\Utils\MemberNames;
26
use TechDivision\Import\Attribute\Utils\EntityTypeCodes;
27
use TechDivision\Import\Attribute\Services\AttributeBunchProcessorInterface;
28
use TechDivision\Import\Observers\AttributeLoaderInterface;
29
use TechDivision\Import\Observers\DynamicAttributeObserverInterface;
30
31
/**
32
 * Observer that create's the attribute options found in the additional CSV file.
33
 *
34
 * @author    Tim Wagner <[email protected]>
35
 * @copyright 2016 TechDivision GmbH <[email protected]>
36
 * @license   http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
37
 * @link      https://github.com/techdivision/import-attribute
38
 * @link      http://www.techdivision.com
39
 */
40
class AttributeOptionObserver extends AbstractAttributeImportObserver implements DynamicAttributeObserverInterface
41
{
42
43
    /**
44
     * The attribute processor instance.
45
     *
46
     * @var \TechDivision\Import\Attribute\Services\AttributeBunchProcessorInterface
47
     */
48
    protected $attributeBunchProcessor;
49
50
    /**
51
     * The attribute loader instance.
52
     *
53
     * @var \TechDivision\Import\Observers\AttributeLoaderInterface
54
     */
55
    protected $attributeLoader;
56
57
    /**
58
     * Initialize the dedicated column.
59
     *
60
     * @var array
61
     */
62
    protected $columns = array(MemberNames::SORT_ORDER => array(ColumnKeys::SORT_ORDER, BackendTypeKeys::BACKEND_TYPE_INT));
63
64
    /**
65
     * Initializes the observer with the passed subject instance.
66
     *
67
     * @param \TechDivision\Import\Attribute\Services\AttributeBunchProcessorInterface $attributeBunchProcessor The attribute bunch processor instance
68
     * @param \TechDivision\Import\Observers\AttributeLoaderInterface                  $attributeLoader         The attribute loader instance
69
     */
70
    public function __construct(
71
        AttributeBunchProcessorInterface $attributeBunchProcessor,
72
        AttributeLoaderInterface $attributeLoader = null
73
    ) {
74
        $this->attributeBunchProcessor = $attributeBunchProcessor;
75
        $this->attributeLoader = $attributeLoader;
76
    }
77
78
    /**
79
     * Process the observer's business logic.
80
     *
81
     * @return void
82
     */
83
    protected function process()
84
    {
85
86
        // query whether or not, we've found a new attribute code => means we've found a new attribute
87
        if ($this->hasBeenProcessed($this->getValue(ColumnKeys::ATTRIBUTE_CODE), $this->getValue(ColumnKeys::VALUE))) {
88
            return;
89
        }
90
91
        // prepare the store view code
92
        $this->prepareStoreViewCode();
93
94
        // prepare the attribue values
95
        $attributeOption = $this->initializeAttribute($this->prepareDynamicAttributes());
96
97
        // insert the attribute option and set the option ID
98
        $this->setLastOptionId($this->persistAttributeOption($attributeOption));
99
    }
100
101
    /**
102
     * Appends the dynamic to the static attributes for the EAV attribute
103
     * and returns them.
104
     *
105
     * @return array The array with all available attributes
106
     */
107
    protected function prepareDynamicAttributes()
108
    {
109
        return array_merge($this->prepareAttributes(), $this->attributeLoader ? $this->attributeLoader->load($this, $this->columns) : array());
110
    }
111
112
    /**
113
     * Prepare the attributes of the entity that has to be persisted.
114
     *
115
     * @return array The prepared attributes
116
     */
117 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...
118
    {
119
120
        // load the attribute ID
121
        $attribute = $this->loadAttributeByEntityTypeIdAndAttributeCode($this->getEntityTypeId(), $this->getValue(ColumnKeys::ATTRIBUTE_CODE));
122
        $attributeId = $attribute[MemberNames::ATTRIBUTE_ID];
123
124
        // return the prepared attribute option
125
        return $this->initializeEntity(
126
            $this->loadRawEntity(
127
                array(MemberNames::ATTRIBUTE_ID => $attributeId)
128
            )
129
        );
130
    }
131
132
    /**
133
     * Load's and return's a raw customer entity without primary key but the mandatory members only and nulled values.
134
     *
135
     * @param array $data An array with data that will be used to initialize the raw entity with
136
     *
137
     * @return array The initialized entity
138
     */
139
    protected function loadRawEntity(array $data = array())
140
    {
141
        return $this->getAttributeBunchProcessor()->loadRawEntity(EntityTypeCodes::EAV_ATTRIBUTE_OPTION, $data);
142
    }
143
144
    /**
145
     * Initialize the EAV attribute option with the passed attributes and returns an instance.
146
     *
147
     * @param array $attr The EAV attribute option attributes
148
     *
149
     * @return array The initialized EAV attribute option
150
     */
151
    protected function initializeAttribute(array $attr)
152
    {
153
        return $attr;
154
    }
155
156
    /**
157
     * Return's the attribute bunch processor instance.
158
     *
159
     * @return \TechDivision\Import\Attribute\Services\AttributeBunchProcessorInterface The attribute bunch processor instance
160
     */
161
    protected function getAttributeBunchProcessor()
162
    {
163
        return $this->attributeBunchProcessor;
164
    }
165
166
    /**
167
     * Queries whether or not the attribute with the passed code/value has already been processed.
168
     *
169
     * @param string $attributeCode The attribute code to check
170
     * @param string $value         The option value to check
171
     *
172
     * @return boolean TRUE if the path has been processed, else FALSE
173
     */
174
    protected function hasBeenProcessed($attributeCode, $value)
175
    {
176
        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...
177
    }
178
179
    /**
180
     * Set's the ID of the option that has been created recently.
181
     *
182
     * @param integer $lastOptionId The option ID
183
     *
184
     * @return void
185
     */
186
    protected function setLastOptionId($lastOptionId)
187
    {
188
        $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...
189
    }
190
191
    /**
192
     * Return's the EAV attribute with the passed entity type ID and code.
193
     *
194
     * @param integer $entityTypeId  The entity type ID of the EAV attribute to return
195
     * @param string  $attributeCode The code of the EAV attribute to return
196
     *
197
     * @return array The EAV attribute
198
     */
199
    public function loadAttributeByEntityTypeIdAndAttributeCode($entityTypeId, $attributeCode)
200
    {
201
        return $this->getAttributeBunchProcessor()->loadAttributeByEntityTypeIdAndAttributeCode($entityTypeId, $attributeCode);
202
    }
203
204
    /**
205
     * Persist the passed attribute option.
206
     *
207
     * @param array $attributeOption The attribute option to persist
208
     *
209
     * @return void
210
     */
211
    protected function persistAttributeOption(array $attributeOption)
212
    {
213
        return $this->getAttributeBunchProcessor()->persistAttributeOption($attributeOption);
214
    }
215
}
216