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

CatalogAttributeObserver::loadRawEntity()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 2
cts 2
cp 1
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 1
crap 1
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
use TechDivision\Import\Attribute\Utils\EntityTypeCodes;
27
28
/**
29
 * Observer that create's the EAV catalog attribute itself.
30
 *
31
 * @author    Tim Wagner <[email protected]>
32
 * @copyright 2016 TechDivision GmbH <[email protected]>
33
 * @license   http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
34
 * @link      https://github.com/techdivision/import-attribute
35
 * @link      http://www.techdivision.com
36
 */
37
class CatalogAttributeObserver extends AbstractAttributeImportObserver
38
{
39
40
    /**
41
     * The key for the additional data containing the swatch type.
42
     *
43
     * @var string
44
     */
45
    const SWATCH_INPUT_TYPE = 'swatch_input_type';
46
47
    /**
48
     * The available swatch types.
49
     *
50
     * @var array
51
     */
52
    protected $swatchTypes = array('text', 'visual', 'image');
53
54
    /**
55
     * The attribute processor instance.
56
     *
57
     * @var \TechDivision\Import\Attribute\Services\AttributeBunchProcessorInterface
58
     */
59
    protected $attributeBunchProcessor;
60
61
    /**
62
     * The array with the possible column names.
63
     *
64
     * @var array
65
     */
66
    protected $columnNames = array(
67
        ColumnKeys::FRONTEND_INPUT_RENDERER,
68
        ColumnKeys::IS_GLOBAL,
69
        ColumnKeys::IS_VISIBLE,
70
        ColumnKeys::IS_SEARCHABLE,
71
        ColumnKeys::IS_FILTERABLE,
72
        ColumnKeys::IS_COMPARABLE,
73
        ColumnKeys::IS_VISIBLE_ON_FRONT,
74
        ColumnKeys::IS_HTML_ALLOWED_ON_FRONT,
75
        ColumnKeys::IS_USED_FOR_PRICE_RULES,
76
        ColumnKeys::IS_FILTERABLE_IN_SEARCH,
77
        ColumnKeys::USED_IN_PRODUCT_LISTING,
78
        ColumnKeys::USED_FOR_SORT_BY,
79
        ColumnKeys::APPLY_TO,
80
        ColumnKeys::IS_VISIBLE_IN_ADVANCED_SEARCH,
81
        ColumnKeys::POSITION,
82
        ColumnKeys::IS_WYSIWYG_ENABLED,
83
        ColumnKeys::IS_USED_FOR_PROMO_RULES,
84
        ColumnKeys::IS_REQUIRED_IN_ADMIN_STORE,
85
        ColumnKeys::IS_USED_IN_GRID,
86
        ColumnKeys::IS_VISIBLE_IN_GRID,
87
        ColumnKeys::IS_FILTERABLE_IN_GRID,
88
        ColumnKeys::SEARCH_WEIGHT,
89
        ColumnKeys::ADDITIONAL_DATA
90
    );
91
92
    /**
93
     * Initializes the observer with the passed subject instance.
94
     *
95
     * @param \TechDivision\Import\Attribute\Services\AttributeBunchProcessorInterface $attributeBunchProcessor The attribute bunch processor instance
96
     */
97 3
    public function __construct(AttributeBunchProcessorInterface $attributeBunchProcessor)
98
    {
99 3
        $this->attributeBunchProcessor = $attributeBunchProcessor;
100 3
    }
101
102
    /**
103
     * Process the observer's business logic.
104
     *
105
     * @return void
106
     */
107 3
    protected function process()
108
    {
109
110
        // query whether or not, we've found a new attribute code => means we've found a new attribute
111 3
        if ($this->hasBeenProcessed($this->getValue(ColumnKeys::ATTRIBUTE_CODE))) {
112
            return;
113
        }
114
115
        // initialize and persist the EAV catalog attribute
116 3
        $this->persistCatalogAttribute($this->initializeAttribute($this->prepareAttributes()));
117 3
    }
118
119
    /**
120
     * Prepare the attributes of the entity that has to be persisted.
121
     *
122
     * @return array The prepared attributes
123
     * @throws \Exception Is thrown, if the size of the option values doesn't equals the size of swatch values, in case
124
     */
125 3
    protected function prepareAttributes()
126
    {
127
128
        // load the recently created EAV attribute ID
129 3
        $attributeId = $this->getLastAttributeId();
130
131
        // initialize the attributes
132 3
        $attr = array(MemberNames::ATTRIBUTE_ID => $attributeId);
133
134
        // iterate over the possible columns and handle the data
135 3
        foreach ($this->columnNames as $columnName) {
136
            // query whether or not, the column is available in the CSV file
137 3
            if ($this->getSubject()->hasHeader($columnName)) {
138
                // custom handling for the additional_data column
139 1
                if ($columnName === ColumnKeys::ADDITIONAL_DATA) {
140
                    // load the raw additional data
141 1
                    $explodedAdditionalData = $this->getValue(ColumnKeys::ADDITIONAL_DATA, array(), array($this->getSubject(), 'explode'));
142
143
                    // query whether or not additional data has been set
144 1
                    if (sizeof($explodedAdditionalData) > 0) {
145
                        // load and extract the additional data
146 1
                        $additionalData = array();
147 1
                        foreach ($explodedAdditionalData as $value) {
148 1
                            list ($key, $val) = $this->getSubject()->explode($value, '=');
149 1
                            $additionalData[$key] = $val;
150
                        }
151
152
                        // set the additional data
153 1
                        $attr[$columnName] = $additionalData;
154
155
                        // query whether or not the attribute is a text or a visual swatch
156 1
                        if ($this->isSwatchType($additionalData)) {
157
                            // load the attribute option values for the custom store views
158 1
                            $attributeOptionValues = $this->getValue(ColumnKeys::ATTRIBUTE_OPTION_VALUES, array(), array($this, 'explode'));
159 1
                            $attributeOptionSwatch = $this->getSubject()->explode($this->getValue(ColumnKeys::ATTRIBUTE_OPTION_SWATCH), $this->getSubject()->getMultipleValueDelimiter());
160
161
                            // query whether or not the size of the option values equals the size of the swatch values
162 1
                            if (($sizeOfSwatchValues = sizeof($attributeOptionSwatch)) !== ($sizeOfOptionValues = sizeof($attributeOptionValues))) {
163
                                throw new \Exception(
164
                                    sprintf(
165
                                        'Size of option values "%d" doesn\'t equals size of swatch values "%d"',
166
                                        $sizeOfOptionValues,
167 1
                                        $sizeOfSwatchValues
168
                                    )
169
                                );
170
                            }
171
                        }
172
                    }
173
                } 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
                    }
178
                }
179
            }
180
        }
