Completed
Push — 15.x ( f1a10c...84e4c2 )
by Tim
06:28
created

AbstractSubject::raiseCounter()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 1

Importance

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

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
386
    }
387
388
    /**
389
     * Set's the subject configuration.
390
     *
391
     * @param \TechDivision\Import\Configuration\SubjectConfigurationInterface $configuration The subject configuration
392
     *
393
     * @return void
394
     */
395 82
    public function setConfiguration(SubjectConfigurationInterface $configuration)
396
    {
397 82
        $this->configuration = $configuration;
398 82
    }
399
400
    /**
401
     * Return's the subject configuration.
402
     *
403
     * @return \TechDivision\Import\Configuration\SubjectConfigurationInterface The subject configuration
404
     */
405 82
    public function getConfiguration()
406
    {
407 82
        return $this->configuration;
408
    }
409
410
    /**
411
     * Set's the import adapter instance.
412
     *
413
     * @param \TechDivision\Import\Adapter\ImportAdapterInterface $importAdapter The import adapter instance
414
     *
415
     * @return void
416
     */
417 1
    public function setImportAdapter(ImportAdapterInterface $importAdapter)
418
    {
419 1
        $this->importAdapter = $importAdapter;
420 1
    }
421
422
    /**
423
     * Return's the import adapter instance.
424
     *
425
     * @return \TechDivision\Import\Adapter\ImportAdapterInterface The import adapter instance
426
     */
427 1
    public function getImportAdapter()
428
    {
429 1
        return $this->importAdapter;
430
    }
431
432
    /**
433
     * Return's the RegistryProcessor instance to handle the running threads.
434
     *
435
     * @return \TechDivision\Import\Services\RegistryProcessorInterface The registry processor instance
436
     */
437 82
    public function getRegistryProcessor()
438
    {
439 82
        return $this->registryProcessor;
440
    }
441
442
    /**
443
     * Set's the unique serial for this import process.
444
     *
445
     * @param string $serial The unique serial
446
     *
447
     * @return void
448
     */
449 9
    public function setSerial($serial)
450
    {
451 9
        $this->serial = $serial;
452 9
    }
453
454
    /**
455
     * Return's the unique serial for this import process.
456
     *
457
     * @return string The unique serial
458
     */
459 2
    public function getSerial()
460
    {
461 2
        return $this->serial;
462
    }
463
464
    /**
465
     * Merge's the passed status into the actual one.
466
     *
467
     * @param array $status The status to MergeBuilder
468
     *
469
     * @return void
470
     */
471 2
    public function mergeStatus(array $status)
472
    {
473 2
        $this->status = array_merge_recursive($this->status, $status);
474 2
    }
475
476
    /**
477
     * Retur's the actual status.
478
     *
479
     * @return array The actual status
480
     */
481 1
    public function getStatus()
482
    {
483 1
        return $this->status;
484
    }
485
486
    /**
487
     * Return's the unique identifier for the actual invocation.
488
     *
489
     * @return string The unique identifier
490
     */
491 2
    public function getUniqueId()
492
    {
493 2
        return $this->uniqueId;
494
    }
495
496
    /**
497
     * Return's the source date format to use.
498
     *
499
     * @return string The source date format
500
     */
501
    public function getSourceDateFormat()
502
    {
503
        return $this->getConfiguration()->getSourceDateFormat();
0 ignored issues
show
Bug introduced by
The method getSourceDateFormat() does not seem to exist on object<TechDivision\Impo...ConfigurationInterface>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
504
    }
505
506
    /**
507
     * Return's the multiple field delimiter character to use, default value is comma (,).
508
     *
509
     * @return string The multiple field delimiter character
510
     */
511 1
    public function getMultipleFieldDelimiter()
512
    {
513 1
        return $this->getConfiguration()->getMultipleFieldDelimiter();
514
    }
515
516
    /**
517
     * Return's the multiple value delimiter character to use, default value is comma (|).
518
     *
519
     * @return string The multiple value delimiter character
520
     */
521 1
    public function getMultipleValueDelimiter()
522
    {
523 1
        return $this->getConfiguration()->getMultipleValueDelimiter();
524
    }
525
526
    /**
527
     * Intializes the previously loaded global data for exactly one bunch.
528
     *
529
     * @param string $serial The serial of the actual import
530
     *
531
     * @return void
532
     */
533 82
    public function setUp($serial)
