Completed
Pull Request — master (#89)
by Tim
02:19
created

AbstractSubject::getValue()   C

Complexity

Conditions 8
Paths 12

Size

Total Lines 29
Code Lines 11

Duplication

Lines 29
Ratio 100 %

Code Coverage

Tests 0
CRAP Score 72

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 29
loc 29
ccs 0
cts 17
cp 0
rs 5.3846
cc 8
eloc 11
nc 12
nop 3
crap 72

2 Methods

Rating   Name   Duplication   Size   Complexity  
A AbstractSubject::setImportAdapter() 0 4 1
A AbstractSubject::getImportAdapter() 0 4 1
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\RowTrait;
24
use TechDivision\Import\HeaderTrait;
25
use TechDivision\Import\SystemLoggerTrait;
26
use TechDivision\Import\Utils\ScopeKeys;
27
use TechDivision\Import\Utils\ColumnKeys;
28
use TechDivision\Import\Utils\MemberNames;
29
use TechDivision\Import\Utils\RegistryKeys;
30
use TechDivision\Import\Utils\Generators\GeneratorInterface;
31
use TechDivision\Import\Services\RegistryProcessor;
32
use TechDivision\Import\Callbacks\CallbackInterface;
33
use TechDivision\Import\Observers\ObserverInterface;
34
use TechDivision\Import\Adapter\ImportAdapterInterface;
35
use TechDivision\Import\Exceptions\WrappedColumnException;
36
use TechDivision\Import\Services\RegistryProcessorInterface;
37
use TechDivision\Import\Configuration\SubjectConfigurationInterface;
38
39
/**
40
 * An abstract subject implementation.
41
 *
42
 * @author    Tim Wagner <[email protected]>
43
 * @copyright 2016 TechDivision GmbH <[email protected]>
44
 * @license   http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
45
 * @link      https://github.com/techdivision/import
46
 * @link      http://www.techdivision.com
47
 */
48
abstract class AbstractSubject implements SubjectInterface
49
{
50
51
    /**
52
     * The trait that provides basic filesystem handling functionality.
53
     *
54
     * @var TechDivision\Import\Subjects\FilesystemTrait
55
     */
56
    use FilesystemTrait;
57
58
    /**
59
     * The trait that provides basic filesystem handling functionality.
60
     *
61
     * @var TechDivision\Import\SystemLoggerTrait
62
     */
63
    use SystemLoggerTrait;
64
65
    /**
66
     * The trait that provides header handling functionality.
67
     *
68
     * @var TechDivision\Import\HeaderTrait
69
     */
70
    use HeaderTrait;
71
72
    /**
73
     * The trait that provides row handling functionality.
74
     *
75
     * @var TechDivision\Import\RowTrait
76
     */
77
    use RowTrait;
78
79
    /**
80
     * The name of the file to be imported.
81
     *
82
     * @var string
83
     */
84
    protected $filename;
85
86
    /**
87
     * The actual line number.
88
     *
89
     * @var integer
90
     */
91
    protected $lineNumber = 0;
92
93
    /**
94
     * The actual operation name.
95
     *
96
     * @var string
97
     */
98
    protected $operationName ;
99
100
    /**
101
     * The flag that stop's overserver execution on the actual row.
102
     *
103
     * @var boolean
104
     */
105
    protected $skipRow = false;
106
107
    /**
108
     * The import adapter instance.
109
     *
110
     * @var \TechDivision\Import\Adapter\AdapterInterface
111
     */
112
    protected $importAdapter;
113
114
    /**
115
     * The system configuration.
116
     *
117
     * @var \TechDivision\Import\Configuration\SubjectConfigurationInterface
118
     */
119
    protected $configuration;
120
121
    /**
122
     * The RegistryProcessor instance to handle running threads.
123
     *
124
     * @var \TechDivision\Import\Services\RegistryProcessorInterface
125
     */
126
    protected $registryProcessor;
127
128
    /**
129
     * The actions unique serial.
130
     *
131
     * @var string
132
     */
133
    protected $serial;
134
135
    /**
136
     * Array with the subject's observers.
137
     *
138
     * @var array
139
     */
140
    protected $observers = array();
141
142
    /**
143
     * Array with the subject's callbacks.
144
     *
145
     * @var array
146
     */
147
    protected $callbacks = array();
148
149
    /**
150
     * The subject's callback mappings.
151
     *
152
     * @var array
153
     */
154
    protected $callbackMappings = array();
155
156
    /**
157
     * The available root categories.
158
     *
159
     * @var array
160
     */
161
    protected $rootCategories = array();
162
163
    /**
164
     * The Magento configuration.
165
     *
166
     * @var array
167
     */
168
    protected $coreConfigData = array();
169
170
    /**
171
     * The available stores.
172
     *
173
     * @var array
174
     */
175
    protected $stores = array();
176
177
    /**
178
     * The available websites.
179
     *
180
     * @var array
181
     */
182
    protected $storeWebsites = array();
183
184
    /**
185
     * The default store.
186
     *
187
     * @var array
188
     */
189
    protected $defaultStore;
190
191
    /**
192
     * The store view code the create the product/attributes for.
193
     *
194
     * @var string
195
     */
196
    protected $storeViewCode;
197
198
    /**
199
     * The UID generator for the core config data.
200
     *
201
     * @var \TechDivision\Import\Utils\Generators\GeneratorInterface
202
     */
203
    protected $coreConfigDataUidGenerator;
204
205
    /**
206
     * Initialize the subject instance.
207
     *
208
     * @param \TechDivision\Import\Services\RegistryProcessorInterface $registryProcessor          The registry processor instance
209
     * @param \TechDivision\Import\Utils\Generators\GeneratorInterface $coreConfigDataUidGenerator The UID generator for the core config data
210
     * @param array                                                    $systemLoggers              The array with the system loggers instances
211
     */
212 76
    public function __construct(
213
        RegistryProcessorInterface $registryProcessor,
214
        GeneratorInterface $coreConfigDataUidGenerator,
215
        array $systemLoggers
216
    ) {
217 76
        $this->systemLoggers = $systemLoggers;
218 76
        $this->registryProcessor = $registryProcessor;
219 76
        $this->coreConfigDataUidGenerator = $coreConfigDataUidGenerator;
220 76
    }
221
222
    /**
223
     * Set's the name of the file to import
224
     *
225
     * @param string $filename The filename
226
     *
227
     * @return void
228
     */
229 10
    public function setFilename($filename)
230
    {
231 10
        $this->filename = $filename;
232 10
    }
233
234
    /**
235
     * Return's the name of the file to import.
236
     *
237
     * @return string The filename
238
     */
239 8
    public function getFilename()
240
    {
241 8
        return $this->filename;
242
    }
243
244
    /**
245
     * Set's the actual operation name.
246
     *
247
     * @param string $operationName The actual operation name
248
     *
249
     * @return void
250
     */
251 1
    public function setOperationName($operationName)
252
    {
253 1
        $this->operationName = $operationName;
254 1
    }
255
256
    /**
257
     * Return's the actual operation name.
258
     *
259
     * @return string
260
     */
261 1
    public function getOperationName()
262
    {
263 1
        return $this->operationName;
264
    }
265
266
    /**
267
     * Set's the actual line number.
268
     *
269
     * @param integer $lineNumber The line number
270
     *
271
     * @return void
272
     */
273 1
    public function setLineNumber($lineNumber)
274
    {
275 1
        $this->lineNumber = $lineNumber;
276 1
    }
277
278
    /**
279
     * Return's the actual line number.
280
     *
281
     * @return integer The line number
282
     */
283 9
    public function getLineNumber()
284
    {
285 9
        return $this->lineNumber;
286
    }
287
288
    /**
289
     * Stop's observer execution on the actual row.
290
     *
291
     * @return void
292
     */
293 1
    public function skipRow()
294
    {
295 1
        $this->skipRow = true;
296 1
    }
297
298
    /**
299
     * Return's the default callback mappings.
300
     *
301
     * @return array The default callback mappings
302
     */
303 1
    public function getDefaultCallbackMappings()
304
    {
305 1
        return array();
306
    }
307
308
    /**
309
     * Tries to format the passed value to a valid date with format 'Y-m-d H:i:s'.
310
     * If the passed value is NOT a valid date, NULL will be returned.
311
     *
312
     * @param string $value The value to format
313
     *
314
     * @return string|null The formatted date or NULL if the date is not valid
315
     */
316 2
    public function formatDate($value)
317
    {
318
319
        // create a DateTime instance from the passed value
320 2
        if ($dateTime = \DateTime::createFromFormat($this->getSourceDateFormat(), $value)) {
321 1
            return $dateTime->format('Y-m-d H:i:s');
322
        }
323
324
        // return NULL, if the passed value is NOT a valid date
325 1
        return null;
326
    }
327
328
    /**
329
     * Extracts the elements of the passed value by exploding them
330
     * with the also passed delimiter.
331
     *
332
     * @param string      $value     The value to extract
333
     * @param string|null $delimiter The delimiter used to extrace the elements
334
     *
335
     * @return array The exploded values
336
     */
337 2
    public function explode($value, $delimiter = null)
338
    {
339
        // load the global configuration
340 2
        $configuration = $this->getConfiguration();
341
342
        // initializet delimiter, enclosure and escape char
343 2
        $delimiter = $delimiter ? $delimiter : $configuration->getDelimiter();
344 2
        $enclosure = $configuration->getEnclosure();
345 2
        $escape = $configuration->getEscape();
346
347
        // parse and return the found data as array
348 2
        return str_getcsv($value, $delimiter, $enclosure, $escape);
349
    }
350
351
    /**
352
     * Queries whether or not debug mode is enabled or not, default is TRUE.
353
     *
354
     * @return boolean TRUE if debug mode is enabled, else FALSE
355
     */
356 1
    public function isDebugMode()
357
    {
358 1
        return $this->getConfiguration()->isDebugMode();
359
    }
360
361
    /**
362
     * Set's the subject configuration.
363
     *
364
     * @param \TechDivision\Import\Configuration\SubjectConfigurationInterface $configuration The subject configuration
365
     *
366
     * @return void
367
     */
368 76
    public function setConfiguration(SubjectConfigurationInterface $configuration)
369
    {
370 76
        $this->configuration = $configuration;
371 76
    }
372
373
    /**
374
     * Return's the subject configuration.
375
     *
376
     * @return \TechDivision\Import\Configuration\SubjectConfigurationInterface The subject configuration
377
     */
378 76
    public function getConfiguration()
379
    {
380 76
        return $this->configuration;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $this->configuration; (TechDivision\Import\Conf...tConfigurationInterface) is incompatible with the return type declared by the interface TechDivision\Import\Subj...rface::getConfiguration of type TechDivision\Import\Configuration\SubjectInterface.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
381
    }
382
383
    /**
384
     * Set's the import adapter instance.
385
     *
386
     * @param \TechDivision\Import\Adapter\ImportAdapterInterface $importAdapter The import adapter instance
387
     *
388
     * @return void
389
     */
390 3
    public function setImportAdapter(ImportAdapterInterface $importAdapter)
391
    {
392 3
        $this->importAdapter = $importAdapter;
0 ignored issues
show
Documentation Bug introduced by
It seems like $importAdapter of type object<TechDivision\Impo...ImportAdapterInterface> is incompatible with the declared type object<TechDivision\Impo...apter\AdapterInterface> of property $importAdapter.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
393 3
    }
394
395
    /**
396
     * Return's the import adapter instance.
397
     *
398
     * @return \TechDivision\Import\Adapter\ImportAdapterInterface The import adapter instance
399
     */
400 3
    public function getImportAdapter()
401
    {
402 3
        return $this->importAdapter;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $this->importAdapter; (TechDivision\Import\Adapter\AdapterInterface) is incompatible with the return type declared by the interface TechDivision\Import\Subj...rface::getImportAdapter of type TechDivision\Import\Adapter\ImportAdapterInterface.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
403
    }
404
405
    /**
406
     * Return's the RegistryProcessor instance to handle the running threads.
407
     *
408
     * @return \TechDivision\Import\Services\RegistryProcessorInterface The registry processor instance
409
     */
410 76
    public function getRegistryProcessor()
411
    {
412 76
        return $this->registryProcessor;
413
    }
414
415
    /**
416
     * Set's the unique serial for this import process.
417
     *
418
     * @param string $serial The unique serial
419
     *
420
     * @return void
421
     */
422 8
    public function setSerial($serial)
423
    {
424 8
        $this->serial = $serial;
425 8
    }
426
427
    /**
428
     * Return's the unique serial for this import process.
429
     *
430
     * @return string The unique serial
431
     */
432 3
    public function getSerial()
433
    {
434 3
        return $this->serial;
435
    }
436
437
    /**
438
     * Return's the source date format to use.
439
     *
440
     * @return string The source date format
441
     */
442 4
    public function getSourceDateFormat()
443
    {
444 4
        return $this->getConfiguration()->getSourceDateFormat();
445
    }
446
447
    /**
448
     * Return's the multiple field delimiter character to use, default value is comma (,).
449
     *
450
     * @return string The multiple field delimiter character
451
     */
452 1
    public function getMultipleFieldDelimiter()
453
    {
454 1
        return $this->getConfiguration()->getMultipleFieldDelimiter();
455
    }
456
457
    /**
458
     * Return's the multiple value delimiter character to use, default value is comma (|).
459
     *
460
     * @return string The multiple value delimiter character
461
     */
462 1
    public function getMultipleValueDelimiter()
463
    {
464 1
        return $this->getConfiguration()->getMultipleValueDelimiter();
465
    }
466
467
    /**
468
     * Intializes the previously loaded global data for exactly one bunch.
469
     *
470
     * @param string $serial The serial of the actual import
471
     *
472
     * @return void
473
     * @see \Importer\Csv\Actions\ProductImportAction::prepare()
474
     */
475 76
    public function setUp($serial)
476
    {
477
478
        // load the status of the actual import
479 76
        $status = $this->getRegistryProcessor()->getAttribute($serial);
480
481
        // load the global data we've prepared initially
482 76
        $this->stores = $status[RegistryKeys::GLOBAL_DATA][RegistryKeys::STORES];
483 76
        $this->defaultStore = $status[RegistryKeys::GLOBAL_DATA][RegistryKeys::DEFAULT_STORE];
484 76
        $this->storeWebsites  = $status[RegistryKeys::GLOBAL_DATA][RegistryKeys::STORE_WEBSITES];
485 76
        $this->rootCategories = $status[RegistryKeys::GLOBAL_DATA][RegistryKeys::ROOT_CATEGORIES];
486 76
        $this->coreConfigData = $status[RegistryKeys::GLOBAL_DATA][RegistryKeys::CORE_CONFIG_DATA];
487
488
        // initialize the operation name
489 76
        $this->operationName = $this->getConfiguration()->getConfiguration()->getOperationName();
490
491
        // merge the callback mappings with the mappings from the child instance
492 76
        $this->callbackMappings = array_merge($this->callbackMappings, $this->getDefaultCallbackMappings());
493
494
        // merge the callback mappings the the one from the configuration file
495 76
        foreach ($this->getConfiguration()->getCallbacks() as $callbackMappings) {
496 76
            foreach ($callbackMappings as $attributeCode => $mappings) {
497
                // write a log message, that default callback configuration will
498
                // be overwritten with the one from the configuration file
499 76
                if (isset($this->callbackMappings[$attributeCode])) {
500 71
                    $this->getSystemLogger()->notice(
501 71
                        sprintf('Now override callback mappings for attribute %s with values found in configuration file', $attributeCode)
502
                    );
503
                }
504
505
                // override the attributes callbacks
506 76
                $this->callbackMappings[$attributeCode] = $mappings;
507
            }
508
        }
509 76
    }
510
511
    /**
512
     * Clean up the global data after importing the variants.
513
     *
514
     * @param string $serial The serial of the actual import
515
     *
516
     * @return void
517
     */
518 1
    public function tearDown($serial)
519
    {
520
521
        // load the registry processor
522 1
        $registryProcessor = $this->getRegistryProcessor();
523
524
        // update the source directory for the next subject
525 1
        $registryProcessor->mergeAttributesRecursive(
526 1
            $serial,
527 1
            array(RegistryKeys::SOURCE_DIRECTORY => $newSourceDir = $this->getNewSourceDir($serial))
528
        );
529
530
        // log a debug message with the new source directory
531 1
        $this->getSystemLogger()->info(
532 1
            sprintf('Subject %s successfully updated source directory to %s', get_class($this), $newSourceDir)
533
        );
534 1
    }
535
536
    /**
537
     * Return's the target directory for the artefact export.
538
     *
539
     * @return string The target directory for the artefact export
540
     */
541
    public function getTargetDir()
542
    {
543
        return $this->getNewSourceDir($this->getSerial());
544
    }
545
546
    /**
547
     * Return's the next source directory, which will be the target directory
548
     * of this subject, in most cases.
549
     *
550
     * @param string $serial The serial of the actual import
551
     *
552
     * @return string The new source directory
553
     */
554 3
    public function getNewSourceDir($serial)
555
    {
556 3
        return sprintf('%s/%s', $this->getConfiguration()->getTargetDir(), $serial);
557
    }
558
559
    /**
560
     * Register the passed observer with the specific type.
561
     *
562
     * @param \TechDivision\Import\Observers\ObserverInterface $observer The observer to register
563
     * @param string                                           $type     The type to register the observer with
564
     *
565
     * @return void
566
     */
567 6
    public function registerObserver(ObserverInterface $observer, $type)
568
    {
569
570
        // query whether or not the array with the callbacks for the
571
        // passed type has already been initialized, or not
572 6
        if (!isset($this->observers[$type])) {
573 6
            $this->observers[$type] = array();
574
        }
575
576
        // append the callback with the instance of the passed type
577 6
        $this->observers[$type][] = $observer;
578 6
    }
579
580
    /**
581
     * Register the passed callback with the specific type.
582
     *
583
     * @param \TechDivision\Import\Callbacks\CallbackInterface $callback The subject to register the callbacks for
584
     * @param string                                           $type     The type to register the callback with
585
     *
586
     * @return void
587
     */
588 2
    public function registerCallback(CallbackInterface $callback, $type)
589
    {
590
591
        // query whether or not the array with the callbacks for the
592
        // passed type has already been initialized, or not
593 2
        if (!isset($this->callbacks[$type])) {
594 2
            $this->callbacks[$type] = array();
595
        }
596
597
        // append the callback with the instance of the passed type
598 2
        $this->callbacks[$type][] = $callback;
599 2
    }
600
601
    /**
602
     * Return's the array with callbacks for the passed type.
603
     *
604
     * @param string $type The type of the callbacks to return
605
     *
606
     * @return array The callbacks
607
     */
608 1
    public function getCallbacksByType($type)
609
    {
610
611
        // initialize the array for the callbacks
612 1
        $callbacks = array();
613
614
        // query whether or not callbacks for the type are available
615 1
        if (isset($this->callbacks[$type])) {
616 1
            $callbacks = $this->callbacks[$type];
617
        }
618
619
        // return the array with the type's callbacks
620 1
        return $callbacks;
621
    }
622
623
    /**
624
     * Return's the array with the available observers.
625
     *
626
     * @return array The observers
627
     */
628 6
    public function getObservers()
629
    {
630 6
        return $this->observers;
631
    }
632
633
    /**
634
     * Return's the array with the available callbacks.
635
     *
636
     * @return array The callbacks
637
     */
638 1
    public function getCallbacks()
639
    {
640 1
        return $this->callbacks;
641
    }
642
643
    /**
644
     * Return's the callback mappings for this subject.
645
     *
646
     * @return array The array with the subject's callback mappings
647
     */
648 2
    public function getCallbackMappings()
649
    {
650 2
        return $this->callbackMappings;
651
    }
652
653
    /**
654
     * Imports the content of the file with the passed filename.
655
     *
656
     *
657
     * @param string $serial   The serial of the actual import
658
     * @param string $filename The filename to process
659
     *
660
     * @return void
661
     * @throws \Exception Is thrown, if the import can't be processed
662
     */
663 5
    public function import($serial, $filename)
664
    {
665
666
        try {
667
            // stop processing, if the filename doesn't match
668 5
            if (!$this->match($filename)) {
669 1
                return;
670
            }
671
672
            // load the system logger instance
673 4
            $systemLogger = $this->getSystemLogger();
674
675
            // prepare the flag filenames
676 4
            $inProgressFilename = sprintf('%s.inProgress', $filename);
677 4
            $importedFilename = sprintf('%s.imported', $filename);
678 4
            $failedFilename = sprintf('%s.failed', $filename);
679
680
            // query whether or not the file has already been imported
681 4
            if ($this->isFile($failedFilename) ||
682 3
                $this->isFile($importedFilename) ||
683 4
                $this->isFile($inProgressFilename)
684
            ) {
685
                // log a debug message and exit
686 1
                $systemLogger->debug(sprintf('Import running, found inProgress file %s', $inProgressFilename));
687 1
                return;
688
            }
689
690
            // flag file as in progress
691 3
            $this->touch($inProgressFilename);
692
693
            // track the start time
694 3
            $startTime = microtime(true);
695
696
            // initialize the serial/filename
697 3
            $this->setSerial($serial);
698 3
            $this->setFilename($filename);
699
700
            // log a message that the file has to be imported
701 3
            $systemLogger->debug(sprintf('Now start importing file %s', $filename));
702
703
            // let the adapter process the file
704 3
            $this->getImportAdapter()->import(array($this, 'importRow'), $filename);
705
706
            // track the time needed for the import in seconds
707 1
            $endTime = microtime(true) - $startTime;
708
709
            // log a message that the file has successfully been imported
710 1
            $systemLogger->debug(sprintf('Successfully imported file %s in %f s', $filename, $endTime));
711
712
            // rename flag file, because import has been successfull
713 1
            $this->rename($inProgressFilename, $importedFilename);
714
0 ignored issues
show
Coding Style introduced by
Blank line found at end of control structure
Loading history...
715 2
        } catch (\Exception $e) {
716
            // rename the flag file, because import failed and write the stack trace
717 2
            $this->rename($inProgressFilename, $failedFilename);
0 ignored issues
show
Bug introduced by
The variable $inProgressFilename does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
Bug introduced by
The variable $failedFilename does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
718 2
            $this->write($failedFilename, $e->__toString());
719
720
            // do not wrap the exception if not already done
721 2
            if ($e instanceof WrappedColumnException) {
722 1
                throw $e;
723
            }
724
725
            // else wrap and throw the exception
726 1
            throw $this->wrapException(array(), $e);
727
        }
728 1
    }
729
730
    /**
731
     * This method queries whether or not the passed filename matches
732
     * the pattern, based on the subjects configured prefix.
733
     *
734
     * @param string $filename The filename to match
735
     *
736
     * @return boolean TRUE if the filename matches, else FALSE
737
     */
738 5
    protected function match($filename)
739
    {
740
741
        // prepare the pattern to query whether the file has to be processed or not
742 5
        $pattern = sprintf(
743 5
            '/^.*\/%s.*\\.%s$/',
744 5
            $this->getConfiguration()->getPrefix(),
745 5
            $this->getConfiguration()->getSuffix()
746
        );
747
748
        // stop processing, if the filename doesn't match
749 5
        return (boolean) preg_match($pattern, $filename);
750
    }
751
752
    /**
753
     * Imports the passed row into the database. If the import failed, the exception
754
     * will be catched and logged, but the import process will be continued.
755
     *
756
     * @param array $row The row with the data to be imported
757
     *
758
     * @return void
759
     */
760 7
    public function importRow(array $row)
761
    {
762
763
        // initialize the row
764 7
        $this->row = $row;
765
766
        // raise the line number and reset the skip row flag
767 7
        $this->lineNumber++;
768 7
        $this->skipRow = false;
769
770
        // initialize the headers with the columns from the first line
771 7
        if (sizeof($this->headers) === 0) {
772 1
            foreach ($this->row as $value => $key) {
773 1
                $this->headers[$this->mapAttributeCodeByHeaderMapping($key)] = $value;
774
            }
775 1
            return;
776
        }
777
778
        // process the observers
779 6
        foreach ($this->getObservers() as $observers) {
780
            // invoke the pre-import/import and post-import observers
781 6
            foreach ($observers as $observer) {
782
                // query whether or not we have to skip the row
783 6
                if ($this->skipRow) {
784 1
                    break;
785
                }
786
787
                // if not, set the subject and process the observer
788 6
                if ($observer instanceof ObserverInterface) {
789 6
                    $this->row = $observer->handle($this);
790
                }
791
            }
792
        }
793
794
        // log a debug message with the actual line nr/file information
795 6
        $this->getSystemLogger()->debug(
796 6
            sprintf(
797 6
                'Successfully processed row (operation: %s) in file %s on line %d',
798 6
                $this->operationName,
799 6
                $this->filename,
800 6
                $this->lineNumber
801
            )
802
        );
803 6
    }
804
805
    /**
806
     * Map the passed attribute code, if a header mapping exists and return the
807
     * mapped mapping.
808
     *
809
     * @param string $attributeCode The attribute code to map
810
     *
811
     * @return string The mapped attribute code, or the original one
812
     */
813 2
    public function mapAttributeCodeByHeaderMapping($attributeCode)
814
    {
815
816
        // load the header mappings
817 2
        $headerMappings = $this->getHeaderMappings();
818
819
        // query weather or not we've a mapping, if yes, map the attribute code
820 2
        if (isset($headerMappings[$attributeCode])) {
821 1
            $attributeCode = $headerMappings[$attributeCode];
822
        }
823
824
        // return the (mapped) attribute code
825 2
        return $attributeCode;
826
    }
827
828
    /**
829
     * Queries whether or not that the subject needs an OK file to be processed.
830
     *
831
     * @return boolean TRUE if the subject needs an OK file, else FALSE
832
     */
833 1
    public function isOkFileNeeded()
834
    {
835 1
        return $this->getConfiguration()->isOkFileNeeded();
836
    }
837
838
    /**
839
     * Return's the default store.
840
     *
841
     * @return array The default store
842
     */
843 4
    public function getDefaultStore()
844
    {
845 4
        return $this->defaultStore;
846
    }
847
848
    /**
849
     * Set's the store view code the create the product/attributes for.
850
     *
851
     * @param string $storeViewCode The store view code
852
     *
853
     * @return void
854
     */
855 4
    public function setStoreViewCode($storeViewCode)
856
    {
857 4
        $this->storeViewCode = $storeViewCode;
858 4
    }
859
860
    /**
861
     * Return's the store view code the create the product/attributes for.
862
     *
863
     * @param string|null $default The default value to return, if the store view code has not been set
864
     *
865
     * @return string The store view code
866
     */
867 8
    public function getStoreViewCode($default = null)
868
    {
869
870
        // return the store view code, if available
871 8
        if ($this->storeViewCode != null) {
872 4
            return $this->storeViewCode;
873
        }
874
875
        // if NOT and a default code is available
876 4
        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...
877
            // return the default value
878 3
            return $default;
879
        }
880 1
    }
881
882
    /**
883
     * Return's the store ID of the store with the passed store view code
884
     *
885
     * @param string $storeViewCode The store view code to return the store ID for
886
     *
887
     * @return integer The ID of the store with the passed ID
888
     * @throws \Exception Is thrown, if the store with the actual code is not available
889
     */
890 4
    public function getStoreId($storeViewCode)
891
    {
892
893
        // query whether or not, the requested store is available
894 4
        if (isset($this->stores[$storeViewCode])) {
895 3
            return (integer) $this->stores[$storeViewCode][MemberNames::STORE_ID];
896
        }
897
898
        // throw an exception, if not
899 1
        throw new \Exception(
900 1
            sprintf(
901 1
                'Found invalid store view code %s in file %s on line %d',
902 1
                $storeViewCode,
903 1
                $this->getFilename(),
904 1
                $this->getLineNumber()
905
            )
906
        );
907
    }
908
909
    /**
910
     * Return's the store ID of the actual row, or of the default store
911
     * if no store view code is set in the CSV file.
912
     *
913
     * @param string|null $default The default store view code to use, if no store view code is set in the CSV file
914
     *
915
     * @return integer The ID of the actual store
916
     * @throws \Exception Is thrown, if the store with the actual code is not available
917
     */
918 2
    public function getRowStoreId($default = null)
919
    {
920
921
        // initialize the default store view code, if not passed
922 2
        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...
923 2
            $defaultStore = $this->getDefaultStore();
924 2
            $default = $defaultStore[MemberNames::CODE];
925
        }
926
927
        // load the store view code the create the product/attributes for
928 2
        return $this->getStoreId($this->getStoreViewCode($default));
929
    }
