Completed
Push — master ( 4069e0...cc7355 )
by Tim
24:34 queued 12:30
created

CatalogAttributeObserver   A

Complexity

Total Complexity 23

Size/Duplication

Total Lines 249
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 3

Test Coverage

Coverage 83.61%

Importance

Changes 0
Metric Value
wmc 23
lcom 1
cbo 3
dl 0
loc 249
ccs 51
cts 61
cp 0.8361
rs 10
c 0
b 0
f 0

11 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A process() 0 11 2
A initializeAttribute() 0 4 1
A getAttributeBunchProcessor() 0 4 1
A addAttributeCodeIdMapping() 0 4 1
A hasBeenProcessed() 0 4 1
A getLastAttributeId() 0 4 1
A isSwatchType() 0 4 2
A persistCatalogAttribute() 0 4 1
C prepareAttributes() 0 61 9
A serializeAdditionalData() 0 11 3
1
<?php
2
3
/**
4
 * TechDivision\Import\Attribute\Observers\CatalogAttributeObserver
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\Attribute\Utils\ColumnKeys;
24
use TechDivision\Import\Attribute\Utils\MemberNames;
25
use TechDivision\Import\Attribute\Services\AttributeBunchProcessorInterface;
26
27
/**
28
 * Observer that create's the EAV catalog attribute itself.
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-attribute
34
 * @link      http://www.techdivision.com
35
 */