534
    {
535
536
        // initialize the unique ID for the actual invocation
537 82
        $this->uniqueId = Uuid::uuid4()->toString();
538
539
        // load the status of the actual import
540 82
        $status = $this->getRegistryProcessor()->getAttribute(RegistryKeys::STATUS);
541
542
        // load the global data, if prepared initially
543 82
        if (isset($status[RegistryKeys::GLOBAL_DATA])) {
544 82
            $this->stores = $status[RegistryKeys::GLOBAL_DATA][RegistryKeys::STORES];
545 82
            $this->defaultStore = $status[RegistryKeys::GLOBAL_DATA][RegistryKeys::DEFAULT_STORE];
546 82
            $this->storeWebsites  = $status[RegistryKeys::GLOBAL_DATA][RegistryKeys::STORE_WEBSITES];
547 82
            $this->rootCategories = $status[RegistryKeys::GLOBAL_DATA][RegistryKeys::ROOT_CATEGORIES];
548 82
            $this->coreConfigData = $status[RegistryKeys::GLOBAL_DATA][RegistryKeys::CORE_CONFIG_DATA];
549
        }
550
551
        // merge the callback mappings with the mappings from the child instance
552 82
        $this->callbackMappings = array_merge($this->callbackMappings, $this->getDefaultCallbackMappings());
553
554
        // merge the header mappings with the values found in the configuration
555 82
        $this->headerMappings = array_merge($this->headerMappings, $this->getConfiguration()->getHeaderMappings());
556
557
        // load the available callbacks from the configuration
558 82
        $availableCallbacks = $this->getConfiguration()->getCallbacks();
559
560
        // merge the callback mappings the the one from the configuration file
561 82
        foreach ($availableCallbacks as $callbackMappings) {
562 82
            foreach ($callbackMappings as $attributeCode => $mappings) {
563
                // write a log message, that default callback configuration will
564
                // be overwritten with the one from the configuration file
565 82
                if (isset($this->callbackMappings[$attributeCode])) {
566 82
                    $this->getSystemLogger()->notice(
567 82
                        sprintf('Now override callback mappings for attribute %s with values found in configuration file', $attributeCode)
568
                    );
569
                }
570
571
                // override the attributes callbacks
572 82
                $this->callbackMappings[$attributeCode] = $mappings;
573
            }
574
        }
575 82
    }
576
577
    /**
578
     * Clean up the global data after importing the variants.
579
     *
580
     * @param string $serial The serial of the actual import
581
     *
582
     * @return void
583
     */
584 1
    public function tearDown($serial)
585
    {
586
587
        // load the registry processor
588 1
        $registryProcessor = $this->getRegistryProcessor();
589
590
        // update the source directory for the next subject
591 1
        $registryProcessor->mergeAttributesRecursive(RegistryKeys::STATUS, array(RegistryKeys::FILES => $this->getStatus()));
592
593
        // log a debug message with the new source directory
594
        $this->getSystemLogger()->debug(
595
            sprintf('Subject %s successfully updated status data for import %s', get_class($this), $serial)
596
        );
597
    }
598
599
    /**
600
     * Return's the target directory for the artefact export.
601
     *
602
     * @return string The target directory for the artefact export
603
     */
604 1 View Code Duplication
    public function getTargetDir()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
605
    {
606
607
        // load the status from the registry processor
608 1
        $status = $this->getRegistryProcessor()->getAttribute(RegistryKeys::STATUS);
609
610
        // query whether or not a target directory (mandatory) has been configured
611 1
        if (isset($status[RegistryKeys::TARGET_DIRECTORY])) {
612
            return $status[RegistryKeys::TARGET_DIRECTORY];
613
        }
614
615
        // throw an exception if the root category is NOT available
616 1
        throw new \Exception(sprintf('Can\'t find a target directory in status data for import %s', $this->getSerial()));
617
    }
618
619
    /**
620
     * Register the passed observer with the specific type.
621
     *
622
     * @param \TechDivision\Import\Observers\ObserverInterface $observer The observer to register
623
     * @param string                                           $type     The type to register the observer with
624
     *
625
     * @return void
626
     */
627 6
    public function registerObserver(ObserverInterface $observer, $type)
628
    {
629
630
        // query whether or not the array with the callbacks for the
631
        // passed type has already been initialized, or not
632 6
        if (!isset($this->observers[$type])) {
633 6
            $this->observers[$type] = array();
634
        }
635
636
        // append the callback with the instance of the passed type
637 6
        $this->observers[$type][] = $observer;
638 6
    }