930
931
    /**
932
     * Prepare's the store view code in the subject.
933
     *
934
     * @return void
935
     */
936 2
    public function prepareStoreViewCode()
937
    {
938
939
        // re-set the store view code
940 2
        $this->setStoreViewCode(null);
941
942
        // initialize the store view code
943 2
        if ($storeViewCode = $this->getValue(ColumnKeys::STORE_VIEW_CODE)) {
944 2
            $this->setStoreViewCode($storeViewCode);
945
        }
946 2
    }
947
948
    /**
949
     * Return's the root category for the actual view store.
950
     *
951
     * @return array The store's root category
952
     * @throws \Exception Is thrown if the root category for the passed store code is NOT available
953
     */
954 2
    public function getRootCategory()
955
    {
956
957
        // load the default store
958 2
        $defaultStore = $this->getDefaultStore();
959
960
        // load the actual store view code
961 2
        $storeViewCode = $this->getStoreViewCode($defaultStore[MemberNames::CODE]);
962
963
        // query weather or not we've a root category or not
964 2
        if (isset($this->rootCategories[$storeViewCode])) {
965 1
            return $this->rootCategories[$storeViewCode];
966
        }
967
968
        // throw an exception if the root category is NOT available
969 1
        throw new \Exception(sprintf('Root category for %s is not available', $storeViewCode));
970
    }