36
class CatalogAttributeObserver extends AbstractAttributeImportObserver
37
{
38
39
    /**
40
     * The key for the additional data containing the swatch type.
41
     *
42
     * @var string
43
     */
44
    const SWATCH_INPUT_TYPE = 'swatch_input_type';
45
46
    /**
47
     * The available swatch types.
48
     *
49
     * @var array
50
     */
51
    protected $swatchTypes = array('text', 'visual');
52
53
    /**
54
     * The attribute processor instance.
55
     *
56
     * @var \TechDivision\Import\Attribute\Services\AttributeBunchProcessorInterface
57
     */
58
    protected $attributeBunchProcessor;
59
60
    /**
61
     * The array with the possible column names.
62
     *
63
     * @var array
64
     */
65
    protected $columnNames = array(
66
        ColumnKeys::FRONTEND_INPUT_RENDERER,
67
        ColumnKeys::IS_GLOBAL,
68
        ColumnKeys::IS_VISIBLE,
69
        ColumnKeys::IS_SEARCHABLE,
70
        ColumnKeys::IS_FILTERABLE,
71
        ColumnKeys::IS_COMPARABLE,
72
        ColumnKeys::IS_VISIBLE_ON_FRONT,
73
        ColumnKeys::IS_HTML_ALLOWED_ON_FRONT,
74
        ColumnKeys::IS_USED_FOR_PRICE_RULES,
75
        ColumnKeys::IS_FILTERABLE_IN_SEARCH,
76
        ColumnKeys::USED_IN_PRODUCT_LISTING,
77
        ColumnKeys::USED_FOR_SORT_BY,
78
        ColumnKeys::APPLY_TO,
79
        ColumnKeys::IS_VISIBLE_IN_ADVANCED_SEARCH,
80
        ColumnKeys::POSITION,
81
        ColumnKeys::IS_WYSIWYG_ENABLED,
82
        ColumnKeys::IS_USED_FOR_PROMO_RULES,
83
        ColumnKeys::IS_REQUIRED_IN_ADMIN_STORE,
84
        ColumnKeys::IS_USED_IN_GRID,
85
        ColumnKeys::IS_VISIBLE_IN_GRID,
86
        ColumnKeys::IS_FILTERABLE_IN_GRID,
87
        ColumnKeys::SEARCH_WEIGHT,
88
        ColumnKeys::ADDITIONAL_DATA
89
    );
90
91
    /**
92
     * Initializes the observer with the passed subject instance.
93
     *
94
     * @param \TechDivision\Import\Attribute\Services\AttributeBunchProcessorInterface $attributeBunchProcessor The attribute bunch processor instance
95
     */
96 3
    public function __construct(AttributeBunchProcessorInterface $attributeBunchProcessor)
97
    {
98 3
        $this->attributeBunchProcessor = $attributeBunchProcessor;
99 3
    }
100
101
    /**
102
     * Process the observer's business logic.
103
     *
104
     * @return void
105
     */
106 3
    protected function process()
107
    {
108
109
        // query whether or not, we've found a new attribute code => means we've found a new attribute
110 3
        if ($this->hasBeenProcessed($this->getValue(ColumnKeys::ATTRIBUTE_CODE))) {
111
            return;
112
        }
113
114
        // initialize and persist the EAV catalog attribute
115 3
        $this->persistCatalogAttribute($this->initializeAttribute($this->prepareAttributes()));
116 3
    }
117
118
    /**
119
     * Prepare the attributes of the entity that has to be persisted.
120
     *
121
     * @return array The prepared attributes
122
     * @throws \Exception Is thrown, if the size of the option values doesn't equals the size of swatch values, in case
123
     */
124 3
    protected function prepareAttributes()
125
    {
126
127
        // load the recently created EAV attribute ID
128 3
        $attributeId = $this->getLastAttributeId();
129
130
        // initialize the attributes
131 3
        $attr = array(MemberNames::ATTRIBUTE_ID => $attributeId);
132
133
        // iterate over the possible columns and handle the data
134 3
        foreach ($this->columnNames as $columnName) {
135
            // query whether or not, the column is available in the CSV file
136 3
            if ($this->getSubject()->hasHeader($columnName)) {
137
                // custom handling for the additional_data column
138 1
                if ($columnName === ColumnKeys::ADDITIONAL_DATA) {
139
                    // load the raw additional data
140 1
                    $explodedAdditionalData = $this->getValue(ColumnKeys::ADDITIONAL_DATA, array(), array($this->getSubject(), 'explode'));
141
142
                    // query whether or not additional data has been set
143 1
                    if (sizeof($explodedAdditionalData) > 0) {
144
                        // load and extract the additional data
145 1
                        $additionalData = array();
146 1
                        foreach ($explodedAdditionalData as $value) {
147 1
                            list ($key, $val) = $this->getSubject()->explode($value, '=');
148 1
                            $additionalData[$key] = $val;
149 1
                        }
150
151
                        // set the additional data
152 1
                        $attr[$columnName] = $additionalData;
153
154
                        // query whether or not the attribute is a text or a visual swatch
155 1
                        if ($this->isSwatchType($additionalData)) {
156
                            // load the attribute option values for the custom store views
157 1
                            $attributeOptionValues = $this->getValue(ColumnKeys::ATTRIBUTE_OPTION_VALUES, array(), array($this, 'explode'));
158 1
                            $attributeOptionSwatch = $this->getSubject()->explode($this->getValue(ColumnKeys::ATTRIBUTE_OPTION_SWATCH), $this->getSubject()->getMultipleValueDelimiter());
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 getMultipleValueDelimiter() does only exist in the following implementations of said interface: TechDivision\Import\Attr...rs\AttributeSubjectImpl, TechDivision\Import\Attr...bstractAttributeSubject, TechDivision\Import\Attr...e\Subjects\BunchSubject, TechDivision\Import\Attr...\Subjects\OptionSubject, TechDivision\Import\Subjects\AbstractEavSubject, TechDivision\Import\Subjects\AbstractSubject, TechDivision\Import\Subjects\MoveFilesSubject.

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...
159
160
                            // query whether or not the size of the option values equals the size of the swatch values
161 1
                            if (($sizeOfSwatchValues = sizeof($attributeOptionSwatch)) !== ($sizeOfOptionValues = sizeof($attributeOptionValues))) {
162
                                throw new \Exception(
163
                                    sprintf(
164
                                        'Size of option values "%d" doesn\'t equals size of swatch values "%d"',
165
                                        $sizeOfOptionValues,
166
                                        $sizeOfSwatchValues
167
                                    )
168
                                );
169
                            }
170 1
                        }
171 1
                    }
172
173 1
                } else {
174
                    // query whether or not a column contains a value
175 1
                    if ($this->hasValue($columnName)) {
176 1
                        $attr[$columnName] = $this->getValue($columnName);
177 1
                    }
178
                }
179 1
            }
180 3
        }
181
182
        // return the prepared product
183 3
        return $this->initializeEntity($attr);
184
    }
185
186
    /**
187
     * Serialize the additional_data attribute of the passed array.
188
     *
189
     * @param array $attr The attribute with the data to serialize
190
     *
191
     * @return array The attribute with the serialized additional_data
192
     */
193 3
    protected function serializeAdditionalData(array $attr)
194
    {
195
196
        // serialize the additional data value if available
197 3
        if (isset($attr[MemberNames::ADDITIONAL_DATA]) && is_array($attr[MemberNames::ADDITIONAL_DATA])) {
198 2
            $attr[MemberNames::ADDITIONAL_DATA] = serialize($attr[MemberNames::ADDITIONAL_DATA]);
199 2
        }
200
201
        // return the attribute
202 3
        return $attr;
203
    }
204
205
    /**
206
     * Initialize the attribute with the passed attributes and returns an instance.
207
     *
208
     * @param array $attr The attribute attributes
209
     *
210
     * @return array The initialized attribute
211
     */
212 1
    protected function initializeAttribute(array $attr)
213
    {
214 1
        return $this->serializeAdditionalData($attr);
215
    }
216
217
    /**
218
     * Return's the attribute bunch processor instance.
219
     *
220
     * @return \TechDivision\Import\Attribute\Services\AttributeBunchProcessorInterface The attribute bunch processor instance
221
     */
222 3
    protected function getAttributeBunchProcessor()
223
    {
224 3
        return $this->attributeBunchProcessor;
225
    }
226
227
    /**
228
     * Map's the passed attribute code to the attribute ID that has been created recently.
229
     *
230
     * @param string $attributeCode The attribute code that has to be mapped
231
     *
232
     * @return void
233
     */
234
    protected function addAttributeCodeIdMapping($attributeCode)
235
    {
236
        $this->getSubject()->addAttributeCodeIdMapping($attributeCode);
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 addAttributeCodeIdMapping() does only exist in the following implementations of said interface: TechDivision\Import\Attr...e\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
     * Queries whether or not the attribute with the passed code has already been processed.
241
     *
242
     * @param string $attributeCode The attribute code to check
243
     *
244
     * @return boolean TRUE if the path has been processed, else FALSE
245
     */
246 3
    protected function hasBeenProcessed($attributeCode)
247
    {
248 3
        return $this->getSubject()->hasBeenProcessed($attributeCode);
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...
249
    }
250
251
    /**
252
     * Return's the ID of the attribute that has been created recently.
253
     *
254
     * @return integer The attribute ID
255
     */
256 3
    protected function getLastAttributeId()
257
    {
258 3
        return $this->getSubject()->getLastAttributeId();
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 getLastAttributeId() does only exist in the following implementations of said interface: TechDivision\Import\Attr...rs\AttributeSubjectImpl, TechDivision\Import\Attr...e\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...
259
    }
260
261
    /**
262
     * Return's TRUE if the additional data contains a swatch type.
263
     *
264
     * @param array $additionalData The additional data to query for a valid swatch type
265
     *
266
     * @return boolean TRUE if the data contains a swatch type, else FALSE
267
     */
268 1
    protected function isSwatchType(array $additionalData)
269
    {
270 1
        return isset($additionalData[CatalogAttributeObserver::SWATCH_INPUT_TYPE]) && in_array($additionalData[CatalogAttributeObserver::SWATCH_INPUT_TYPE], $this->swatchTypes);
271
    }
272
273
    /**
274
     * Persist the passed EAV catalog attribute.
275
     *
276
     * @param array $catalogAttribute The EAV catalog attribute to persist
277
     *
278
     * @return void
279
     */
280 3
    protected function persistCatalogAttribute(array $catalogAttribute)
281
    {
282 3
        return $this->getAttributeBunchProcessor()->persistCatalogAttribute($catalogAttribute);
283
    }
284
}
285