639
640
    /**
641
     * Register the passed callback with the specific type.
642
     *
643
     * @param \TechDivision\Import\Callbacks\CallbackInterface $callback The subject to register the callbacks for
644
     * @param string                                           $type     The type to register the callback with
645
     *
646
     * @return void
647
     */
648 2
    public function registerCallback(CallbackInterface $callback, $type)
649
    {
650
651
        // query whether or not the array with the callbacks for the
652
        // passed type has already been initialized, or not
653 2
        if (!isset($this->callbacks[$type])) {
654 2
            $this->callbacks[$type] = array();
655
        }
656
657
        // append the callback with the instance of the passed type
658 2
        $this->callbacks[$type][] = $callback;
659 2
    }
660
661
    /**
662
     * Return's the array with callbacks for the passed type.
663
     *
664
     * @param string $type The type of the callbacks to return
665
     *
666
     * @return array The callbacks
667
     */
668 1
    public function getCallbacksByType($type)
669
    {
670
671
        // initialize the array for the callbacks
672 1
        $callbacks = array();
673
674
        // query whether or not callbacks for the type are available
675 1
        if (isset($this->callbacks[$type])) {
676 1
            $callbacks = $this->callbacks[$type];
677
        }
678
679
        // return the array with the type's callbacks
680 1
        return $callbacks;
681
    }
682
683
    /**
684
     * Return's the array with the available observers.
685
     *
686
     * @return array The observers
687
     */
688 6
    public function getObservers()
689
    {
690 6
        return $this->observers;
691
    }
692
693
    /**
694
     * Return's the array with the available callbacks.
695
     *
696
     * @return array The callbacks
697
     */
698 1
    public function getCallbacks()
699
    {
700 1
        return $this->callbacks;
701
    }
702
703
    /**
704
     * Return's the callback mappings for this subject.
705
     *
706
     * @return array The array with the subject's callback mappings
707
     */
708 2
    public function getCallbackMappings()
709
    {
710 2
        return $this->callbackMappings;
711
    }
712
713
    /**
714
     * Imports the content of the file with the passed filename.
715
     *
716
     *
717
     * @param string $serial   The serial of the actual import
718
     * @param string $filename The filename to process
719
     *
720
     * @return void
721
     * @throws \Exception Is thrown, if the import can't be processed
722
     */
723 2
    public function import($serial, $filename)
724
    {
725
726
        try {
727
            // initialize the serial/filename
728 2
            $this->setSerial($serial);
729 2
            $this->setFilename($filename);
730
731
            // invoke the events that has to be fired before the artfact will be processed
732 2
            $this->getEmitter()->emit(EventNames::SUBJECT_ARTEFACT_PROCESS_START, $this);
0 ignored issues
show
Unused Code introduced by
The call to EmitterInterface::emit() has too many arguments starting with $this.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
733
734
            // load the system logger instance
735 2
            $systemLogger = $this->getSystemLogger();
736
737
            // prepare the flag filenames
738 2
            $inProgressFilename = sprintf('%s.inProgress', $filename);
739 2
            $importedFilename = sprintf('%s.imported', $filename);
740 2
            $failedFilename = sprintf('%s.failed', $filename);
741
742
            // query whether or not the file has already been imported
743 2
            if ($this->isFile($failedFilename) ||
744 1
                $this->isFile($importedFilename) ||
745 2
                $this->isFile($inProgressFilename)
746
            ) {
747
                // log a debug message and exit
748 1
                $systemLogger->debug(sprintf('Import running, found inProgress file %s', $inProgressFilename));
749 1
                return;
750
            }
751
752
            // flag file as in progress
753 1
            $this->touch($inProgressFilename);
754
755
            // track the start time
756 1
            $startTime = microtime(true);
757
758
            // initialize the last time we've logged the counter with the processed rows per minute
759 1
            $this->lastLog = time();
760
761
            // log a message that the file has to be imported
762 1
            $systemLogger->info(sprintf('Now start processing file %s', $filename));
763
764
            // let the adapter process the file
765 1
            $this->getImportAdapter()->import(array($this, 'importRow'), $filename);
766
767
            // track the time needed for the import in seconds
768 1
            $endTime = microtime(true) - $startTime;
769
770
            // log a message that the file has successfully been imported
771 1
            $systemLogger->info(sprintf('Successfully processed file %s with %d lines in %f s', $filename, $this->lineNumber, $endTime));
772
773
            // rename flag file, because import has been successfull
774 1
            if ($this->getConfiguration()->isCreatingImportedFile()) {
775 1
                $this->rename($inProgressFilename, $importedFilename);
776
            } else {
777
                $this->getFilesystemAdapter()->delete($inProgressFilename);
778
            }
779
780
            // update the status
781 1
            $this->mergeStatus(
782
                array(
783
                    $filename => array(
784 1
                        $this->getUniqueId() => array(
785 1
                            RegistryKeys::STATUS => 1,
786 1
                            RegistryKeys::PROCESSED_ROWS => $this->getLineNumber()
787
                        )
788
                    )
789
                )
790
            );
791
792
            // invoke the events that has to be fired when the artfact has been successfully processed
793 1
            $this->getEmitter()->emit(EventNames::SUBJECT_ARTEFACT_PROCESS_SUCCESS, $this);
0 ignored issues
show
Unused Code introduced by
The call to EmitterInterface::emit() has too many arguments starting with $this.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
794
        } catch (\Exception $e) {
795
            // rename the flag file, because import failed and write the stack trace
796
            $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...
797
            $this->write($failedFilename, $e->__toString());
798
799
            // update the status with the error message
800
            $this->mergeStatus(
801
                array(
802
                    $filename => array(
803
                        $this->getUniqueId() => array(
804
                            RegistryKeys::STATUS         => 2,
805
                            RegistryKeys::ERROR_MESSAGE  => $e->getMessage(),
806
                            RegistryKeys::PROCESSED_ROWS => $this->getLineNumber()
807
                        )
808
                    )
809
                )
810
            );
811
812
            // invoke the events that has to be fired when the artfact can't be processed
813
            $this->getEmitter()->emit(EventNames::SUBJECT_ARTEFACT_PROCESS_FAILURE, $this, $e);
0 ignored issues
show
Unused Code introduced by
The call to EmitterInterface::emit() has too many arguments starting with $this.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
814
815
            // do not wrap the exception if not already done
816
            if ($e instanceof WrappedColumnException) {
817
                throw $e;
818
            }
819
820
            // else wrap and throw the exception
821
            throw $this->wrapException(array(), $e);
822
        }
823 1
    }