181
182
        // return the prepared product
183 3
        return $this->initializeEntity($this->loadRawEntity($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]) && $attr[MemberNames::ADDITIONAL_DATA] !== null) {
198 2
            $attr[MemberNames::ADDITIONAL_DATA] = json_encode($attr[MemberNames::ADDITIONAL_DATA]);
199
        }
200
201
        // return the attribute
202 3
        return $attr;
203
    }
204
205
    /**
206
     * Load's and return's a raw customer entity without primary key but the mandatory members only and nulled values.
207
     *
208
     * @param array $data An array with data that will be used to initialize the raw entity with
209
     *
210
     * @return array The initialized entity
211
     */
212 3
    protected function loadRawEntity(array $data = array())
213
    {
214 3
        return $this->getAttributeBunchProcessor()->loadRawEntity(EntityTypeCodes::CATALOG_EAV_ATTRIBUTE, $data);
215
    }
216
217
    /**
218
     * Initialize the attribute with the passed attributes and returns an instance.
219
     *
220
     * @param array $attr The attribute attributes
221
     *
222
     * @return array The initialized attribute
223
     */
224 1
    protected function initializeAttribute(array $attr)
225
    {
226 1
        return $this->serializeAdditionalData($attr);
227
    }
228
229
    /**
230
     * Return's the attribute bunch processor instance.
231
     *
232
     * @return \TechDivision\Import\Attribute\Services\AttributeBunchProcessorInterface The attribute bunch processor instance
233
     */
234 3
    protected function getAttributeBunchProcessor()
235
    {
236 3
        return $this->attributeBunchProcessor;
237
    }
238
239
    /**
240
     * Map's the passed attribute code to the attribute ID that has been created recently.
241
     *
242
     * @param string $attributeCode The attribute code that has to be mapped
243
     *
244
     * @return void
245
     */
246
    protected function addAttributeCodeIdMapping($attributeCode)
247
    {
248
        $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...
249
    }
250
251
    /**
252
     * Queries whether or not the attribute with the passed code has already been processed.
253
     *
254
     * @param string $attributeCode The attribute code to check
255
     *
256
     * @return boolean TRUE if the path has been processed, else FALSE
257
     */
258 3
    protected function hasBeenProcessed($attributeCode)
259
    {
260 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...
261
    }
262
263
    /**
264
     * Return's the ID of the attribute that has been created recently.
265
     *
266
     * @return integer The attribute ID
267
     */
268 3
    protected function getLastAttributeId()
269
    {
270 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...
271
    }
272
273
    /**
274
     * Return's TRUE if the additional data contains a swatch type.
275
     *
276
     * @param array $additionalData The additional data to query for a valid swatch type
277
     *
278
     * @return boolean TRUE if the data contains a swatch type, else FALSE
279
     */
280 1
    protected function isSwatchType(array $additionalData)
281
    {
282 1
        return isset($additionalData[CatalogAttributeObserver::SWATCH_INPUT_TYPE]) && in_array($additionalData[CatalogAttributeObserver::SWATCH_INPUT_TYPE], $this->swatchTypes);
283
    }
284
285
    /**
286
     * Persist the passed EAV catalog attribute.
287
     *
288
     * @param array $catalogAttribute The EAV catalog attribute to persist
289
     *
290
     * @return void
291
     */
292 3
    protected function persistCatalogAttribute(array $catalogAttribute)
293
    {
294 3
        return $this->getAttributeBunchProcessor()->persistCatalogAttribute($catalogAttribute);
295
    }
296
}
297