971
972
    /**
973
     * Return's the Magento configuration value.
974
     *
975
     * @param string  $path    The Magento path of the requested configuration value
976
     * @param mixed   $default The default value that has to be returned, if the requested configuration value is not set
977
     * @param string  $scope   The scope the configuration value has been set
978
     * @param integer $scopeId The scope ID the configuration value has been set
979
     *
980
     * @return mixed The configuration value
981
     * @throws \Exception Is thrown, if nor a value can be found or a default value has been passed
982
     */
983 5
    public function getCoreConfigData($path, $default = null, $scope = ScopeKeys::SCOPE_DEFAULT, $scopeId = 0)
984
    {
985
986
        // initialize the core config data
987
        $coreConfigData = array(
988 5
            MemberNames::PATH => $path,
989 5
            MemberNames::SCOPE => $scope,
990 5
            MemberNames::SCOPE_ID => $scopeId
991
        );
992
993
        // generate the UID from the passed data
994 5
        $uniqueIdentifier = $this->coreConfigDataUidGenerator->generate($coreConfigData);
995
996
        // iterate over the core config data and try to find the requested configuration value
997 5
        if (isset($this->coreConfigData[$uniqueIdentifier])) {
998 1
            return $this->coreConfigData[$uniqueIdentifier][MemberNames::VALUE];
999
        }
1000
1001
        // query whether or not we've to query for the configuration value on fallback level 'websites' also
1002 4
        if ($scope === ScopeKeys::SCOPE_STORES) {
1003
            // query whether or not the website with the passed ID is available
1004 2
            foreach ($this->storeWebsites as $storeWebsite) {
1005 2
                if ($storeWebsite[MemberNames::WEBSITE_ID] === $scopeId) {
1006
                    // replace scope with 'websites' and website ID
1007 2
                    $coreConfigData = array_merge(
1008 2
                        $coreConfigData,
1009
                        array(
1010 2
                            MemberNames::SCOPE    => ScopeKeys::SCOPE_WEBSITES,
1011 2
                            MemberNames::SCOPE_ID => $storeWebsite[MemberNames::WEBSITE_ID]
1012
                        )
1013
                    );
1014
1015
                    // generate the UID from the passed data, merged with the 'websites' scope and ID
1016 2
                    $uniqueIdentifier = $this->coreConfigDataUidGenerator->generate($coreConfigData);
1017
1018
                    // query whether or not, the configuration value on 'websites' level
1019 2 View Code Duplication
                    if (isset($this->coreConfigData[$uniqueIdentifier][MemberNames::VALUE])) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
1020 2
                        return $this->coreConfigData[$uniqueIdentifier][MemberNames::VALUE];
1021
                    }
1022
                }
1023
            }
1024
        }