824
825
    /**
826
     * Imports the passed row into the database. If the import failed, the exception
827
     * will be catched and logged, but the import process will be continued.
828
     *
829
     * @param array $row The row with the data to be imported
830
     *
831
     * @return void
832
     */
833 7
    public function importRow(array $row)
834
    {
835
836
        // initialize the row
837 7
        $this->row = $row;
838
839
        // raise the line number and reset the skip row flag
840 7
        $this->lineNumber++;
841 7
        $this->skipRow = false;
842
843
        // invoke the events that has to be fired before the artfact's row will be processed
844 7
        $this->getEmitter()->emit(EventNames::SUBJECT_ARTEFACT_ROW_PROCESS_START, $this);
0 ignored issues
show
Unused Code introduced by
The call to EmitterInterface::emit() has too many arguments starting with $this.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
845
846
        // initialize the headers with the columns from the first line
847 7
        if (sizeof($this->headers) === 0) {
848 1
            foreach ($this->row as $value => $key) {
849 1
                $this->headers[$this->mapAttributeCodeByHeaderMapping($key)] = $value;
850
            }
851 1
            return;
852
        }
853
854
        // load the available observers
855 6
        $availableObservers = $this->getObservers();
856
857
        // process the observers
858 6
        foreach ($availableObservers as $observers) {
859
            // invoke the pre-import/import and post-import observers
860
            /** @var \TechDivision\Import\Observers\ObserverInterface $observer */
861 6
            foreach ($observers as $observer) {
862
                // query whether or not we have to skip the row
863 6
                if ($this->skipRow) {
864
                    // log a debug message with the actual line nr/file information
865 1
                    $this->getSystemLogger()->warning(
866 1
                        $this->appendExceptionSuffix(
867 1
                            sprintf(
868 1
                                'Skip processing operation "%s" after observer "%s"',
869 1
                                implode(' > ', $this->getConfiguration()->getConfiguration()->getOperationNames()),
870
                                get_class($observer)
871
                            )
872
                        )
873
                    );
874
875
                    // skip the row
876
                    break 2;
877
                }
878
879
                // if not, set the subject and process the observer
880 6
                if ($observer instanceof ObserverInterface) {
881 6
                    $this->row = $observer->handle($this);
882
                }
883
            }
884
        }
885
886
        // query whether or not a minute has been passed
887 5
        if ($this->lastLog < time() - 60) {
888
            // log the number processed rows per minute
889 5
            $this->getSystemLogger()->info(
890 5
                sprintf(
891 5
                    'Successfully processed "%d (%d)" rows per minute of file "%s"',
892 5
                    $this->lineNumber - $this->lastLineNumber,
893 5
                    $this->lineNumber,
894 5
                    $this->getFilename()
895
                )
896
            );
897
898
            // reset the last log time and the line number
899 5
            $this->lastLog = time();
900 5
            $this->lastLineNumber = $this->lineNumber;
901
        }
902
903
        // log a debug message with the actual line nr/file information
904 5
        $this->getSystemLogger()->debug(
905 5
            $this->appendExceptionSuffix(
906 5
                sprintf(
907 5
                    'Successfully processed operation "%s"',
908 5
                    implode(' > ', $this->getConfiguration()->getConfiguration()->getOperationNames())
909
                )
910
            )
911
        );
912
913
        // invoke the events that has to be fired when the artfact's row has been successfully processed
914
        $this->getEmitter()->emit(EventNames::SUBJECT_ARTEFACT_ROW_PROCESS_SUCCESS, $this);
0 ignored issues
show
Unused Code introduced by
The call to EmitterInterface::emit() has too many arguments starting with $this.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
915
    }
