Completed
Push — master ( c0b944...674048 )
by Tim
13s
created

AbstractSubject::tearDown()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 20
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 1.037

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 20
ccs 6
cts 9
cp 0.6667
rs 9.4285
cc 1
eloc 9
nc 1
nop 1
crap 1.037
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 Doctrine\Common\Collections\Collection;
24
use TechDivision\Import\RowTrait;
25
use TechDivision\Import\HeaderTrait;
26
use TechDivision\Import\SystemLoggerTrait;
27
use TechDivision\Import\Utils\ScopeKeys;
28
use TechDivision\Import\Utils\ColumnKeys;
29
use TechDivision\Import\Utils\MemberNames;
30
use TechDivision\Import\Utils\RegistryKeys;
31
use TechDivision\Import\Utils\Generators\GeneratorInterface;
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\ImportAdapterInterface
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 \Doctrine\Common\Collections\Collection                  $systemLoggers              The array with the system loggers instances
211
     */
212 77
    public function __construct(
213
        RegistryProcessorInterface $registryProcessor,
214
        GeneratorInterface $coreConfigDataUidGenerator,
215
        Collection $systemLoggers
216
    ) {
217 77
        $this->systemLoggers = $systemLoggers;
0 ignored issues
show
Documentation Bug introduced by
It seems like $systemLoggers of type object<Doctrine\Common\Collections\Collection> is incompatible with the declared type array of property $systemLoggers.

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...
218 77
        $this->registryProcessor = $registryProcessor;
219 77
        $this->coreConfigDataUidGenerator = $coreConfigDataUidGenerator;
220 77
    }
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 13
    public function setFilename($filename)
230
    {
231 13
        $this->filename = $filename;
232 13
    }
233
234
    /**
235
     * Return's the name of the file to import.
236
     *
237
     * @return string The filename
238
     */
239 13
    public function getFilename()