1025
1026
        // replace scope with 'default' and scope ID '0'
1027 3
        $coreConfigData = array_merge(
1028 3
            $coreConfigData,
1029
            array(
1030 3
                MemberNames::SCOPE    => ScopeKeys::SCOPE_DEFAULT,
1031 3
                MemberNames::SCOPE_ID => 0
1032
            )
1033
        );
1034
1035
        // generate the UID from the passed data, merged with the 'default' scope and ID 0
1036 3
        $uniqueIdentifier = $this->coreConfigDataUidGenerator->generate($coreConfigData);
1037
1038
        // query whether or not, the configuration value on 'default' level
1039 3 View Code Duplication
        if (isset($this->coreConfigData[$uniqueIdentifier][MemberNames::VALUE])) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
1040 1
            return $this->coreConfigData[$uniqueIdentifier][MemberNames::VALUE];
1041
        }
1042
1043
        // if not, return the passed default value
1044 2
        if ($default !== null) {
1045 1
            return $default;
1046
        }
1047
1048
        // throw an exception if no value can be found
1049
        // in the Magento configuration
1050 1
        throw new \Exception(
1051 1
            sprintf(
1052 1
                'Can\'t find a value for configuration "%s-%s-%d" in "core_config_data"',
1053 1
                $path,
1054 1
                $scope,
1055 1
                $scopeId
1056
            )
1057
        );