916
917
    /**
918
     * Queries whether or not that the subject needs an OK file to be processed.
919
     *
920
     * @return boolean TRUE if the subject needs an OK file, else FALSE
921
     */
922 1
    public function isOkFileNeeded()
923
    {
924 1
        return $this->getConfiguration()->isOkFileNeeded();
925
    }
926
927
    /**
928
     * Return's the default store.
929
     *
930
     * @return array The default store
931
     */
932
    public function getDefaultStore()
933
    {
934
        return $this->defaultStore;
935
    }
936
937
    /**
938
     * Return's the default store view code.
939
     *
940
     * @return array The default store view code
941
     */
942 4
    public function getDefaultStoreViewCode()
943
    {
944 4
        return $this->defaultStore[MemberNames::CODE];
945
    }
946
947
    /**
948
     * Set's the store view code the create the product/attributes for.
949
     *
950
     * @param string $storeViewCode The store view code
951
     *
952
     * @return void
953
     */
954 3
    public function setStoreViewCode($storeViewCode)
955
    {
956 3
        $this->storeViewCode = $storeViewCode;
957 3
    }
958
959
    /**
960
     * Return's the store view code the create the product/attributes for.
961
     *
962
     * @param string|null $default The default value to return, if the store view code has not been set
963
     *
964
     * @return string The store view code
965
     */
966 6
    public function getStoreViewCode($default = null)
967
    {
968
969
        // return the store view code, if available
970 6
        if ($this->storeViewCode !== null) {
971 2
            return $this->storeViewCode;
972
        }
973
974
        // if NOT and a default code is available
975 4
        if ($default !== null) {
976
            // return the default value
977 3
            return $default;
978
        }
979
980
        // return the default store view code
981 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...
982
    }
983
984
    /**
985
     * Prepare's the store view code in the subject. If the store_view_code row doesn't contain
986
     * any value, the default code of the default store view will be set.
987
     *
988
     * @return void
989
     */
990 1
    public function prepareStoreViewCode()
991
    {
992
993
        // re-set the store view code
994 1
        $this->setStoreViewCode(null);
995
996
        // initialize the store view code
997 1
        if ($storeViewCode = $this->getValue(ColumnKeys::STORE_VIEW_CODE)) {
998 1
            $this->setStoreViewCode($storeViewCode);
999
        }
1000 1
    }
1001
1002
    /**
1003
     * Return's the store ID of the store with the passed store view code
1004
     *
1005
     * @param string $storeViewCode The store view code to return the store ID for
1006
     *
1007
     * @return integer The ID of the store with the passed ID
1008
     * @throws \Exception Is thrown, if the store with the actual code is not available
1009
     */
1010 2
    public function getStoreId($storeViewCode)
1011
    {
1012
1013
        // query whether or not, the requested store is available
1014 2
        if (isset($this->stores[$storeViewCode])) {
1015 2
            return (integer) $this->stores[$storeViewCode][MemberNames::STORE_ID];
1016
        }
1017
1018
        // throw an exception, if not
1019
        throw new \Exception(
1020
            sprintf(
1021
                'Found invalid store view code %s in file %s on line %d',
1022
                $storeViewCode,
1023
                $this->getFilename(),
1024
                $this->getLineNumber()
1025
            )
1026
        );
1027
    }
