Completed
Pull Request — master (#40)
by Tim
05:25
created

getDefaultFrontendInputCallbackMappings()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

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
eloc 2
nc 1
nop 0
crap 2
1
<?php
2
3
/**
4
 * TechDivision\Import\Subjects\AbstractSubject
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
18
 * @link      http://www.techdivision.com
19
 */
20
21
namespace TechDivision\Import\Subjects;
22
23
use TechDivision\Import\Utils\MemberNames;
24
use TechDivision\Import\Utils\RegistryKeys;
25
26
/**
27
 * An abstract EAV subject implementation.
28
 *
29
 * @author    Tim Wagner <[email protected]>
30
 * @copyright 2016 TechDivision GmbH <[email protected]>
31
 * @license   http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
32
 * @link      https://github.com/techdivision/import
33
 * @link      http://www.techdivision.com
34
 */
35
abstract class AbstractEavSubject extends AbstractSubject implements EavSubjectInterface
36
{
37
38
    /**
39
     * The available EAV attributes, grouped by their attribute set and the attribute set name as keys.
40
     *
41
     * @var array
42
     */
43
    protected $attributes = array();
44
45
    /**
46
     * The available user defined EAV attributes, grouped by their entity type.
47
     *
48
     * @var array
49
     */
50
    protected $userDefinedAttributes = array();
51
52
    /**
53
     * The attribute set of the entity that has to be created.
54
     *
55
     * @var array
56
     */
57
    protected $attributeSet = array();
58
59
    /**
60
     * The available EAV attribute sets.
61
     *
62
     * @var array
63
     */
64
    protected $attributeSets = array();
65
66
    /**
67
     * The mapping for the supported backend types (for the EAV entity) => persist methods.
68
     *
69
     * @var array
70
     */
71
    protected $backendTypes = array(
72
        'datetime' => array('persistDatetimeAttribute', 'loadDatetimeAttribute'),
73
        'decimal'  => array('persistDecimalAttribute', 'loadDecimalAttribute'),
74
        'int'      => array('persistIntAttribute', 'loadIntAttribute'),
75
        'text'     => array('persistTextAttribute', 'loadTextAttribute'),
76
        'varchar'  => array('persistVarcharAttribute', 'loadVarcharAttribute')
77
    );
78
79
    /**
80
     * The default mappings for the user defined attributes, based on the attributes frontend input type.
81
     *
82
     * @var array
83
     */
84
    protected $defaultFrontendInputCallbackMappings = array(
85
        'select' => 'TechDivision\\Import\\Callbacks\\SelectCallback',
86
        'multiselect' => 'TechDivision\\Import\\Callbacks\\MultiselectCallback',
87
        'boolean' => 'TechDivision\\Import\\Callbacks\\BooleanCallback'
88
    );
89
90
    /**
91
     * Return's the default callback frontend input mappings for the user defined attributes.
92
     *
93
     * @return array The default frontend input callback mappings
94
     */
95
    public function getDefaultFrontendInputCallbackMappings()
96
    {
97
        return $this->defaultFrontendInputCallbackMappings;
98
    }
99
100
    /**
101
     * Intializes the previously loaded global data for exactly one bunch.
102
     *
103
     * @return void
104
     * @see \Importer\Csv\Actions\ProductImportAction::prepare()
105
     */
106
    public function setUp()
107
    {
108
109
        // load the status of the actual import
110
        $status = $this->getRegistryProcessor()->getAttribute($this->getSerial());
111
112
        // load the global data we've prepared initially
113
        $this->attributes = $status[RegistryKeys::GLOBAL_DATA][RegistryKeys::EAV_ATTRIBUTES];
114
        $this->attributeSets = $status[RegistryKeys::GLOBAL_DATA][RegistryKeys::ATTRIBUTE_SETS];
115
        $this->userDefinedAttributes = $status[RegistryKeys::GLOBAL_DATA][RegistryKeys::EAV_USER_DEFINED_ATTRIBUTES];
116
117
        // load the default frontend callback mappings from the child instance
118
        $defaultFrontendInputCallbackMappings = $this->getDefaultFrontendInputCallbackMappings();
119
120
        // load the user defined attributes and add the callback mappings
121
        foreach ($this->getEavUserDefinedAttributes() as $eavAttribute) {
122
            // load attribute code and frontend input type
123
            $attributeCode = $eavAttribute[MemberNames::ATTRIBUTE_CODE];
124
            $frontendInput = $eavAttribute[MemberNames::FRONTEND_INPUT];
125
126
            // query whether or not the array for the mappings has been initialized
127
            if (!isset($this->callbackMappings[$attributeCode])) {
128
                $this->callbackMappings[$attributeCode] = array();
129
            }
130
131
            // set the appropriate callback mapping for the attributes input type
132
            if (isset($defaultFrontendInputCallbackMappings[$frontendInput])) {
133
                $this->callbackMappings[$attributeCode][] = $defaultFrontendInputCallbackMappings[$frontendInput];
134
            }
135
        }
136
137
        // prepare the callbacks
138
        parent::setUp();
139
    }
140
141
    /**
142
     * Return's mapping for the supported backend types (for the product entity) => persist methods.
143
     *
144
     * @return array The mapping for the supported backend types
145
     */
146
    public function getBackendTypes()
147
    {
148
        return $this->backendTypes;
149
    }
150
151
    /**
152
     * Set's the attribute set of the product that has to be created.
153
     *
154
     * @param array $attributeSet The attribute set
155
     *
156
     * @return void
157
     */
158
    public function setAttributeSet(array $attributeSet)
159
    {
160
        $this->attributeSet = $attributeSet;
161
    }
162
163
    /**
164
     * Return's the attribute set of the product that has to be created.
165
     *
166
     * @return array The attribute set
167
     */
168
    public function getAttributeSet()
169
    {
170
        return $this->attributeSet;
171
    }
172
173
    /**
174
     * Return's the store ID of the actual row, or of the default store
175
     * if no store view code is set in the CSV file.
176
     *
177
     * @param string|null $default The default store view code to use, if no store view code is set in the CSV file
178
     *
179
     * @return integer The ID of the actual store
180
     * @throws \Exception Is thrown, if the store with the actual code is not available
181
     */
182
    public function getRowStoreId($default = null)
183
    {
184
185
        // initialize the default store view code, if not passed
186
        if ($default == null) {
0 ignored issues
show
Bug introduced by
It seems like you are loosely comparing $default of type string|null against null; this is ambiguous if the string can be empty. Consider using a strict comparison === instead.
Loading history...
187
            $defaultStore = $this->getDefaultStore();
188
            $default = $defaultStore[MemberNames::CODE];
189
        }
190
191
        // load the store view code the create the product/attributes for
192
        $storeViewCode = $this->getStoreViewCode($default);
193
194
        // query whether or not, the requested store is available
195
        if (isset($this->stores[$storeViewCode])) {
196
            return (integer) $this->stores[$storeViewCode][MemberNames::STORE_ID];
0 ignored issues
show
Bug introduced by
The property stores 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...
197
        }
198
199
        // throw an exception, if not
200
        throw new \Exception(
201
            sprintf(
202
                'Found invalid store view code %s in file %s on line %d',
203
                $storeViewCode,
204
                $this->getFilename(),
205
                $this->getLineNumber()
206
            )
207
        );
208
    }
209
210
    /**
211
     * Cast's the passed value based on the backend type information.
212
     *
213
     * @param string $backendType The backend type to cast to
214
     * @param mixed  $value       The value to be casted
215
     *
216
     * @return mixed The casted value
217
     */
218
    public function castValueByBackendType($backendType, $value)
219
    {
220
221
        // cast the value to a valid timestamp
222
        if ($backendType === 'datetime') {
223
            return \DateTime::createFromFormat($this->getSourceDateFormat(), $value)->format('Y-m-d H:i:s');
224
        }
225
226
        // cast the value to a float value
227
        if ($backendType === 'float') {
228
            return (float) $value;
229
        }
230
231
        // cast the value to an integer
232
        if ($backendType === 'int') {
233
            return (int) $value;
234
        }
235
236
        // we don't need to cast strings
237
        return $value;
238
    }
239
240
    /**
241
     * Return's the entity type code to be used.
242
     *
243
     * @return string The entity type code to be used
244
     */
245
    public function getEntityTypeCode()
246
    {
247
        return $this->getConfiguration()->getConfiguration()->getEntityTypeCode();
248
    }
249
250
    /**
251
     * Return's the attribute set with the passed attribute set name.
252
     *
253
     * @param string $attributeSetName The name of the requested attribute set
254
     *
255
     * @return array The attribute set data
256
     * @throws \Exception Is thrown, if the attribute set with the passed name is not available
257
     */
258 View Code Duplication
    public function getAttributeSetByAttributeSetName($attributeSetName)
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...
259
    {
260
261
        // query whether or not attribute sets for the actualy entity type code are available
262
        if (isset($this->attributeSets[$entityTypeCode = $this->getEntityTypeCode()])) {
263
            // load the attribute sets for the actualy entity type code
264
            $attributSets = $this->attributeSets[$entityTypeCode];
265
266
            // query whether or not, the requested attribute set is available
267
            if (isset($attributSets[$attributeSetName])) {
268
                return $attributSets[$attributeSetName];
269
            }
270
        }
271
272
        // throw an exception, if not
273
        throw new \Exception(
274
            sprintf(
275
                'Found invalid attribute set name %s in file %s on line %d',
276
                $attributeSetName,
277
                $this->getFilename(),
278
                $this->getLineNumber()
279
            )
280
        );
281
    }
282
283
    /**
284
     * Return's the attributes for the attribute set of the product that has to be created.
285
     *
286
     * @return array The attributes
287
     * @throws \Exception Is thrown if the attributes for the actual attribute set are not available
288
     */
289 View Code Duplication
    public function getAttributes()
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...
290
    {
291
292
        // query whether or not, the requested EAV attributes are available
293
        if (isset($this->attributes[$entityTypeCode = $this->getEntityTypeCode()])) {
294
            // load the attributes for the entity type code
295
            $attributes = $this->attributes[$entityTypeCode];
296
297
            // query whether or not attributes for the actual attribute set name
298
            if (isset($attributes[$attributeSetName = $this->attributeSet[MemberNames::ATTRIBUTE_SET_NAME]])) {
299
                return $attributes[$attributeSetName];
300
            }
301
        }
302
303
        // throw an exception, if not
304
        throw new \Exception(
305
            sprintf(
306
                'Found invalid attribute set name "%s" in file %s on line %d',
307
                $attributeSetName,
308
                $this->getFilename(),
309
                $this->getLineNumber()
310
            )
311
        );
312
    }
313
314
    /**
315
     * Return's an array with the available user defined EAV attributes for the actual entity type.
316
     *
317
     * @return array The array with the user defined EAV attributes
318
     */
319
    public function getEavUserDefinedAttributes()
320
    {
321
322
        // query whether or not user defined attributes for the actualy entity type are available
323
        if (isset($this->userDefinedAttributes[$entityTypeCode = $this->getEntityTypeCode()])) {
324
            return $this->userDefinedAttributes[$entityTypeCode];
325
        }
326
327
        // throw an exception if an unknown entity type has been passed
328
        throw new \Exception(sprintf('Unknown entity type code %s', $entityTypeCode));
329
    }
330
331
    /**
332
     * Return's the EAV attribute with the passed attribute code.
333
     *
334
     * @param string $attributeCode The attribute code
335
     *
336
     * @return array The array with the EAV attribute
337
     * @throws \Exception Is thrown if the attribute with the passed code is not available
338
     */
339
    public function getEavAttributeByAttributeCode($attributeCode)
340
    {
341
342
        // load the attributes
343
        $attributes = $this->getAttributes();
344
345
        // query whether or not the attribute exists
346
        if (isset($attributes[$attributeCode])) {
347
            return $attributes[$attributeCode];
348
        }
349
350
        // throw an exception if the requested attribute is not available
351
        throw new \Exception(
352
            sprintf(
353
                'Can\'t load attribute with code "%s" in file %s and line %d',
354
                $attributeCode,
355
                $this->getFilename(),
356
                $this->getLineNumber()
357
            )
358
        );
359
    }
360
}
361