1058
    }
1059
1060
    /**
1061
     * Resolve the original column name for the passed one.
1062
     *
1063
     * @param string $columnName The column name that has to be resolved
1064
     *
1065
     * @return string|null The original column name
1066
     */
1067 2
    public function resolveOriginalColumnName($columnName)
1068
    {
1069
1070
        // try to load the original data
1071 2
        $originalData = $this->getOriginalData();
1072
1073
        // query whether or not original data is available
1074 2
        if (isset($originalData[ColumnKeys::ORIGINAL_COLUMN_NAMES])) {
1075
            // query whether or not the original column name is available
1076 1
            if (isset($originalData[ColumnKeys::ORIGINAL_COLUMN_NAMES][$columnName])) {
1077 1
                return $originalData[ColumnKeys::ORIGINAL_COLUMN_NAMES][$columnName];
1078
            }
1079
1080
            // query whether or a wildcard column name is available
1081 1
            if (isset($originalData[ColumnKeys::ORIGINAL_COLUMN_NAMES]['*'])) {
1082 1
                return $originalData[ColumnKeys::ORIGINAL_COLUMN_NAMES]['*'];
1083
            }
1084
        }
1085
1086
        // return the original column name
1087 1
        return $columnName;
1088
    }
1089
1090
    /**
1091
     * Return's the original data if available, or an empty array.
1092
     *
1093
     * @return array The original data
1094
     */