1028
1029
    /**
1030
     * Return's the store ID of the actual row, or of the default store
1031
     * if no store view code is set in the CSV file.
1032
     *
1033
     * @param string|null $default The default store view code to use, if no store view code is set in the CSV file
1034
     *
1035
     * @return integer The ID of the actual store
1036
     * @throws \Exception Is thrown, if the store with the actual code is not available
1037
     */
1038 1
    public function getRowStoreId($default = null)
1039
    {
1040
1041
        // initialize the default store view code, if not passed
1042 1
        if ($default === null) {
1043 1
            $default = $this->getDefaultStoreViewCode();
1044
        }
1045
1046
        // load the store view code the create the product/attributes for
1047 1
        return $this->getStoreId($this->getStoreViewCode($default));
0 ignored issues
show
Bug introduced by
It seems like $default defined by $this->getDefaultStoreViewCode() on line 1043 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...
1048
    }
1049
1050
    /**
1051
     * Return's the root category for the actual view store.
1052
     *
1053
     * @return array The store's root category
1054
     * @throws \Exception Is thrown if the root category for the passed store code is NOT available
1055
     */
1056 2
    public function getRootCategory()
1057
    {
1058
1059
        // load the actual store view code
1060 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...
1061
1062
        // query weather or not we've a root category or not
1063 2
        if (isset($this->rootCategories[$storeViewCode])) {
1064 1
            return $this->rootCategories[$storeViewCode];
1065
        }
1066
1067
        // throw an exception if the root category is NOT available
1068 1
        throw new \Exception(sprintf('Root category for %s is not available', $storeViewCode));
1069
    }
1070
1071
    /**
1072
     * Return's the Magento configuration value.
1073
     *
1074
     * @param string  $path    The Magento path of the requested configuration value
1075
     * @param mixed   $default The default value that has to be returned, if the requested configuration value is not set
1076
     * @param string  $scope   The scope the configuration value has been set
1077
     * @param integer $scopeId The scope ID the configuration value has been set
1078
     *
1079
     * @return mixed The configuration value
1080
     * @throws \Exception Is thrown, if nor a value can be found or a default value has been passed
1081
     */
1082 5
    public function getCoreConfigData($path, $default = null, $scope = ScopeKeys::SCOPE_DEFAULT, $scopeId = 0)
1083
    {
1084
1085
        // initialize the core config data
1086
        $coreConfigData = array(
1087 5
            MemberNames::PATH => $path,
1088 5
            MemberNames::SCOPE => $scope,
1089 5
            MemberNames::SCOPE_ID => $scopeId
1090
        );
1091
1092
        // generate the UID from the passed data
1093 5
        $uniqueIdentifier = $this->coreConfigDataUidGenerator->generate($coreConfigData);
1094
1095
        // iterate over the core config data and try to find the requested configuration value
1096 5
        if (isset($this->coreConfigData[$uniqueIdentifier])) {
1097 1
            return $this->coreConfigData[$uniqueIdentifier][MemberNames::VALUE];
1098
        }
1099
1100
        // query whether or not we've to query for the configuration value on fallback level 'websites' also
1101 4
        if ($scope === ScopeKeys::SCOPE_STORES) {
1102
            // query whether or not the website with the passed ID is available
1103 2
            foreach ($this->storeWebsites as $storeWebsite) {
1104 2
                if ($storeWebsite[MemberNames::WEBSITE_ID] === $scopeId) {
1105
                    // replace scope with 'websites' and website ID
1106 2
                    $coreConfigData = array_merge(
1107 2
                        $coreConfigData,
1108
                        array(
1109 2
                            MemberNames::SCOPE    => ScopeKeys::SCOPE_WEBSITES,
1110
                            MemberNames::SCOPE_ID => $storeWebsite[MemberNames::WEBSITE_ID]
1111
                        )
1112
                    );
1113
1114
                    // generate the UID from the passed data, merged with the 'websites' scope and ID
1115 2
                    $uniqueIdentifier = $this->coreConfigDataUidGenerator->generate($coreConfigData);
1116
1117
                    // query whether or not, the configuration value on 'websites' level
1118 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...
1119 1
                        return $this->coreConfigData[$uniqueIdentifier][MemberNames::VALUE];
1120
                    }
1121
                }
1122
            }
1123
        }
1124
1125
        // replace scope with 'default' and scope ID '0'
1126 3
        $coreConfigData = array_merge(
1127 3
            $coreConfigData,
1128
            array(
1129 3
                MemberNames::SCOPE    => ScopeKeys::SCOPE_DEFAULT,
1130
                MemberNames::SCOPE_ID => 0
1131
            )
1132
        );