240
    {
241 13
        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 13
    public function getLineNumber()
284
    {
285 13
        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 77
    public function setConfiguration(SubjectConfigurationInterface $configuration)
369
    {
370 77
        $this->configuration = $configuration;
371 77
    }
372
373
    /**
374
     * Return's the subject configuration.
375
     *
376
     * @return \TechDivision\Import\Configuration\SubjectConfigurationInterface The subject configuration
377
     */
378 77
    public function getConfiguration()
379
    {
380 77
        return $this->configuration;
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;
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;
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 77
    public function getRegistryProcessor()
411
    {
412 77
        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 9
    public function setSerial($serial)
423
    {
424 9
        $this->serial = $serial;
425 9
    }
426
427
    /**
428
     * Return's the unique serial for this import process.
429
     *
430
     * @return string The unique serial
431
     */
432 4
    public function getSerial()
433
    {
434 4
        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
     */
474 77
    public function setUp($serial)
475
    {
476
477
        // load the status of the actual import
478 77
        $status = $this->getRegistryProcessor()->getAttribute($serial);
479
480
        // load the global data we've prepared initially
481 77
        $this->stores = $status[RegistryKeys::GLOBAL_DATA][RegistryKeys::STORES];
482 77
        $this->defaultStore = $status[RegistryKeys::GLOBAL_DATA][RegistryKeys::DEFAULT_STORE];
483 77
        $this->storeWebsites  = $status[RegistryKeys::GLOBAL_DATA][RegistryKeys::STORE_WEBSITES];
484 77
        $this->rootCategories = $status[RegistryKeys::GLOBAL_DATA][RegistryKeys::ROOT_CATEGORIES];
485 77
        $this->coreConfigData = $status[RegistryKeys::GLOBAL_DATA][RegistryKeys::CORE_CONFIG_DATA];
486
487
        // initialize the operation name
488 77
        $this->operationName = $this->getConfiguration()->getConfiguration()->getOperationName();
489
490
        // merge the callback mappings with the mappings from the child instance
491 77
        $this->callbackMappings = array_merge($this->callbackMappings, $this->getDefaultCallbackMappings());
492
493
        // merge the header mappings with the values found in the configuration
494 77
        $this->headerMappings = array_merge($this->headerMappings, $this->getConfiguration()->getHeaderMappings());
495
496
        // merge the callback mappings the the one from the configuration file
497 77
        foreach ($this->getConfiguration()->getCallbacks() as $callbackMappings) {
498 77
            foreach ($callbackMappings as $attributeCode => $mappings) {
499
                // write a log message, that default callback configuration will
500
                // be overwritten with the one from the configuration file
501 77
                if (isset($this->callbackMappings[$attributeCode])) {
502 72
                    $this->getSystemLogger()->notice(
503 72
                        sprintf('Now override callback mappings for attribute %s with values found in configuration file', $attributeCode)
504
                    );
505
                }
506
507
                // override the attributes callbacks
508 77
                $this->callbackMappings[$attributeCode] = $mappings;
509
            }
510
        }
511 77
    }
512
513
    /**
514
     * Clean up the global data after importing the variants.
515
     *
516
     * @param string $serial The serial of the actual import
517
     *
518
     * @return void
519
     */
520 1
    public function tearDown($serial)
521
    {
522
523
        // load the registry processor
524 1
        $registryProcessor = $this->getRegistryProcessor();
525
526
        // update the source directory for the next subject
527 1
        $registryProcessor->mergeAttributesRecursive(
528 1
            $serial,
529
            array(
530 1
                RegistryKeys::SOURCE_DIRECTORY => $newSourceDir = $this->getNewSourceDir($serial),
531 1
                RegistryKeys::FILES => array($this->getFilename() => array(RegistryKeys::STATUS => 1))
532
            )
533
        );
534
535
        // log a debug message with the new source directory
536
        $this->getSystemLogger()->debug(
537
            sprintf('Subject %s successfully updated source directory to %s', get_class($this), $newSourceDir)
538
        );
539
    }
540
541
    /**
542
     * Return's the target directory for the artefact export.
543
     *
544
     * @return string The target directory for the artefact export
545
     */
546 1
    public function getTargetDir()
547
    {
548 1
        return $this->getNewSourceDir($this->getSerial());
549
    }
550
551
    /**
552
     * Return's the next source directory, which will be the target directory
553
     * of this subject, in most cases.
554
     *
555
     * @param string $serial The serial of the actual import
556
     *
557
     * @return string The new source directory
558
     */
559 4
    public function getNewSourceDir($serial)
560
    {
561 4
        return sprintf('%s/%s', $this->getConfiguration()->getTargetDir(), $serial);
562
    }
563
564
    /**
565
     * Register the passed observer with the specific type.
566
     *
567
     * @param \TechDivision\Import\Observers\ObserverInterface $observer The observer to register
568
     * @param string                                           $type     The type to register the observer with
569
     *
570
     * @return void
571
     */
572 6
    public function registerObserver(ObserverInterface $observer, $type)
573
    {
574
575
        // query whether or not the array with the callbacks for the
576
        // passed type has already been initialized, or not
577 6
        if (!isset($this->observers[$type])) {
578 6
            $this->observers[$type] = array();
579
        }
580
581
        // append the callback with the instance of the passed type
582 6
        $this->observers[$type][] = $observer;
583 6
    }
584
585
    /**
586
     * Register the passed callback with the specific type.
587
     *
588
     * @param \TechDivision\Import\Callbacks\CallbackInterface $callback The subject to register the callbacks for
589
     * @param string                                           $type     The type to register the callback with
590
     *
591
     * @return void
592
     */
593 2
    public function registerCallback(CallbackInterface $callback, $type)
594
    {
595
596
        // query whether or not the array with the callbacks for the
597
        // passed type has already been initialized, or not
598 2
        if (!isset($this->callbacks[$type])) {
599 2
            $this->callbacks[$type] = array();
600
        }
601
602
        // append the callback with the instance of the passed type
603 2
        $this->callbacks[$type][] = $callback;
604 2
    }
605
606
    /**
607
     * Return's the array with callbacks for the passed type.
608
     *
609
     * @param string $type The type of the callbacks to return
610
     *
611
     * @return array The callbacks
612
     */
613 1
    public function getCallbacksByType($type)
614
    {
615
616
        // initialize the array for the callbacks
617 1
        $callbacks = array();
618
619
        // query whether or not callbacks for the type are available
620 1
        if (isset($this->callbacks[$type])) {
621 1
            $callbacks = $this->callbacks[$type];
622
        }
623
624
        // return the array with the type's callbacks
625 1
        return $callbacks;
626
    }
627
628
    /**
629
     * Return's the array with the available observers.
630
     *
631
     * @return array The observers
632
     */
633 6
    public function getObservers()
634
    {
635 6
        return $this->observers;
636
    }
637
638
    /**
639
     * Return's the array with the available callbacks.
640
     *
641
     * @return array The callbacks
642
     */
643 1
    public function getCallbacks()
644
    {
645 1
        return $this->callbacks;
646
    }
647
648
    /**
649
     * Return's the callback mappings for this subject.
650
     *
651
     * @return array The array with the subject's callback mappings
652
     */
653 2
    public function getCallbackMappings()
654
    {
655 2
        return $this->callbackMappings;
656
    }
657
658
    /**
659
     * Imports the content of the file with the passed filename.
660
     *
661
     *
662
     * @param string $serial   The serial of the actual import
663
     * @param string $filename The filename to process
664
     *
665
     * @return void
666
     * @throws \Exception Is thrown, if the import can't be processed
667
     */
668 5
    public function import($serial, $filename)
669
    {
670
671
        try {
672
            // stop processing, if the filename doesn't match
673 5
            if (!$this->match($filename)) {
674 1
                return;
675
            }
676
677
            // load the system logger instance
678 4
            $systemLogger = $this->getSystemLogger();
679
680
            // prepare the flag filenames
681 4
            $inProgressFilename = sprintf('%s.inProgress', $filename);
682 4
            $importedFilename = sprintf('%s.imported', $filename);
683 4
            $failedFilename = sprintf('%s.failed', $filename);
684
685
            // query whether or not the file has already been imported
686 4
            if ($this->isFile($failedFilename) ||
687 3
                $this->isFile($importedFilename) ||
688 4
                $this->isFile($inProgressFilename)
689
            ) {
690
                // log a debug message and exit
691 1
                $systemLogger->debug(sprintf('Import running, found inProgress file %s', $inProgressFilename));
692 1
                return;
693
            }
694
695
            // flag file as in progress
696 3
            $this->touch($inProgressFilename);
697
698
            // track the start time
699 3
            $startTime = microtime(true);
700
701
            // initialize the serial/filename
702 3
            $this->setSerial($serial);
703 3
            $this->setFilename($filename);
704
705
            // log a message that the file has to be imported
706 3
            $systemLogger->info(sprintf('Now start processing file %s', $filename));
707
708
            // let the adapter process the file
709 3
            $this->getImportAdapter()->import(array($this, 'importRow'), $filename);
710
711
            // track the time needed for the import in seconds
712 1
            $endTime = microtime(true) - $startTime;
713
714
            // log a message that the file has successfully been imported
715 1
            $systemLogger->info(sprintf('Successfully processed file %s with %d lines in %f s', $filename, $this->lineNumber, $endTime));
716
717
            // rename flag file, because import has been successfull
718 1
            $this->rename($inProgressFilename, $importedFilename);
719
0 ignored issues
show
Coding Style introduced by
Blank line found at end of control structure
Loading history...
720 2
        } catch (\Exception $e) {
721
            // rename the flag file, because import failed and write the stack trace
722 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...
723 2
            $this->write($failedFilename, $e->__toString());
724
725
            // do not wrap the exception if not already done
726 2
            if ($e instanceof WrappedColumnException) {
727 1
                throw $e;
728
            }
729
730
            // else wrap and throw the exception
731 1
            throw $this->wrapException(array(), $e);
732
        }
733 1
    }
734
735
    /**
736
     * This method queries whether or not the passed filename matches
737
     * the pattern, based on the subjects configured prefix.
738
     *
739
     * @param string $filename The filename to match
740
     *
741
     * @return boolean TRUE if the filename matches, else FALSE
742
     */
743 5
    protected function match($filename)
744
    {
745
746
        // prepare the pattern to query whether the file has to be processed or not
747 5
        $pattern = sprintf(
748 5
            '/^.*\/%s.*\\.%s$/',
749 5
            $this->getConfiguration()->getPrefix(),
750 5
            $this->getConfiguration()->getSuffix()
751
        );
752
753
        // stop processing, if the filename doesn't match
754 5
        return (boolean) preg_match($pattern, $filename);
755
    }
756
757
    /**
758
     * Imports the passed row into the database. If the import failed, the exception
759
     * will be catched and logged, but the import process will be continued.
760
     *
761
     * @param array $row The row with the data to be imported
762
     *
763
     * @return void
764
     */
765 7
    public function importRow(array $row)
766
    {
767
768
        // initialize the row
769 7
        $this->row = $row;
770
771
        // raise the line number and reset the skip row flag
772 7
        $this->lineNumber++;
773 7
        $this->skipRow = false;
774
775
        // initialize the headers with the columns from the first line
776 7
        if (sizeof($this->headers) === 0) {
777 1
            foreach ($this->row as $value => $key) {
778 1
                $this->headers[$this->mapAttributeCodeByHeaderMapping($key)] = $value;
779
            }
780 1
            return;
781
        }
782
783
        // process the observers
784 6
        foreach ($this->getObservers() as $observers) {
785
            // invoke the pre-import/import and post-import observers
786 6
            foreach ($observers as $observer) {
787
                // query whether or not we have to skip the row
788 6
                if ($this->skipRow) {
789
                    // log a debug message with the actual line nr/file information
790 1
                    $this->getSystemLogger()->warning(
791 1
                        $this->appendExceptionSuffix(
792 1
                            sprintf(
793 1
                                'Skip processing operation "%s" after observer "%s"',
794 1
                                $this->operationName,
795 1
                                $this->getConfiguration()->getId()
796
                            )
797
                        )
798
                    );
799
800
                    // skip the row
801 1
                    break 2;
802
                }
803
804
                // if not, set the subject and process the observer
805 6
                if ($observer instanceof ObserverInterface) {
806 6
                    $this->row = $observer->handle($this);
807
                }
808
            }
809
        }
810
811
        // log a debug message with the actual line nr/file information
812 6
        $this->getSystemLogger()->debug(
813 6
            $this->appendExceptionSuffix(
814 6
                sprintf(
815 6
                    'Successfully processed operation "%s"',
816 6
                    $this->operationName
817
                )
818
            )
819
        );
820 6
    }
821
822
    /**
823
     * Queries whether or not that the subject needs an OK file to be processed.
824
     *
825
     * @return boolean TRUE if the subject needs an OK file, else FALSE
826
     */
827 1
    public function isOkFileNeeded()
828
    {
829 1
        return $this->getConfiguration()->isOkFileNeeded();
830
    }
831
832
    /**
833
     * Return's the default store.
834
     *
835
     * @return array The default store
836
     */
837
    public function getDefaultStore()
838
    {
839
        return $this->defaultStore;
840
    }
841
842
    /**
843
     * Return's the default store view code.
844
     *
845
     * @return array The default store view code
846
     */
847 5
    public function getDefaultStoreViewCode()
848
    {
849 5
        return $this->defaultStore[MemberNames::CODE];
850
    }
851
852
    /**
853
     * Set's the store view code the create the product/attributes for.
854
     *
855
     * @param string $storeViewCode The store view code
856
     *
857
     * @return void
858
     */
859 4
    public function setStoreViewCode($storeViewCode)
860
    {
861 4
        $this->storeViewCode = $storeViewCode;
862 4
    }
863
864
    /**
865
     * Return's the store view code the create the product/attributes for.
866
     *
867
     * @param string|null $default The default value to return, if the store view code has not been set
868
     *
869
     * @return string The store view code
870
     */
871 8
    public function getStoreViewCode($default = null)
872
    {
873
874
        // return the store view code, if available
875 8
        if ($this->storeViewCode !== null) {
876 4
            return $this->storeViewCode;
877
        }
878
879
        // if NOT and a default code is available
880 4
        if ($default !== null) {
881
            // return the default value
882 3
            return $default;
883
        }
884
885
        // return the default store view code
886 1
        return $this->getDefaultStoreViewCode();
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $this->getDefaultStoreViewCode(); (array) is incompatible with the return type declared by the interface TechDivision\Import\Subj...rface::getStoreViewCode of type string.

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...
887
    }
888
889
    /**
890
     * Prepare's the store view code in the subject. If the store_view_code row doesn't contain
891
     * any value, the default code of the default store view will be set.
892
     *
893
     * @return void
894
     */
895 2
    public function prepareStoreViewCode()
896
    {
897
898
        // re-set the store view code
899 2
        $this->setStoreViewCode(null);
900
901
        // initialize the store view code
902 2
        if ($storeViewCode = $this->getValue(ColumnKeys::STORE_VIEW_CODE)) {
903 2
            $this->setStoreViewCode($storeViewCode);
904
        }
905 2
    }
906
907
    /**
908
     * Return's the store ID of the store with the passed store view code
909
     *
910
     * @param string $storeViewCode The store view code to return the store ID for
911
     *
912
     * @return integer The ID of the store with the passed ID
913
     * @throws \Exception Is thrown, if the store with the actual code is not available
914
     */
915 4
    public function getStoreId($storeViewCode)
916
    {
917
918
        // query whether or not, the requested store is available
919 4
        if (isset($this->stores[$storeViewCode])) {
920 3
            return (integer) $this->stores[$storeViewCode][MemberNames::STORE_ID];
921
        }
922
923
        // throw an exception, if not
924 1
        throw new \Exception(
925 1
            sprintf(
926 1
                'Found invalid store view code %s in file %s on line %d',
927 1
                $storeViewCode,
928 1
                $this->getFilename(),
929 1
                $this->getLineNumber()
930
            )
931
        );
932
    }
933
934
    /**
935
     * Return's the store ID of the actual row, or of the default store
936
     * if no store view code is set in the CSV file.
937
     *
938
     * @param string|null $default The default store view code to use, if no store view code is set in the CSV file
939
     *
940
     * @return integer The ID of the actual store
941
     * @throws \Exception Is thrown, if the store with the actual code is not available
942
     */
943 2
    public function getRowStoreId($default = null)
944
    {
945
946
        // initialize the default store view code, if not passed
947 2
        if ($default === null) {
948 2
            $default = $this->getDefaultStoreViewCode();
949
        }
950
951
        // load the store view code the create the product/attributes for
952 2
        return $this->getStoreId($this->getStoreViewCode($default));
0 ignored issues
show
Bug introduced by
It seems like $default defined by $this->getDefaultStoreViewCode() on line 948 can also be of type array; however, TechDivision\Import\Subj...ect::getStoreViewCode() does only seem to accept string|null, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
Bug introduced by
It seems like $this->getStoreViewCode($default) targeting TechDivision\Import\Subj...ect::getStoreViewCode() can also be of type array; however, TechDivision\Import\Subj...ctSubject::getStoreId() does only seem to accept string, maybe add an additional type check?

This check looks at variables that are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
953
    }
954
955
    /**
956
     * Return's the root category for the actual view store.
957
     *
958
     * @return array The store's root category
959
     * @throws \Exception Is thrown if the root category for the passed store code is NOT available
960
     */
961 2
    public function getRootCategory()
962
    {
963
964
        // load the actual store view code
965 2
        $storeViewCode = $this->getStoreViewCode($this->getDefaultStoreViewCode());
0 ignored issues
show
Documentation introduced by
$this->getDefaultStoreViewCode() is of type array, but the function expects a string|null.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
966
967
        // query weather or not we've a root category or not
968 2
        if (isset($this->rootCategories[$storeViewCode])) {
969 1
            return $this->rootCategories[$storeViewCode];
970
        }
971
972
        // throw an exception if the root category is NOT available
973 1
        throw new \Exception(sprintf('Root category for %s is not available', $storeViewCode));
974
    }
975
976
    /**
977
     * Return's the Magento configuration value.
978
     *
979
     * @param string  $path    The Magento path of the requested configuration value
980
     * @param mixed   $default The default value that has to be returned, if the requested configuration value is not set
981
     * @param string  $scope   The scope the configuration value has been set
982
     * @param integer $scopeId The scope ID the configuration value has been set
983
     *
984
     * @return mixed The configuration value
985
     * @throws \Exception Is thrown, if nor a value can be found or a default value has been passed
986
     */
987 5
    public function getCoreConfigData($path, $default = null, $scope = ScopeKeys::SCOPE_DEFAULT, $scopeId = 0)
988
    {
989
990
        // initialize the core config data
991
        $coreConfigData = array(
992 5
            MemberNames::PATH => $path,
993 5
            MemberNames::SCOPE => $scope,
994 5
            MemberNames::SCOPE_ID => $scopeId
995
        );
996
997
        // generate the UID from the passed data
998 5
        $uniqueIdentifier = $this->coreConfigDataUidGenerator->generate($coreConfigData);
999
1000
        // iterate over the core config data and try to find the requested configuration value
1001 5
        if (isset($this->coreConfigData[$uniqueIdentifier])) {
1002 1
            return $this->coreConfigData[$uniqueIdentifier][MemberNames::VALUE];
1003
        }
1004
1005
        // query whether or not we've to query for the configuration value on fallback level 'websites' also
1006 4
        if ($scope === ScopeKeys::SCOPE_STORES) {
1007
            // query whether or not the website with the passed ID is available
1008 2
            foreach ($this->storeWebsites as $storeWebsite) {
1009 2
                if ($storeWebsite[MemberNames::WEBSITE_ID] === $scopeId) {
1010
                    // replace scope with 'websites' and website ID
1011 2
                    $coreConfigData = array_merge(
1012 2
                        $coreConfigData,
1013
                        array(
1014 2
                            MemberNames::SCOPE    => ScopeKeys::SCOPE_WEBSITES,
1015
                            MemberNames::SCOPE_ID => $storeWebsite[MemberNames::WEBSITE_ID]
1016
                        )
1017
                    );
1018
1019
                    // generate the UID from the passed data, merged with the 'websites' scope and ID
1020 2
                    $uniqueIdentifier = $this->coreConfigDataUidGenerator->generate($coreConfigData);
1021
1022
                    // query whether or not, the configuration value on 'websites' level
1023 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...
1024 2
                        return $this->coreConfigData[$uniqueIdentifier][MemberNames::VALUE];
1025
                    }
1026
                }
1027
            }
1028
        }
1029
1030
        // replace scope with 'default' and scope ID '0'
1031 3
        $coreConfigData = array_merge(
1032 3
            $coreConfigData,
1033
            array(
1034 3
                MemberNames::SCOPE    => ScopeKeys::SCOPE_DEFAULT,
1035
                MemberNames::SCOPE_ID => 0
1036
            )
1037
        );
1038
1039
        // generate the UID from the passed data, merged with the 'default' scope and ID 0
1040 3
        $uniqueIdentifier = $this->coreConfigDataUidGenerator->generate($coreConfigData);
1041
1042
        // query whether or not, the configuration value on 'default' level
1043 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...
1044 1
            return $this->coreConfigData[$uniqueIdentifier][MemberNames::VALUE];
1045
        }
1046
1047
        // if not, return the passed default value
1048 2
        if ($default !== null) {
1049 1
            return $default;
1050
        }
1051
1052
        // throw an exception if no value can be found
1053
        // in the Magento configuration
1054 1
        throw new \Exception(
1055 1
            sprintf(
1056 1
                'Can\'t find a value for configuration "%s-%s-%d" in "core_config_data"',
1057 1
                $path,
1058 1
                $scope,
1059 1
                $scopeId
1060
            )
1061
        );
1062
    }
1063
1064
    /**
1065
     * Resolve the original column name for the passed one.
1066
     *
1067
     * @param string $columnName The column name that has to be resolved
1068
     *
1069
     * @return string|null The original column name
1070
     */
1071 2
    public function resolveOriginalColumnName($columnName)
1072
    {
1073
1074
        // try to load the original data
1075 2
        $originalData = $this->getOriginalData();
1076
1077
        // query whether or not original data is available
1078 2
        if (isset($originalData[ColumnKeys::ORIGINAL_COLUMN_NAMES])) {
1079
            // query whether or not the original column name is available
1080 1
            if (isset($originalData[ColumnKeys::ORIGINAL_COLUMN_NAMES][$columnName])) {
1081 1
                return $originalData[ColumnKeys::ORIGINAL_COLUMN_NAMES][$columnName];
1082
            }
1083
1084
            // query whether or a wildcard column name is available
1085 1
            if (isset($originalData[ColumnKeys::ORIGINAL_COLUMN_NAMES]['*'])) {
1086 1
                return $originalData[ColumnKeys::ORIGINAL_COLUMN_NAMES]['*'];
1087
            }
1088
        }
1089
1090
        // return the original column name
1091 1
        return $columnName;
1092
    }
1093
1094
    /**
1095
     * Return's the original data if available, or an empty array.
1096
     *
1097
     * @return array The original data
1098
     */
1099 2
    public function getOriginalData()
1100
    {
1101
1102
        // initialize the array for the original data
1103 2
        $originalData = array();
1104
1105
        // query whether or not the column contains original data
1106 2
        if ($this->hasOriginalData()) {
1107
            // unerialize the original data from the column
1108 1
            $originalData = unserialize($this->row[$this->headers[ColumnKeys::ORIGINAL_DATA]]);
1109
        }
1110
1111
        // return an empty array, if not
1112 2
        return $originalData;
1113
    }
1114
1115
    /**
1116
     * Query's whether or not the actual column contains original data like
1117
     * filename, line number and column names.
1118
     *
1119
     * @return boolean TRUE if the actual column contains origin data, else FALSE
1120
     */
1121 3
    public function hasOriginalData()
1122
    {
1123 3
        return isset($this->headers[ColumnKeys::ORIGINAL_DATA]) && isset($this->row[$this->headers[ColumnKeys::ORIGINAL_DATA]]);
1124
    }
1125
1126
    /**
1127
     * Wraps the passed exeception into a new one by trying to resolve the original filname,
1128
     * line number and column names and use it for a detailed exception message.
1129
     *
1130
     * @param array      $columnNames The column names that should be resolved and wrapped
1131
     * @param \Exception $parent      The exception we want to wrap
1132
     * @param string     $className   The class name of the exception type we want to wrap the parent one
1133
     *
1134
     * @return \Exception the wrapped exception
1135
     */
1136 2
    public function wrapException(
1137
        array $columnNames = array(),
1138
        \Exception $parent = null,
1139
        $className = '\TechDivision\Import\Exceptions\WrappedColumnException'
1140
    ) {
1141
1142
        // initialize the message
1143 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...
1144
1145
        // query whether or not has been a result of invalid data of a previous column of a CSV file
1146 2
        if ($this->hasOriginalData()) {
1147
            // load the original data
1148 1
            $originalData = $this->getOriginalData();
1149
1150
            // replace old filename and line number of the original message
1151 1
            $message = $this->appendExceptionSuffix(
1152 1
                $this->stripExceptionSuffix($message),
1153 1
                $originalData[ColumnKeys::ORIGINAL_FILENAME],
1154 1
                $originalData[ColumnKeys::ORIGINAL_LINE_NUMBER]
1155
            );
1156
0 ignored issues
show
Coding Style introduced by
Blank line found at end of control structure
Loading history...
1157
        } else {
1158
            // append filename and line number to the original message
1159 1
            $message = $this->appendExceptionSuffix(
1160 1
                $this->stripExceptionSuffix($message),
1161 1
                $this->filename,
1162 1
                $this->lineNumber
1163
            );
1164
        }
1165
1166
        // query whether or not, column names has been passed
1167 2
        if (sizeof($columnNames) > 0) {
1168
            // prepare the original column names
1169 1
            $originalColumnNames = array();
1170 1
            foreach ($columnNames as $columnName) {
1171 1
                $originalColumnNames[] = $this->resolveOriginalColumnName($columnName);
1172
            }
1173
1174
            // append the column information
1175 1
            $message = sprintf('%s in column(s) %s', $message, implode(', ', $originalColumnNames));
1176
        }
1177
1178
        // create a new exception and wrap the parent one
1179 2
        return new $className($message, null, $parent);
1180
    }
1181
1182
    /**
1183
     * Strip's the exception suffix containing filename and line number from the
1184
     * passed message.
1185
     *
1186
     * @param string $message The message to strip the exception suffix from
1187
     *
1188
     * @return mixed The message without the exception suffix
1189
     */
1190 2
    public function stripExceptionSuffix($message)
1191
    {
1192 2
        return str_replace($this->appendExceptionSuffix(), '', $message);
1193
    }
1194
1195
    /**
1196
     * Append's the exception suffix containing filename and line number to the
1197
     * passed message. If no message has been passed, only the suffix will be
1198
     * returned
1199
     *
1200
     * @param string|null $message    The message to append the exception suffix to
1201
     * @param string|null $filename   The filename used to create the suffix
1202
     * @param string|null $lineNumber The line number used to create the suffx
1203
     *
1204
     * @return string The message with the appended exception suffix
1205
     */
1206 12
    public function appendExceptionSuffix($message = null, $filename = null, $lineNumber = null)
1207
    {
1208
1209
        // query whether or not a filename has been passed
1210 12
        if ($filename === null) {
1211 12
            $filename = $this->getFilename();
1212
        }
1213
1214
        // query whether or not a line number has been passed
1215 12
        if ($lineNumber === null) {
1216 12
            $lineNumber = $this->getLineNumber();
1217
        }
1218
1219
        // if no message has been passed, only return the suffix
1220 12
        if ($message === null) {
1221 2
            return sprintf(' in file %s on line %d', $filename, $lineNumber);
1222
        }
1223
1224
        // concatenate the message with the suffix and return it
1225 12
        return sprintf('%s in file %s on line %d', $message, $filename, $lineNumber);
1226
    }
1227
1228
    /**
1229
     * Raises the value for the counter with the passed key by one.
1230
     *
1231
     * @param mixed $counterName The name of the counter to raise
1232
     *
1233
     * @return integer The counter's new value
1234
     */
1235 1
    public function raiseCounter($counterName)
1236
    {
1237
1238
        // raise the counter with the passed name
1239 1
        return $this->getRegistryProcessor()->raiseCounter(
1240 1
            $this->getSerial(),
1241 1
            $counterName
1242
        );
1243
    }
1244
1245
    /**
1246
     * Merge the passed array into the status of the actual import.
1247
     *
1248
     * @param array $status The status information to be merged
1249
     *
1250
     * @return void
1251
     */
1252 1
    public function mergeAttributesRecursive(array $status)
1253
    {
1254
1255
        // merge the passed status
1256 1
        $this->getRegistryProcessor()->mergeAttributesRecursive(
1257 1
            $this->getSerial(),
1258 1
            $status
1259
        );
1260 1
    }
1261
}
1262