Completed
Push — master ( 0ce8a4...9a185e )
by Tim
9s
created

AbstractObserver::getSourceDateFormat()   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\Observers\AbstractObserver
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\Observers;
22
23
use TechDivision\Import\Utils\ScopeKeys;
24
use TechDivision\Import\Utils\ColumnKeys;
25
use TechDivision\Import\Utils\LoggerKeys;
26
use TechDivision\Import\Utils\EntityStatus;
27
28
/**
29
 * An abstract observer implementation.
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
35
 * @link      http://www.techdivision.com
36
 */
37
abstract class AbstractObserver implements ObserverInterface
38
{
39
40
    /**
41
     * The actual row, that has to be processed.
42
     *
43
     * @var array
44
     */
45
    protected $row = array();
46
47
    /**
48
     * The obeserver's subject instance.
49
     *
50
     * @var object
51
     */
52
    protected $subject;
53
54
    /**
55
     * Initializes the observer with the passed subject instance.
56
     *
57
     * @param object|null $subject The observer's subject instance
58
     */
59
    public function __construct($subject = null)
60
    {
61
        if ($subject != null) {
62
            $this->setSubject($subject);
63
        }
64
    }
65
66
    /**
67
     * Set's the obeserver's subject instance to initialize the observer with.
68
     *
69
     * @param object $subject The observer's subject
70
     *
71
     * @return void
72
     */
73
    public function setSubject($subject)
74
    {
75
        $this->subject = $subject;
76
    }
77
78
    /**
79
     * Return's the observer's subject instance.
80
     *
81
     * @return object The observer's subject instance
82
     */
83
    public function getSubject()
84
    {
85
        return $this->subject;
86
    }
87
88
    /**
89
     * Set's the array containing header row.
90
     *
91
     * @param array $headers The array with the header row
92
     *
93
     * @return void
94
     */
95
    public function setHeaders(array $headers)
96
    {
97
        $this->getSubject()->setHeaders($headers);
98
    }
99
100
    /**
101
     * Return's the array containing header row.
102
     *
103
     * @return array The array with the header row
104
     */
105
    public function getHeaders()
106
    {
107
        return $this->getSubject()->getHeaders();
108
    }
109
110
    /**
111
     * Return's the RegistryProcessor instance to handle the running threads.
112
     *
113
     * @return \TechDivision\Import\Services\RegistryProcessorInterface The registry processor instance
114
     */
115
    public function getRegistryProcessor()
116
    {
117
        return $this->getSubject()->getRegistryProcessor();
118
    }
119
120
    /**
121
     * Set's the actual row, that has to be processed.
122
     *
123
     * @param array $row The row
124
     *
125
     * @return void
126
     */
127
    protected function setRow(array $row)
128
    {
129
        $this->row = $row;
130
    }
131
132
    /**
133
     * Return's the actual row, that has to be processed.
134
     *
135
     * @return array The row
136
     */
137
    protected function getRow()
138
    {
139
        return $this->row;
140
    }
141
142
    /**
143
     * Append's the exception suffix containing filename and line number to the
144
     * passed message. If no message has been passed, only the suffix will be
145
     * returned
146
     *
147
     * @param string|null $message    The message to append the exception suffix to
148
     * @param string|null $filename   The filename used to create the suffix
149
     * @param string|null $lineNumber The line number used to create the suffx
150
     *
151
     * @return string The message with the appended exception suffix
152
     */
153
    protected function appendExceptionSuffix($message = null, $filename = null, $lineNumber = null)
154
    {
155
        return $this->getSubject()-> appendExceptionSuffix($message, $filename, $lineNumber);
156
    }
157
158
    /**
159
     * Wraps the passed exeception into a new one by trying to resolve the original filname,
160
     * line number and column name and use it for a detailed exception message.
161
     *
162
     * @param string     $columnName The column name that should be resolved
163
     * @param \Exception $parent     The exception we want to wrap
164
     * @param string     $className  The class name of the exception type we want to wrap the parent one
165
     *
166
     * @return \Exception the wrapped exception
167
     */
168
    protected function wrapException(
169
        $columnName,
170
        \Exception $parent = null,
171
        $className = '\TechDivision\Import\Exceptions\WrappedColumnException'
172
    ) {
173
        return $this->getSubject()->wrapException($columnName, $parent, $className);
174
    }
175
176
    /**
177
     * Queries whether or not debug mode is enabled or not, default is TRUE.
178
     *
179
     * @return boolean TRUE if debug mode is enabled, else FALSE
180
     */
181
    protected function isDebugMode()
182
    {
183
        return $this->getSubject()->isDebugMode();
184
    }
185
186
    /**
187
     * Stop's observer execution on the actual row.
188
     *
189
     * @return void
190
     */
191
    protected function skipRow()
192
    {
193
        $this->getSubject()->skipRow();
194
    }
195
196
    /**
197
     * Return's the name of the file to import.
198
     *
199
     * @return string The filename
200
     */
201
    protected function getFilename()
202
    {
203
        return $this->getSubject()->getFilename();
204
    }
205
206
    /**
207
     * Return's the actual line number.
208
     *
209
     * @return integer The line number
210
     */
211
    protected function getLineNumber()
212
    {
213
        return $this->getSubject()->getLineNumber();
214
    }
215
216
    /**
217
     * Return's the logger with the passed name, by default the system logger.
218
     *
219
     * @param string $name The name of the requested system logger
220
     *
221
     * @return \Psr\Log\LoggerInterface The logger instance
222
     * @throws \Exception Is thrown, if the requested logger is NOT available
223
     */
224
    protected function getSystemLogger($name = LoggerKeys::SYSTEM)
225
    {
226
        return $this->getSubject()->getSystemLogger($name);
227
    }
228
229
    /**
230
     * Return's the array with the system logger instances.
231
     *
232
     * @return array The logger instance
233
     */
234
    protected function getSystemLoggers()
235
    {
236
        return $this->getSubject()->getSystemLoggers();
237
    }
238
239
    /**
240
     * Return's the multiple field delimiter character to use, default value is comma (,).
241
     *
242
     * @return string The multiple field delimiter character
243
     */
244
    protected function getMultipleFieldDelimiter()
245
    {
246
        return $this->getSubject()->getMultipleFieldDelimiter();
247
    }
248
249
    /**
250
     * Queries whether or not the header with the passed name is available.
251
     *
252
     * @param string $name The header name to query
253
     *
254
     * @return boolean TRUE if the header is available, else FALSE
255
     */
256
    protected function hasHeader($name)
257
    {
258
        return $this->getSubject()->hasHeader($name);
259
    }
260
261
    /**
262
     * Return's the header value for the passed name.
263
     *
264
     * @param string $name The name of the header to return the value for
265
     *
266
     * @return mixed The header value
267
     * \InvalidArgumentException Is thrown, if the header with the passed name is NOT available
268
     */
269
    protected function getHeader($name)
270
    {
271
        return $this->getSubject()->getHeader($name);
272
    }
273
274
    /**
275
     * Add's the header with the passed name and position, if not NULL.
276
     *
277
     * @param string $name The header name to add
278
     *
279
     * @return integer The new headers position
280
     */
281
    protected function addHeader($name)
282
    {
283
        return $this->getSubject()->addHeader($name);
284
    }
285
286
    /**
287
     * Return's the ID of the product that has been created recently.
288
     *
289
     * @return string The entity Id
290
     */
291
    protected function getLastEntityId()
292
    {
293
        return $this->getSubject()->getLastEntityId();
294
    }
295
296
    /**
297
     * Return's the source date format to use.
298
     *
299
     * @return string The source date format
300
     */
301
    protected function getSourceDateFormat()
302
    {
303
        return $this->getSubject()->getSourceDateFormat();
304
    }
305
306
    /**
307
     * Cast's the passed value based on the backend type information.
308
     *
309
     * @param string $backendType The backend type to cast to
310
     * @param mixed  $value       The value to be casted
311
     *
312
     * @return mixed The casted value
313
     */
314
    protected function castValueByBackendType($backendType, $value)
315
    {
316
        return $this->getSubject()->castValueByBackendType($backendType, $value);
317
    }
318
319
    /**
320
     * Set's the store view code the create the product/attributes for.
321
     *
322
     * @param string $storeViewCode The store view code
323
     *
324
     * @return void
325
     */
326
    protected function setStoreViewCode($storeViewCode)
327
    {
328
        $this->getSubject()->setStoreViewCode($storeViewCode);
329
    }
330
331
    /**
332
     * Return's the store view code the create the product/attributes for.
333
     *
334
     * @param string|null $default The default value to return, if the store view code has not been set
335
     *
336
     * @return string The store view code
337
     */
338
    protected function getStoreViewCode($default = null)
339
    {
340
        return $this->getSubject()->getStoreViewCode($default);
341
    }
342
343
    /**
344
     * Prepare's the store view code in the subject.
345
     *
346
     * @return void
347
     */
348
    protected function prepareStoreViewCode()
349
    {
350
351
        // re-set the store view code
352
        $this->setStoreViewCode(null);
353
354
        // initialize the store view code
355
        if ($storeViewCode = $this->getValue(ColumnKeys::STORE_VIEW_CODE)) {
356
            $this->setStoreViewCode($storeViewCode);
357
        }
358
    }
359
360
    /**
361
     * Tries to format the passed value to a valid date with format 'Y-m-d H:i:s'.
362
     * If the passed value is NOT a valid date, NULL will be returned.
363
     *
364
     * @param string|null $value The value to format
365
     *
366
     * @return string The formatted date
367
     */
368
    protected function formatDate($value)
369
    {
370
371
        // create a DateTime instance from the passed value
372
        if ($dateTime = \DateTime::createFromFormat($this->getSourceDateFormat(), $value)) {
373
            return $dateTime->format('Y-m-d H:i:s');
374
        }
375
376
        // return NULL, if the passed value is NOT a valid date
377
        return null;
378
    }
379
380
    /**
381
     * Extracts the elements of the passed value by exploding them
382
     * with the also passed delimiter.
383
     *
384
     * @param string      $value     The value to extract
385
     * @param string|null $delimiter The delimiter used to extrace the elements
386
     *
387
     * @return array The exploded values
388
     */
389
    protected function explode($value, $delimiter = null)
390
    {
391
392
        // load the default multiple field delimiter
393
        if ($delimiter === null) {
394
            $delimiter = $this->getMultipleFieldDelimiter();
395
        }
396
397
        // explode and return the array with the values, by using the delimiter
398
        return explode($delimiter, $value);
399
    }
400
401
    /**
402
     * Query whether or not a value for the column with the passed name exists.
403
     *
404
     * @param string $name The column name to query for a valid value
405
     *
406
     * @return boolean TRUE if the value is set, else FALSE
407
     */
408
    protected function hasValue($name)
409
    {
410
411
        // query whether or not the header is available
412
        if ($this->hasHeader($name)) {
413
            // load the key for the row
414
            $headerValue = $this->getHeader($name);
415
416
            // query whether the rows column has a vaild value
417
            return (isset($this->row[$headerValue]) && $this->row[$headerValue] != '');
418
        }
419
420
        // return FALSE if not
421
        return false;
422
    }
423
424
    /**
425
     * Set the value in the passed column name.
426
     *
427
     * @param string $name  The column name to set the value for
428
     * @param mixed  $value The value to set
429
     *
430
     * @return void
431
     */
432
    protected function setValue($name, $value)
433
    {
434
        $this->row[$this->getHeader($name)] = $value;
435
    }
436
437
    /**
438
     * Resolve's the value with the passed colum name from the actual row. If a callback will
439
     * be passed, the callback will be invoked with the found value as parameter. If
440
     * the value is NULL or empty, the default value will be returned.
441
     *
442
     * @param string        $name     The name of the column to return the value for
443
     * @param mixed|null    $default  The default value, that has to be returned, if the row's value is empty
444
     * @param callable|null $callback The callback that has to be invoked on the value, e. g. to format it
445
     *
446
     * @return mixed|null The, almost formatted, value
447
     */
448
    protected function getValue($name, $default = null, callable $callback = null)
449
    {
450
451
        // initialize the value
452
        $value = null;
453
454
        // query whether or not the header is available
455
        if ($this->hasHeader($name)) {
456
            // load the header value
457
            $headerValue = $this->getHeader($name);
458
            // query wheter or not, the value with the requested key is available
459
            if ((isset($this->row[$headerValue]) && $this->row[$headerValue] != '')) {
460
                $value = $this->row[$headerValue];
461
            }
462
        }
463
464
        // query whether or not, a callback has been passed
465
        if ($value != null && is_callable($callback)) {
466
            $value = call_user_func($callback, $value);
467
        }
468
469
        // query whether or not
470
        if ($value == null && $default !== null) {
471
            $value = $default;
472
        }
473
474
        // return the value
475
        return $value;
476
    }
477
478
    /**
479
     * Return's the Magento configuration value.
480
     *
481
     * @param string  $path    The Magento path of the requested configuration value
482
     * @param mixed   $default The default value that has to be returned, if the requested configuration value is not set
483
     * @param string  $scope   The scope the configuration value has been set
484
     * @param integer $scopeId The scope ID the configuration value has been set
485
     *
486
     * @return mixed The configuration value
487
     * @throws \Exception Is thrown, if nor a value can be found or a default value has been passed
488
     */
489
    protected function getCoreConfigData($path, $default = null, $scope = ScopeKeys::SCOPE_DEFAULT, $scopeId = 0)
490
    {
491
        return $this->getSubject()->getCoreConfigData($path, $default, $scope, $scopeId);
492
    }
493
494
    /**
495
     * Initialize's and return's a new entity with the status 'create'.
496
     *
497
     * @param array $attr The attributes to merge into the new entity
498
     *
499
     * @return array The initialized entity
500
     */
501
    protected function initializeEntity(array $attr = array())
502
    {
503
        return array_merge(array(EntityStatus::MEMBER_NAME => EntityStatus::STATUS_CREATE), $attr);
504
    }
505
506
    /**
507
     * Merge's and return's the entity with the passed attributes and set's the
508
     * status to 'update'.
509
     *
510
     * @param array $entity The entity to merge the attributes into
511
     * @param array $attr   The attributes to be merged
512
     *
513
     * @return array The merged entity
514
     */
515
    protected function mergeEntity(array $entity, array $attr)
516
    {
517
        return array_merge($entity, $attr, array(EntityStatus::MEMBER_NAME => EntityStatus::STATUS_UPDATE));
518
    }
519
}
520