1133
1134
        // generate the UID from the passed data, merged with the 'default' scope and ID 0
1135 3
        $uniqueIdentifier = $this->coreConfigDataUidGenerator->generate($coreConfigData);
1136
1137
        // query whether or not, the configuration value on 'default' level
1138 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...
1139 1
            return $this->coreConfigData[$uniqueIdentifier][MemberNames::VALUE];
1140
        }
1141
1142
        // if not, return the passed default value
1143 2
        if ($default !== null) {
1144 1
            return $default;
1145
        }
1146
1147
        // throw an exception if no value can be found
1148
        // in the Magento configuration
1149 1
        throw new \Exception(
1150 1
            sprintf(
1151 1
                'Can\'t find a value for configuration "%s-%s-%d" in "core_config_data"',
1152 1
                $path,
1153 1
                $scope,
1154 1
                $scopeId
1155
            )
1156
        );
1157
    }
1158
1159
    /**
1160
     * Resolve the original column name for the passed one.
1161
     *
1162
     * @param string $columnName The column name that has to be resolved
1163
     *
1164
     * @return string|null The original column name
1165
     */
1166 1
    public function resolveOriginalColumnName($columnName)
1167
    {
1168
1169
        // try to load the original data
1170 1
        $originalData = $this->getOriginalData();
1171
1172
        // query whether or not original data is available
1173 1
        if (isset($originalData[ColumnKeys::ORIGINAL_COLUMN_NAMES])) {
1174
            // query whether or not the original column name is available
1175
            if (isset($originalData[ColumnKeys::ORIGINAL_COLUMN_NAMES][$columnName])) {
1176
                return $originalData[ColumnKeys::ORIGINAL_COLUMN_NAMES][$columnName];
1177
            }
1178
1179
            // query whether or a wildcard column name is available
1180
            if (isset($originalData[ColumnKeys::ORIGINAL_COLUMN_NAMES]['*'])) {
1181
                return $originalData[ColumnKeys::ORIGINAL_COLUMN_NAMES]['*'];
1182
            }
1183
        }
1184
1185
        // return the original column name
1186 1
        return $columnName;
1187
    }
1188
1189
    /**
1190
     * Return's the original data if available, or an empty array.
1191
     *
1192
     * @return array The original data
1193
     */
1194 1
    public function getOriginalData()
1195
    {
1196
1197
        // initialize the array for the original data
1198 1
        $originalData = array();
1199
1200
        // query whether or not the column contains original data
1201 1
        if ($this->hasOriginalData()) {
1202
            // unerialize the original data from the column
1203
            $originalData = unserialize($this->row[$this->headers[ColumnKeys::ORIGINAL_DATA]]);
1204
        }
1205
1206
        // return an empty array, if not
1207 1
        return $originalData;
1208
    }
1209
1210
    /**
1211
     * Query's whether or not the actual column contains original data like
1212
     * filename, line number and column names.
1213
     *
1214
     * @return boolean TRUE if the actual column contains origin data, else FALSE
1215
     */
1216 1
    public function hasOriginalData()
1217
    {
1218 1
        return isset($this->headers[ColumnKeys::ORIGINAL_DATA]) && isset($this->row[$this->headers[ColumnKeys::ORIGINAL_DATA]]);
1219
    }
1220
1221
    /**
1222
     * Wraps the passed exeception into a new one by trying to resolve the original filname,
1223
     * line number and column names and use it for a detailed exception message.
1224
     *
1225
     * @param array      $columnNames The column names that should be resolved and wrapped
1226
     * @param \Exception $parent      The exception we want to wrap
1227
     * @param string     $className   The class name of the exception type we want to wrap the parent one
1228
     *
1229
     * @return \Exception the wrapped exception
1230
     */