1095 2
    public function getOriginalData()
1096
    {
1097
1098
        // initialize the array for the original data
1099 2
        $originalData = array();
1100
1101
        // query whether or not the column contains original data
1102 2
        if ($this->hasOriginalData()) {
1103
            // unerialize the original data from the column
1104 1
            $originalData = unserialize($this->row[$this->headers[ColumnKeys::ORIGINAL_DATA]]);
1105
        }
1106
1107
        // return an empty array, if not
1108 2
        return $originalData;
1109
    }
1110
1111
    /**
1112
     * Query's whether or not the actual column contains original data like
1113
     * filename, line number and column names.
1114
     *
1115
     * @return boolean TRUE if the actual column contains origin data, else FALSE
1116
     */
1117 3
    public function hasOriginalData()
1118
    {
1119 3
        return isset($this->headers[ColumnKeys::ORIGINAL_DATA]) && isset($this->row[$this->headers[ColumnKeys::ORIGINAL_DATA]]);
1120
    }
1121
1122
    /**
1123
     * Wraps the passed exeception into a new one by trying to resolve the original filname,
1124
     * line number and column names and use it for a detailed exception message.
1125
     *
1126
     * @param array      $columnNames The column names that should be resolved and wrapped
1127
     * @param \Exception $parent      The exception we want to wrap
1128
     * @param string     $className   The class name of the exception type we want to wrap the parent one
1129
     *
1130
     * @return \Exception the wrapped exception
1131
     */