1231
    public function wrapException(
1232
        array $columnNames = array(),
1233
        \Exception $parent = null,
1234
        $className = '\TechDivision\Import\Exceptions\WrappedColumnException'
1235
    ) {
1236
1237
        // initialize the message
1238
        $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...
1239
1240
        // query whether or not has been a result of invalid data of a previous column of a CSV file
1241
        if ($this->hasOriginalData()) {
1242
            // load the original data
1243
            $originalData = $this->getOriginalData();
1244
1245
            // replace old filename and line number of the original message
1246
            $message = $this->appendExceptionSuffix(
1247
                $this->stripExceptionSuffix($message),
1248
                $originalData[ColumnKeys::ORIGINAL_FILENAME],
1249
                $originalData[ColumnKeys::ORIGINAL_LINE_NUMBER]
1250
            );
1251
        } else {
1252
            // append filename and line number to the original message
1253
            $message = $this->appendExceptionSuffix(
1254
                $this->stripExceptionSuffix($message),
1255
                $this->filename,
1256
                $this->lineNumber
1257
            );
1258
        }
1259
1260
        // query whether or not, column names has been passed
1261
        if (sizeof($columnNames) > 0) {
1262
            // prepare the original column names
1263
            $originalColumnNames = array();
1264
            foreach ($columnNames as $columnName) {
1265
                $originalColumnNames[] = $this->resolveOriginalColumnName($columnName);
1266
            }
1267
1268
            // append the column information
1269
            $message = sprintf('%s in column(s) %s', $message, implode(', ', $originalColumnNames));
1270
        }
1271
1272
        // create a new exception and wrap the parent one
1273
        return new $className($message, null, $parent);
1274
    }
1275
1276
    /**
1277
     * Strip's the exception suffix containing filename and line number from the
1278
     * passed message.
1279
     *
1280
     * @param string $message The message to strip the exception suffix from
1281
     *
1282
     * @return mixed The message without the exception suffix
1283
     */
1284
    public function stripExceptionSuffix($message)
1285
    {
1286
        return str_replace($this->appendExceptionSuffix(), '', $message);
1287
    }
1288
1289
    /**
1290
     * Append's the exception suffix containing filename and line number to the
1291
     * passed message. If no message has been passed, only the suffix will be
1292
     * returned
1293
     *
1294
     * @param string|null $message    The message to append the exception suffix to
1295
     * @param string|null $filename   The filename used to create the suffix
1296
     * @param string|null $lineNumber The line number used to create the suffx
1297
     *
1298
     * @return string The message with the appended exception suffix
1299
     */
1300 8
    public function appendExceptionSuffix($message = null, $filename = null, $lineNumber = null)
1301
    {
1302
1303
        // query whether or not a filename has been passed
1304 8
        if ($filename === null) {
1305 8
            $filename = $this->getFilename();
1306
        }
1307
1308
        // query whether or not a line number has been passed
1309 8
        if ($lineNumber === null) {
1310 8
            $lineNumber = $this->getLineNumber();
1311
        }
1312
1313
        // if no message has been passed, only return the suffix
1314 8
        if ($message === null) {
1315
            return sprintf(' in file %s on line %d', $filename, $lineNumber);
1316
        }
1317
1318
        // concatenate the message with the suffix and return it
1319 8
        return sprintf('%s in file %s on line %d', $message, $filename, $lineNumber);
1320
    }
1321
1322
    /**
1323
     * Raises the value for the counter with the passed key by one.
1324
     *
1325
     * @param mixed $counterName The name of the counter to raise
1326
     *
1327
     * @return integer The counter's new value
1328
     */
1329 1
    public function raiseCounter($counterName)
1330
    {
1331
1332
        // raise the counter with the passed name
1333 1
        return $this->getRegistryProcessor()->raiseCounter(
1334 1
            RegistryKeys::COUNTERS,
1335 1
            $counterName
1336
        );
1337
    }
1338
1339
    /**
1340
     * Merge the passed array into the status of the actual import.
1341
     *
1342
     * @param array $status The status information to be merged
1343
     *
1344
     * @return void
1345
     */
1346 1
    public function mergeAttributesRecursive(array $status)
1347
    {
1348
1349
        // merge the passed status
1350 1
        return $this->getRegistryProcessor()->mergeAttributesRecursive(
1351 1
            RegistryKeys::STATUS,
1352 1
            $status
1353
        );
1354
    }
1355
1356
    /**
1357
     * Return's the entity type code to be used.
1358
     *
1359
     * @return string The entity type code to be used
1360
     */
1361
    public function getEntityTypeCode()
1362
    {
1363
1364
        // load the configuration specific entity type code from the plugin configuration
1365
        $entityTypeCode = $this->getExecutionContext()->getEntityTypeCode();
1366
1367
        // try to map the entity type code
1368
        if (isset($this->entityTypeCodeMappings[$entityTypeCode])) {
1369
            $entityTypeCode = $this->entityTypeCodeMappings[$entityTypeCode];
1370
        }
1371
1372
        // return the (mapped) entity type code
1373
        return $entityTypeCode;
1374
    }
1375
}
1376