1132 2
    public function wrapException(
1133
        array $columnNames = array(),
1134
        \Exception $parent = null,
1135
        $className = '\TechDivision\Import\Exceptions\WrappedColumnException'
1136
    ) {
1137
1138
        // initialize the message
1139 2
        $message = $parent->getMessage();
0 ignored issues
show
Bug introduced by
It seems like $parent is not always an object, but can also be of type null. Maybe add an additional type check?

If a variable is not always an object, we recommend to add an additional type check to ensure your method call is safe:

function someFunction(A $objectMaybe = null)
{
    if ($objectMaybe instanceof A) {
        $objectMaybe->doSomething();
    }
}
Loading history...
1140
1141
        // query whether or not has been a result of invalid data of a previous column of a CSV file
1142 2
        if ($this->hasOriginalData()) {
1143
            // load the original data
1144 1
            $originalData = $this->getOriginalData();
1145
1146
            // replace old filename and line number of the original message
1147 1
            $message = $this->appendExceptionSuffix(
1148 1
                $this->stripExceptionSuffix($message),
1149 1
                $originalData[ColumnKeys::ORIGINAL_FILENAME],
1150 1
                $originalData[ColumnKeys::ORIGINAL_LINE_NUMBER]
1151
            );
1152
0 ignored issues
show
Coding Style introduced by
Blank line found at end of control structure
Loading history...
1153
        } else {
1154
            // append filename and line number to the original message
1155 1
            $message = $this->appendExceptionSuffix(
1156 1
                $this->stripExceptionSuffix($message),
1157 1
                $this->filename,
1158 1
                $this->lineNumber
1159
            );
1160
        }
1161
1162
        // query whether or not, column names has been passed
1163 2
        if (sizeof($columnNames) > 0) {
1164
            // prepare the original column names
1165 1
            $originalColumnNames = array();
1166 1
            foreach ($columnNames as $columnName) {
1167 1
                $originalColumnNames[] = $this->resolveOriginalColumnName($columnName);
1168
            }
1169
1170
            // append the column information
1171 1
            $message = sprintf('%s in column(s) %s', $message, implode(', ', $originalColumnNames));
1172
        }
1173
1174
        // create a new exception and wrap the parent one
1175 2
        return new $className($message, null, $parent);
1176
    }
1177
1178
    /**
1179
     * Strip's the exception suffix containing filename and line number from the
1180
     * passed message.
1181
     *
1182
     * @param string $message The message to strip the exception suffix from
1183
     *
1184
     * @return mixed The message without the exception suffix
1185
     */
1186 2
    public function stripExceptionSuffix($message)
1187
    {
1188 2
        return str_replace($this->appendExceptionSuffix(), '', $message);
1189
    }
1190
1191
    /**
1192
     * Append's the exception suffix containing filename and line number to the
1193
     * passed message. If no message has been passed, only the suffix will be
1194
     * returned
1195
     *
1196
     * @param string|null $message    The message to append the exception suffix to
1197
     * @param string|null $filename   The filename used to create the suffix
1198
     * @param string|null $lineNumber The line number used to create the suffx
1199
     *
1200
     * @return string The message with the appended exception suffix
1201
     */
1202 7
    public function appendExceptionSuffix($message = null, $filename = null, $lineNumber = null)
1203
    {
1204
1205
        // query whether or not a filename has been passed
1206 7
        if ($filename === null) {
1207 7
            $filename = $this->getFilename();
1208
        }
1209
1210
        // query whether or not a line number has been passed
1211 7
        if ($lineNumber === null) {
1212 7
            $lineNumber = $this->getLineNumber();
1213
        }
1214
1215
        // if no message has been passed, only return the suffix
1216 7
        if ($message === null) {
1217 2
            return sprintf(' in file %s on line %d', $filename, $lineNumber);
1218
        }
1219
1220
        // concatenate the message with the suffix and return it
1221 7
        return sprintf('%s in file %s on line %d', $message, $filename, $lineNumber);
1222
    }
1223
1224
    /**
1225
     * Raises the value for the counter with the passed key by one.
1226
     *
1227
     * @param mixed $counterName The name of the counter to raise
1228
     *
1229
     * @return integer The counter's new value
1230
     */
1231 1
    public function raiseCounter($counterName)
1232
    {
1233
1234
        // raise the counter with the passed name
1235 1
        return $this->getRegistryProcessor()->raiseCounter(
1236 1
            $this->getSerial(),
1237 1
            $counterName
1238
        );
1239
    }
1240
1241
    /**
1242
     * Merge the passed array into the status of the actual import.
1243
     *
1244
     * @param array $status The status information to be merged
1245
     *
1246
     * @return void
1247
     */
1248 1
    public function mergeAttributesRecursive(array $status)
1249
    {
1250
1251
        // merge the passed status
1252 1
        $this->getRegistryProcessor()->mergeAttributesRecursive(
1253 1
            $this->getSerial(),
1254 1
            $status
1255
        );
1256 1
    }
1257
}
1258