Completed
Push — 15.x ( 60340d...89878a )
by Tim
02:34
created

AbstractSubject::getExecutionContext()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 4
c 0
b 0
f 0
ccs 0
cts 4
cp 0
rs 10
cc 1
nc 1
nop 0
crap 2
1
<?php
2
3
/**
4
 * TechDivision\Import\Subjects\AbstractSubject
5
 *
6
 * NOTICE OF LICENSE
7
 *
8
 * This source file is subject to the Open Software License (OSL 3.0)
9
 * that is available through the world-wide-web at this URL:
10
 * http://opensource.org/licenses/osl-3.0.php
11
 *
12
 * PHP version 5
13
 *
14
 * @author    Tim Wagner <[email protected]>
15
 * @copyright 2016 TechDivision GmbH <[email protected]>
16
 * @license   http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
17
 * @link      https://github.com/techdivision/import
18
 * @link      http://www.techdivision.com
19
 */
20
21
namespace TechDivision\Import\Subjects;
22
23
use League\Event\EmitterInterface;
24
use Doctrine\Common\Collections\Collection;
25
use TechDivision\Import\RowTrait;
26
use TechDivision\Import\HeaderTrait;
27
use TechDivision\Import\SystemLoggerTrait;
28
use TechDivision\Import\Utils\ScopeKeys;
29
use TechDivision\Import\Utils\ColumnKeys;
30
use TechDivision\Import\Utils\EventNames;
31
use TechDivision\Import\Utils\MemberNames;
32
use TechDivision\Import\Utils\RegistryKeys;
33
use TechDivision\Import\Utils\EntityTypeCodes;
34
use TechDivision\Import\Utils\Generators\GeneratorInterface;
35
use TechDivision\Import\Callbacks\CallbackInterface;
36
use TechDivision\Import\Observers\ObserverInterface;
37
use TechDivision\Import\Adapter\ImportAdapterInterface;
38
use TechDivision\Import\Exceptions\WrappedColumnException;
39
use TechDivision\Import\Services\RegistryProcessorInterface;
40
use TechDivision\Import\Configuration\SubjectConfigurationInterface;
41
42
/**
43
 * An abstract subject implementation.
44
 *
45
 * @author    Tim Wagner <[email protected]>
46
 * @copyright 2016 TechDivision GmbH <[email protected]>
47
 * @license   http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
48
 * @link      https://github.com/techdivision/import
49
 * @link      http://www.techdivision.com
50
 */
51
abstract class AbstractSubject implements SubjectInterface, FilesystemSubjectInterface, DateConverterSubjectInterface
52
{
53
54
    /**
55
     * The trait that provides basic filesystem handling functionality.
56
     *
57
     * @var \TechDivision\Import\Subjects\FilesystemTrait
58
     */
59
    use FilesystemTrait;
60
61
    /**
62
     * The trait that provides basic filesystem handling functionality.
63
     *
64
     * @var \TechDivision\Import\SystemLoggerTrait
65
     */
66
    use SystemLoggerTrait;
67
68
    /**
69
     * The trait that provides date converting functionality.
70
     *
71
     * @var \TechDivision\Import\DateConverterTrait
72
     */
73
    use DateConverterTrait;
74
75
    /**
76
     * The trait that provides header handling functionality.
77
     *
78
     * @var \TechDivision\Import\HeaderTrait
79
     */
80
    use HeaderTrait;
81
82
    /**
83
     * The trait that provides row handling functionality.
84
     *
85
     * @var \TechDivision\Import\RowTrait
86
     */
87
    use RowTrait;
88
89
    /**
90
     * The name of the file to be imported.
91
     *
92
     * @var string
93
     */
94
    protected $filename;
95
96
    /**
97
     * The actual line number.
98
     *
99
     * @var integer
100
     */
101
    protected $lineNumber = 0;
102
103
    /**
104
     * The import adapter instance.
105
     *
106
     * @var \TechDivision\Import\Adapter\ImportAdapterInterface
107
     */
108
    protected $importAdapter;
109
110
    /**
111
     * The subject configuration.
112
     *
113
     * @var \TechDivision\Import\Configuration\SubjectConfigurationInterface
114
     */
115
    protected $configuration;
116
117
    /**
118
     * The plugin configuration.
119
     *
120
     * @var \TechDivision\Import\Configuration\PluginConfigurationInterface
121
     */
122
    protected $pluginConfiguration;
123
124
    /**
125
     * The RegistryProcessor instance to handle running threads.
126
     *
127
     * @var \TechDivision\Import\Services\RegistryProcessorInterface
128
     */
129
    protected $registryProcessor;
130
131
    /**
132
     * The actions unique serial.
133
     *
134
     * @var string
135
     */
136
    protected $serial;
137
138
    /**
139
     * Array with the subject's observers.
140
     *
141
     * @var array
142
     */
143
    protected $observers = array();
144
145
    /**
146
     * Array with the subject's callbacks.
147
     *
148
     * @var array
149
     */
150
    protected $callbacks = array();
151
152
    /**
153
     * The subject's callback mappings.
154
     *
155
     * @var array
156
     */
157
    protected $callbackMappings = array();
158
159
    /**
160
     * The available root categories.
161
     *
162
     * @var array
163
     */
164
    protected $rootCategories = array();
165
166
    /**
167
     * The Magento configuration.
168
     *
169
     * @var array
170
     */
171
    protected $coreConfigData = array();
172
173
    /**
174
     * The available stores.
175
     *
176
     * @var array
177
     */
178
    protected $stores = array();
179
180
    /**
181
     * The available websites.
182
     *
183
     * @var array
184
     */
185
    protected $storeWebsites = array();
186
187
    /**
188
     * The default store.
189
     *
190
     * @var array
191
     */
192
    protected $defaultStore;
193
194
    /**
195
     * The store view code the create the product/attributes for.
196
     *
197
     * @var string
198
     */
199
    protected $storeViewCode;
200
201
    /**
202
     * The UID generator for the core config data.
203
     *
204
     * @var \TechDivision\Import\Utils\Generators\GeneratorInterface
205
     */
206
    protected $coreConfigDataUidGenerator;
207
208
    /**
209
     * UNIX timestamp with the date the last row counter has been logged.
210
     *
211
     * @var integer
212
     */
213
    protected $lastLog = 0;
214
215
    /**
216
     * The number of the last line that has been logged with the row counter
217
     * @var integer
218
     */
219
    protected $lastLineNumber = 0;
220
221
    /**
222
     * The event emitter instance.
223
     *
224
     * @var \League\Event\EmitterInterface
225
     */
226
    protected $emitter;
227
228
    /**
229
     * Mapping for the virtual entity type code to the real Magento 2 EAV entity type code.
230
     *
231
     * @var array
232
     */
233
    protected $entityTypeCodeMappings = array(
234
        EntityTypeCodes::EAV_ATTRIBUTE                 => EntityTypeCodes::CATALOG_PRODUCT,
235
        EntityTypeCodes::EAV_ATTRIBUTE_SET             => EntityTypeCodes::CATALOG_PRODUCT,
236
        EntityTypeCodes::CATALOG_PRODUCT_PRICE         => EntityTypeCodes::CATALOG_PRODUCT,
237
        EntityTypeCodes::CATALOG_PRODUCT_INVENTORY     => EntityTypeCodes::CATALOG_PRODUCT,
238
        EntityTypeCodes::CATALOG_PRODUCT_INVENTORY_MSI => EntityTypeCodes::CATALOG_PRODUCT,
239
        EntityTypeCodes::CATALOG_PRODUCT_TIER_PRICE    => EntityTypeCodes::CATALOG_PRODUCT
240
    );
241
242
    /**
243
     * Initialize the subject instance.
244
     *
245
     * @param \TechDivision\Import\Services\RegistryProcessorInterface $registryProcessor          The registry processor instance
246
     * @param \TechDivision\Import\Utils\Generators\GeneratorInterface $coreConfigDataUidGenerator The UID generator for the core config data
247
     * @param \Doctrine\Common\Collections\Collection                  $systemLoggers              The array with the system loggers instances
248
     * @param \League\Event\EmitterInterface                           $emitter                    The event emitter instance
249
     */
250
    public function __construct(
251
        RegistryProcessorInterface $registryProcessor,
252
        GeneratorInterface $coreConfigDataUidGenerator,
253
        Collection $systemLoggers,
254
        EmitterInterface $emitter
255
    ) {
256
        $this->emitter = $emitter;
257
        $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...
258
        $this->registryProcessor = $registryProcessor;
259
        $this->coreConfigDataUidGenerator = $coreConfigDataUidGenerator;
260
    }
261
262
    /**
263
     * Return's the event emitter instance.
264
     *
265
     * @return \League\Event\EmitterInterface The event emitter instance
266
     */
267
    public function getEmitter()
268
    {
269
        return $this->emitter;
270
    }
271
272
    /**
273
     * Set's the name of the file to import
274
     *
275
     * @param string $filename The filename
276
     *
277
     * @return void
278
     */
279
    public function setFilename($filename)
280
    {
281
        $this->filename = $filename;
282
    }
283
284
    /**
285
     * Return's the name of the file to import.
286
     *
287
     * @return string The filename
288
     */
289
    public function getFilename()
290
    {
291
        return $this->filename;
292
    }
293
294
    /**
295
     * Set's the actual line number.
296
     *
297
     * @param integer $lineNumber The line number
298
     *
299
     * @return void
300
     */
301
    public function setLineNumber($lineNumber)
302
    {
303
        $this->lineNumber = $lineNumber;
304
    }
305
306
    /**
307
     * Return's the actual line number.
308
     *
309
     * @return integer The line number
310
     */
311
    public function getLineNumber()
312
    {
313
        return $this->lineNumber;
314
    }
315
316
    /**
317
     * Return's the default callback mappings.
318
     *
319
     * @return array The default callback mappings
320
     */
321
    public function getDefaultCallbackMappings()
322
    {
323
        return array();
324
    }
325
326
    /**
327
     * Tries to format the passed value to a valid date with format 'Y-m-d H:i:s'.
328
     * If the passed value is NOT a valid date, NULL will be returned.
329
     *
330
     * @param string $value The value to format
331
     *
332
     * @return string|null The formatted date or NULL if the date is not valid
333
     */
334
    public function formatDate($value)
335
    {
336
        return $this->getDateConverter()->convert($value);
337
    }
338
339
    /**
340
     * Extracts the elements of the passed value by exploding them
341
     * with the also passed delimiter.
342
     *
343
     * @param string      $value     The value to extract
344
     * @param string|null $delimiter The delimiter used to extrace the elements
345
     *
346
     * @return array The exploded values
347
     */
348
    public function explode($value, $delimiter = null)
349
    {
350
        return $this->getImportAdapter()->explode($value, $delimiter);
351
    }
352
353
    /**
354
     * Queries whether or not debug mode is enabled or not, default is TRUE.
355
     *
356
     * @return boolean TRUE if debug mode is enabled, else FALSE
357
     */
358
    public function isDebugMode()
359
    {
360
        return $this->getConfiguration()->isDebugMode();
361
    }
362
363
    /**
364
     * Return's the subject's execution context configuration.
365
     *
366
     * @return \TechDivision\Import\Configuration\ExecutionContextConfigurationInterface The execution context configuration to use
367
     */
368
    public function getExecutionContext()
369
    {
370
        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...
371
    }
372
373
    /**
374
     * Set's the subject configuration.
375
     *
376
     * @param \TechDivision\Import\Configuration\SubjectConfigurationInterface $configuration The subject configuration
377
     *
378
     * @return void
379
     */
380
    public function setConfiguration(SubjectConfigurationInterface $configuration)
381
    {
382
        $this->configuration = $configuration;
383
    }
384
385
    /**
386
     * Return's the subject configuration.
387
     *
388
     * @return \TechDivision\Import\Configuration\SubjectConfigurationInterface The subject configuration
389
     */
390
    public function getConfiguration()
391
    {
392
        return $this->configuration;
393
    }
394
395
    /**
396
     * Set's the import adapter instance.
397
     *
398
     * @param \TechDivision\Import\Adapter\ImportAdapterInterface $importAdapter The import adapter instance
399
     *
400
     * @return void
401
     */
402
    public function setImportAdapter(ImportAdapterInterface $importAdapter)
403
    {
404
        $this->importAdapter = $importAdapter;
405
    }
406
407
    /**
408
     * Return's the import adapter instance.
409
     *
410
     * @return \TechDivision\Import\Adapter\ImportAdapterInterface The import adapter instance
411
     */
412
    public function getImportAdapter()
413
    {
414
        return $this->importAdapter;
415
    }
416
417
    /**
418
     * Return's the RegistryProcessor instance to handle the running threads.
419
     *
420
     * @return \TechDivision\Import\Services\RegistryProcessorInterface The registry processor instance
421
     */
422
    public function getRegistryProcessor()
423
    {
424
        return $this->registryProcessor;
425
    }
426
427
    /**
428
     * Set's the unique serial for this import process.
429
     *
430
     * @param string $serial The unique serial
431
     *
432
     * @return void
433
     */
434
    public function setSerial($serial)
435
    {
436
        $this->serial = $serial;
437
    }
438
439
    /**
440
     * Return's the unique serial for this import process.
441
     *
442
     * @return string The unique serial
443
     */
444
    public function getSerial()
445
    {
446
        return $this->serial;
447
    }
448
449
    /**
450
     * Return's the source date format to use.
451
     *
452
     * @return string The source date format
453
     */
454
    public function getSourceDateFormat()
455
    {
456
        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...
457
    }
458
459
    /**
460
     * Return's the multiple field delimiter character to use, default value is comma (,).
461
     *
462
     * @return string The multiple field delimiter character
463
     */
464
    public function getMultipleFieldDelimiter()
465
    {
466
        return $this->getConfiguration()->getMultipleFieldDelimiter();
467
    }
468
469
    /**
470
     * Return's the multiple value delimiter character to use, default value is comma (|).
471
     *
472
     * @return string The multiple value delimiter character
473
     */
474
    public function getMultipleValueDelimiter()
475
    {
476
        return $this->getConfiguration()->getMultipleValueDelimiter();
477
    }
478
479
    /**
480
     * Intializes the previously loaded global data for exactly one bunch.
481
     *
482
     * @param string $serial The serial of the actual import
483
     *
484
     * @return void
485
     */
486
    public function setUp($serial)
487
    {
488
489
        // load the status of the actual import
490
        $status = $this->getRegistryProcessor()->getAttribute(RegistryKeys::STATUS);
491
492
        // load the global data, if prepared initially
493
        if (isset($status[RegistryKeys::GLOBAL_DATA])) {
494
            $this->stores = $status[RegistryKeys::GLOBAL_DATA][RegistryKeys::STORES];
495
            $this->defaultStore = $status[RegistryKeys::GLOBAL_DATA][RegistryKeys::DEFAULT_STORE];
496
            $this->storeWebsites  = $status[RegistryKeys::GLOBAL_DATA][RegistryKeys::STORE_WEBSITES];
497
            $this->rootCategories = $status[RegistryKeys::GLOBAL_DATA][RegistryKeys::ROOT_CATEGORIES];
498
            $this->coreConfigData = $status[RegistryKeys::GLOBAL_DATA][RegistryKeys::CORE_CONFIG_DATA];
499
        }
500
501
        // merge the callback mappings with the mappings from the child instance
502
        $this->callbackMappings = array_merge($this->callbackMappings, $this->getDefaultCallbackMappings());
503
504
        // merge the header mappings with the values found in the configuration
505
        $this->headerMappings = array_merge($this->headerMappings, $this->getConfiguration()->getHeaderMappings());
506
507
        // load the available callbacks from the configuration
508
        $availableCallbacks = $this->getConfiguration()->getCallbacks();
509
510
        // merge the callback mappings the the one from the configuration file
511
        foreach ($availableCallbacks as $callbackMappings) {
512
            foreach ($callbackMappings as $attributeCode => $mappings) {
513
                // write a log message, that default callback configuration will
514
                // be overwritten with the one from the configuration file
515
                if (isset($this->callbackMappings[$attributeCode])) {
516
                    $this->getSystemLogger()->notice(
517
                        sprintf('Now override callback mappings for attribute %s with values found in configuration file', $attributeCode)
518
                    );
519
                }
520
521
                // override the attributes callbacks
522
                $this->callbackMappings[$attributeCode] = $mappings;
523
            }
524
        }
525
    }
526
527
    /**
528
     * Clean up the global data after importing the variants.
529
     *
530
     * @param string $serial The serial of the actual import
531
     *
532
     * @return void
533
     */
534
    public function tearDown($serial)
535
    {
536
537
        // load the registry processor
538
        $registryProcessor = $this->getRegistryProcessor();
539
540
        // update the source directory for the next subject
541
        $registryProcessor->mergeAttributesRecursive(
542
            RegistryKeys::STATUS,
543
            array(
544
                RegistryKeys::SOURCE_DIRECTORY => $newSourceDir = $this->getNewSourceDir($serial),
545
                RegistryKeys::FILES => array($this->getFilename() => array(RegistryKeys::STATUS => 1))
546
            )
547
        );
548
549
        // log a debug message with the new source directory
550
        $this->getSystemLogger()->debug(
551
            sprintf('Subject %s successfully updated source directory to %s', get_class($this), $newSourceDir)
552
        );
553
    }
554
555
    /**
556
     * Return's the target directory for the artefact export.
557
     *
558
     * @return string The target directory for the artefact export
559
     */
560
    public function getTargetDir()
561
    {
562
        return $this->getNewSourceDir($this->getSerial());
563
    }
564
565
    /**
566
     * Return's the next source directory, which will be the target directory
567
     * of this subject, in most cases.
568
     *
569
     * @param string $serial The serial of the actual import
570
     *
571
     * @return string The new source directory
572
     */
573
    public function getNewSourceDir($serial)
574
    {
575
        return sprintf('%s/%s', $this->getConfiguration()->getTargetDir(), $serial);
576
    }
577
578
    /**
579
     * Register the passed observer with the specific type.
580
     *
581
     * @param \TechDivision\Import\Observers\ObserverInterface $observer The observer to register
582
     * @param string                                           $type     The type to register the observer with
583
     *
584
     * @return void
585
     */
586
    public function registerObserver(ObserverInterface $observer, $type)
587
    {
588
589
        // query whether or not the array with the callbacks for the
590
        // passed type has already been initialized, or not
591
        if (!isset($this->observers[$type])) {
592
            $this->observers[$type] = array();
593
        }
594
595
        // append the callback with the instance of the passed type
596
        $this->observers[$type][] = $observer;
597
    }
598
599
    /**
600
     * Register the passed callback with the specific type.
601
     *
602
     * @param \TechDivision\Import\Callbacks\CallbackInterface $callback The subject to register the callbacks for
603
     * @param string                                           $type     The type to register the callback with
604
     *
605
     * @return void
606
     */
607
    public function registerCallback(CallbackInterface $callback, $type)
608
    {
609
610
        // query whether or not the array with the callbacks for the
611
        // passed type has already been initialized, or not
612
        if (!isset($this->callbacks[$type])) {
613
            $this->callbacks[$type] = array();
614
        }
615
616
        // append the callback with the instance of the passed type
617
        $this->callbacks[$type][] = $callback;
618
    }
619
620
    /**
621
     * Return's the array with callbacks for the passed type.
622
     *
623
     * @param string $type The type of the callbacks to return
624
     *
625
     * @return array The callbacks
626
     */
627
    public function getCallbacksByType($type)
628
    {
629
630
        // initialize the array for the callbacks
631
        $callbacks = array();
632
633
        // query whether or not callbacks for the type are available
634
        if (isset($this->callbacks[$type])) {
635
            $callbacks = $this->callbacks[$type];
636
        }
637
638
        // return the array with the type's callbacks
639
        return $callbacks;
640
    }
641
642
    /**
643
     * Return's the array with the available observers.
644
     *
645
     * @return array The observers
646
     */
647
    public function getObservers()
648
    {
649
        return $this->observers;
650
    }
651
652
    /**
653
     * Return's the array with the available callbacks.
654
     *
655
     * @return array The callbacks
656
     */
657
    public function getCallbacks()
658
    {
659
        return $this->callbacks;
660
    }
661
662
    /**
663
     * Return's the callback mappings for this subject.
664
     *
665
     * @return array The array with the subject's callback mappings
666
     */
667
    public function getCallbackMappings()
668
    {
669
        return $this->callbackMappings;
670
    }
671
672
    /**
673
     * Imports the content of the file with the passed filename.
674
     *
675
     *
676
     * @param string $serial   The serial of the actual import
677
     * @param string $filename The filename to process
678
     *
679
     * @return void
680
     * @throws \Exception Is thrown, if the import can't be processed
681
     */
682
    public function import($serial, $filename)
683
    {
684
685
        try {
686
            // initialize the serial/filename
687
            $this->setSerial($serial);
688
            $this->setFilename($filename);
689
690
            // invoke the events that has to be fired before the artfact will be processed
691
            $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...
692
693
            // load the system logger instance
694
            $systemLogger = $this->getSystemLogger();
695
696
            // prepare the flag filenames
697
            $inProgressFilename = sprintf('%s.inProgress', $filename);
698
            $importedFilename = sprintf('%s.imported', $filename);
699
            $failedFilename = sprintf('%s.failed', $filename);
700
701
            // query whether or not the file has already been imported
702
            if ($this->isFile($failedFilename) ||
703
                $this->isFile($importedFilename) ||
704
                $this->isFile($inProgressFilename)
705
            ) {
706
                // log a debug message and exit
707
                $systemLogger->debug(sprintf('Import running, found inProgress file %s', $inProgressFilename));
708
                return;
709
            }
710
711
            // flag file as in progress
712
            $this->touch($inProgressFilename);
713
714
            // track the start time
715
            $startTime = microtime(true);
716
717
            // initialize the last time we've logged the counter with the processed rows per minute
718
            $this->lastLog = time();
719
720
            // log a message that the file has to be imported
721
            $systemLogger->info(sprintf('Now start processing file %s', $filename));
722
723
            // let the adapter process the file
724
            $this->getImportAdapter()->import(array($this, 'importRow'), $filename);
725
726
            // track the time needed for the import in seconds
727
            $endTime = microtime(true) - $startTime;
728
729
            // log a message that the file has successfully been imported
730
            $systemLogger->info(sprintf('Successfully processed file %s with %d lines in %f s', $filename, $this->lineNumber, $endTime));
731
732
            // rename flag file, because import has been successfull
733
            if ($this->getConfiguration()->isCreatingImportedFile()) {
734
                $this->rename($inProgressFilename, $importedFilename);
735
            } else {
736
                $this->getFilesystemAdapter()->delete($inProgressFilename);
737
            }
738
739
            // invoke the events that has to be fired when the artfact has been successfully processed
740
            $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...
741
        } catch (\Exception $e) {
742
            // rename the flag file, because import failed and write the stack trace
743
            $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...
744
            $this->write($failedFilename, $e->__toString());
745
746
            // invoke the events that has to be fired when the artfact can't be processed
747
            $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...
748
749
            // do not wrap the exception if not already done
750
            if ($e instanceof WrappedColumnException) {
751
                throw $e;
752
            }
753
754
            // else wrap and throw the exception
755
            throw $this->wrapException(array(), $e);
756
        }
757
    }
758
759
    /**
760
     * Imports the passed row into the database. If the import failed, the exception
761
     * will be catched and logged, but the import process will be continued.
762
     *
763
     * @param array $row The row with the data to be imported
764
     *
765
     * @return void
766
     */
767
    public function importRow(array $row)
768
    {
769
770
        // initialize the row
771
        $this->row = $row;
772
773
        // raise the line number and reset the skip row flag
774
        $this->lineNumber++;
775
        $this->skipRow = false;
776
777
        // invoke the events that has to be fired before the artfact's row will be processed
778
        $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...
779
780
        // initialize the headers with the columns from the first line
781
        if (sizeof($this->headers) === 0) {
782
            foreach ($this->row as $value => $key) {
783
                $this->headers[$this->mapAttributeCodeByHeaderMapping($key)] = $value;
784
            }
785
            return;
786
        }
787
788
        // load the available observers
789
        $availableObservers = $this->getObservers();
790
791
        // process the observers
792
        foreach ($availableObservers as $observers) {
793
            // invoke the pre-import/import and post-import observers
794
            /** @var \TechDivision\Import\Observers\ObserverInterface $observer */
795
            foreach ($observers as $observer) {
796
                // query whether or not we have to skip the row
797
                if ($this->skipRow) {
798
                    // log a debug message with the actual line nr/file information
799
                    $this->getSystemLogger()->warning(
800
                        $this->appendExceptionSuffix(
801
                            sprintf(
802
                                'Skip processing operation "%s" after observer "%s"',
803
                                implode(' > ', $this->getConfiguration()->getConfiguration()->getOperationNames()),
804
                                get_class($observer)
805
                            )
806
                        )
807
                    );
808
809
                    // skip the row
810
                    break 2;
811
                }
812
813
                // if not, set the subject and process the observer
814
                if ($observer instanceof ObserverInterface) {
815
                    $this->row = $observer->handle($this);
816
                }
817
            }
818
        }
819
820
        // query whether or not a minute has been passed
821
        if ($this->lastLog < time() - 60) {
822
            // log the number processed rows per minute
823
            $this->getSystemLogger()->info(
824
                sprintf(
825
                    'Successfully processed "%d (%d)" rows per minute of file "%s"',
826
                    $this->lineNumber - $this->lastLineNumber,
827
                    $this->lineNumber,
828
                    $this->getFilename()
829
                )
830
            );
831
832
            // reset the last log time and the line number
833
            $this->lastLog = time();
834
            $this->lastLineNumber = $this->lineNumber;
835
        }
836
837
        // log a debug message with the actual line nr/file information
838
        $this->getSystemLogger()->debug(
839
            $this->appendExceptionSuffix(
840
                sprintf(
841
                    'Successfully processed operation "%s"',
842
                    implode(' > ', $this->getConfiguration()->getConfiguration()->getOperationNames())
843
                )
844
            )
845
        );
846
847
        // invoke the events that has to be fired when the artfact's row has been successfully processed
848
        $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...
849
    }
850
851
    /**
852
     * Queries whether or not that the subject needs an OK file to be processed.
853
     *
854
     * @return boolean TRUE if the subject needs an OK file, else FALSE
855
     */
856
    public function isOkFileNeeded()
857
    {
858
        return $this->getConfiguration()->isOkFileNeeded();
859
    }
860
861
    /**
862
     * Return's the default store.
863
     *
864
     * @return array The default store
865
     */
866
    public function getDefaultStore()
867
    {
868
        return $this->defaultStore;
869
    }
870
871
    /**
872
     * Return's the default store view code.
873
     *
874
     * @return array The default store view code
875
     */
876
    public function getDefaultStoreViewCode()
877
    {
878
        return $this->defaultStore[MemberNames::CODE];
879
    }
880
881
    /**
882
     * Set's the store view code the create the product/attributes for.
883
     *
884
     * @param string $storeViewCode The store view code
885
     *
886
     * @return void
887
     */
888
    public function setStoreViewCode($storeViewCode)
889
    {
890
        $this->storeViewCode = $storeViewCode;
891
    }
892
893
    /**
894
     * Return's the store view code the create the product/attributes for.
895
     *
896
     * @param string|null $default The default value to return, if the store view code has not been set
897
     *
898
     * @return string The store view code
899
     */
900
    public function getStoreViewCode($default = null)
901
    {
902
903
        // return the store view code, if available
904
        if ($this->storeViewCode !== null) {
905
            return $this->storeViewCode;
906
        }
907
908
        // if NOT and a default code is available
909
        if ($default !== null) {
910
            // return the default value
911
            return $default;
912
        }
913
914
        // return the default store view code
915
        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...
916
    }
917
918
    /**
919
     * Prepare's the store view code in the subject. If the store_view_code row doesn't contain
920
     * any value, the default code of the default store view will be set.
921
     *
922
     * @return void
923
     */
924
    public function prepareStoreViewCode()
925
    {
926
927
        // re-set the store view code
928
        $this->setStoreViewCode(null);
929
930
        // initialize the store view code
931
        if ($storeViewCode = $this->getValue(ColumnKeys::STORE_VIEW_CODE)) {
932
            $this->setStoreViewCode($storeViewCode);
933
        }
934
    }
935
936
    /**
937
     * Return's the store ID of the store with the passed store view code
938
     *
939
     * @param string $storeViewCode The store view code to return the store ID for
940
     *
941
     * @return integer The ID of the store with the passed ID
942
     * @throws \Exception Is thrown, if the store with the actual code is not available
943
     */
944
    public function getStoreId($storeViewCode)
945
    {
946
947
        // query whether or not, the requested store is available
948
        if (isset($this->stores[$storeViewCode])) {
949
            return (integer) $this->stores[$storeViewCode][MemberNames::STORE_ID];
950
        }
951
952
        // throw an exception, if not
953
        throw new \Exception(
954
            sprintf(
955
                'Found invalid store view code %s in file %s on line %d',
956
                $storeViewCode,
957
                $this->getFilename(),
958
                $this->getLineNumber()
959
            )
960
        );
961
    }
962
963
    /**
964
     * Return's the store ID of the actual row, or of the default store
965
     * if no store view code is set in the CSV file.
966
     *
967
     * @param string|null $default The default store view code to use, if no store view code is set in the CSV file
968
     *
969
     * @return integer The ID of the actual store
970
     * @throws \Exception Is thrown, if the store with the actual code is not available
971
     */
972
    public function getRowStoreId($default = null)
973
    {
974
975
        // initialize the default store view code, if not passed
976
        if ($default === null) {
977
            $default = $this->getDefaultStoreViewCode();
978
        }
979
980
        // load the store view code the create the product/attributes for
981
        return $this->getStoreId($this->getStoreViewCode($default));
0 ignored issues
show
Bug introduced by
It seems like $default defined by $this->getDefaultStoreViewCode() on line 977 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...
982
    }
983
984
    /**
985
     * Return's the root category for the actual view store.
986
     *
987
     * @return array The store's root category
988
     * @throws \Exception Is thrown if the root category for the passed store code is NOT available
989
     */
990
    public function getRootCategory()
991
    {
992
993
        // load the actual store view code
994
        $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...
995
996
        // query weather or not we've a root category or not
997
        if (isset($this->rootCategories[$storeViewCode])) {
998
            return $this->rootCategories[$storeViewCode];
999
        }
1000
1001
        // throw an exception if the root category is NOT available
1002
        throw new \Exception(sprintf('Root category for %s is not available', $storeViewCode));
1003
    }
1004
1005
    /**
1006
     * Return's the Magento configuration value.
1007
     *
1008
     * @param string  $path    The Magento path of the requested configuration value
1009
     * @param mixed   $default The default value that has to be returned, if the requested configuration value is not set
1010
     * @param string  $scope   The scope the configuration value has been set
1011
     * @param integer $scopeId The scope ID the configuration value has been set
1012
     *
1013
     * @return mixed The configuration value
1014
     * @throws \Exception Is thrown, if nor a value can be found or a default value has been passed
1015
     */
1016
    public function getCoreConfigData($path, $default = null, $scope = ScopeKeys::SCOPE_DEFAULT, $scopeId = 0)
1017
    {
1018
1019
        // initialize the core config data
1020
        $coreConfigData = array(
1021
            MemberNames::PATH => $path,
1022
            MemberNames::SCOPE => $scope,
1023
            MemberNames::SCOPE_ID => $scopeId
1024
        );
1025
1026
        // generate the UID from the passed data
1027
        $uniqueIdentifier = $this->coreConfigDataUidGenerator->generate($coreConfigData);
1028
1029
        // iterate over the core config data and try to find the requested configuration value
1030
        if (isset($this->coreConfigData[$uniqueIdentifier])) {
1031
            return $this->coreConfigData[$uniqueIdentifier][MemberNames::VALUE];
1032
        }
1033
1034
        // query whether or not we've to query for the configuration value on fallback level 'websites' also
1035
        if ($scope === ScopeKeys::SCOPE_STORES) {
1036
            // query whether or not the website with the passed ID is available
1037
            foreach ($this->storeWebsites as $storeWebsite) {
1038
                if ($storeWebsite[MemberNames::WEBSITE_ID] === $scopeId) {
1039
                    // replace scope with 'websites' and website ID
1040
                    $coreConfigData = array_merge(
1041
                        $coreConfigData,
1042
                        array(
1043
                            MemberNames::SCOPE    => ScopeKeys::SCOPE_WEBSITES,
1044
                            MemberNames::SCOPE_ID => $storeWebsite[MemberNames::WEBSITE_ID]
1045
                        )
1046
                    );
1047
1048
                    // generate the UID from the passed data, merged with the 'websites' scope and ID
1049
                    $uniqueIdentifier = $this->coreConfigDataUidGenerator->generate($coreConfigData);
1050
1051
                    // query whether or not, the configuration value on 'websites' level
1052 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...
1053
                        return $this->coreConfigData[$uniqueIdentifier][MemberNames::VALUE];
1054
                    }
1055
                }
1056
            }
1057
        }
1058
1059
        // replace scope with 'default' and scope ID '0'
1060
        $coreConfigData = array_merge(
1061
            $coreConfigData,
1062
            array(
1063
                MemberNames::SCOPE    => ScopeKeys::SCOPE_DEFAULT,
1064
                MemberNames::SCOPE_ID => 0
1065
            )
1066
        );
1067
1068
        // generate the UID from the passed data, merged with the 'default' scope and ID 0
1069
        $uniqueIdentifier = $this->coreConfigDataUidGenerator->generate($coreConfigData);
1070
1071
        // query whether or not, the configuration value on 'default' level
1072 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...
1073
            return $this->coreConfigData[$uniqueIdentifier][MemberNames::VALUE];
1074
        }
1075
1076
        // if not, return the passed default value
1077
        if ($default !== null) {
1078
            return $default;
1079
        }
1080
1081
        // throw an exception if no value can be found
1082
        // in the Magento configuration
1083
        throw new \Exception(
1084
            sprintf(
1085
                'Can\'t find a value for configuration "%s-%s-%d" in "core_config_data"',
1086
                $path,
1087
                $scope,
1088
                $scopeId
1089
            )
1090
        );
1091
    }
1092
1093
    /**
1094
     * Resolve the original column name for the passed one.
1095
     *
1096
     * @param string $columnName The column name that has to be resolved
1097
     *
1098
     * @return string|null The original column name
1099
     */
1100
    public function resolveOriginalColumnName($columnName)
1101
    {
1102
1103
        // try to load the original data
1104
        $originalData = $this->getOriginalData();
1105
1106
        // query whether or not original data is available
1107
        if (isset($originalData[ColumnKeys::ORIGINAL_COLUMN_NAMES])) {
1108
            // query whether or not the original column name is available
1109
            if (isset($originalData[ColumnKeys::ORIGINAL_COLUMN_NAMES][$columnName])) {
1110
                return $originalData[ColumnKeys::ORIGINAL_COLUMN_NAMES][$columnName];
1111
            }
1112
1113
            // query whether or a wildcard column name is available
1114
            if (isset($originalData[ColumnKeys::ORIGINAL_COLUMN_NAMES]['*'])) {
1115
                return $originalData[ColumnKeys::ORIGINAL_COLUMN_NAMES]['*'];
1116
            }
1117
        }
1118
1119
        // return the original column name
1120
        return $columnName;
1121
    }
1122
1123
    /**
1124
     * Return's the original data if available, or an empty array.
1125
     *
1126
     * @return array The original data
1127
     */
1128
    public function getOriginalData()
1129
    {
1130
1131
        // initialize the array for the original data
1132
        $originalData = array();
1133
1134
        // query whether or not the column contains original data
1135
        if ($this->hasOriginalData()) {
1136
            // unerialize the original data from the column
1137
            $originalData = unserialize($this->row[$this->headers[ColumnKeys::ORIGINAL_DATA]]);
1138
        }
1139
1140
        // return an empty array, if not
1141
        return $originalData;
1142
    }
1143
1144
    /**
1145
     * Query's whether or not the actual column contains original data like
1146
     * filename, line number and column names.
1147
     *
1148
     * @return boolean TRUE if the actual column contains origin data, else FALSE
1149
     */
1150
    public function hasOriginalData()
1151
    {
1152
        return isset($this->headers[ColumnKeys::ORIGINAL_DATA]) && isset($this->row[$this->headers[ColumnKeys::ORIGINAL_DATA]]);
1153
    }
1154
1155
    /**
1156
     * Wraps the passed exeception into a new one by trying to resolve the original filname,
1157
     * line number and column names and use it for a detailed exception message.
1158
     *
1159
     * @param array      $columnNames The column names that should be resolved and wrapped
1160
     * @param \Exception $parent      The exception we want to wrap
1161
     * @param string     $className   The class name of the exception type we want to wrap the parent one
1162
     *
1163
     * @return \Exception the wrapped exception
1164
     */
1165
    public function wrapException(
1166
        array $columnNames = array(),
1167
        \Exception $parent = null,
1168
        $className = '\TechDivision\Import\Exceptions\WrappedColumnException'
1169
    ) {
1170
1171
        // initialize the message
1172
        $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...
1173
1174
        // query whether or not has been a result of invalid data of a previous column of a CSV file
1175
        if ($this->hasOriginalData()) {
1176
            // load the original data
1177
            $originalData = $this->getOriginalData();
1178
1179
            // replace old filename and line number of the original message
1180
            $message = $this->appendExceptionSuffix(
1181
                $this->stripExceptionSuffix($message),
1182
                $originalData[ColumnKeys::ORIGINAL_FILENAME],
1183
                $originalData[ColumnKeys::ORIGINAL_LINE_NUMBER]
1184
            );
1185
        } else {
1186
            // append filename and line number to the original message
1187
            $message = $this->appendExceptionSuffix(
1188
                $this->stripExceptionSuffix($message),
1189
                $this->filename,
1190
                $this->lineNumber
1191
            );
1192
        }
1193
1194
        // query whether or not, column names has been passed
1195
        if (sizeof($columnNames) > 0) {
1196
            // prepare the original column names
1197
            $originalColumnNames = array();
1198
            foreach ($columnNames as $columnName) {
1199
                $originalColumnNames[] = $this->resolveOriginalColumnName($columnName);
1200
            }
1201
1202
            // append the column information
1203
            $message = sprintf('%s in column(s) %s', $message, implode(', ', $originalColumnNames));
1204
        }
1205
1206
        // create a new exception and wrap the parent one
1207
        return new $className($message, null, $parent);
1208
    }
1209
1210
    /**
1211
     * Strip's the exception suffix containing filename and line number from the
1212
     * passed message.
1213
     *
1214
     * @param string $message The message to strip the exception suffix from
1215
     *
1216
     * @return mixed The message without the exception suffix
1217
     */
1218
    public function stripExceptionSuffix($message)
1219
    {
1220
        return str_replace($this->appendExceptionSuffix(), '', $message);
1221
    }
1222
1223
    /**
1224
     * Append's the exception suffix containing filename and line number to the
1225
     * passed message. If no message has been passed, only the suffix will be
1226
     * returned
1227
     *
1228
     * @param string|null $message    The message to append the exception suffix to
1229
     * @param string|null $filename   The filename used to create the suffix
1230
     * @param string|null $lineNumber The line number used to create the suffx
1231
     *
1232
     * @return string The message with the appended exception suffix
1233
     */
1234
    public function appendExceptionSuffix($message = null, $filename = null, $lineNumber = null)
1235
    {
1236
1237
        // query whether or not a filename has been passed
1238
        if ($filename === null) {
1239
            $filename = $this->getFilename();
1240
        }
1241
1242
        // query whether or not a line number has been passed
1243
        if ($lineNumber === null) {
1244
            $lineNumber = $this->getLineNumber();
1245
        }
1246
1247
        // if no message has been passed, only return the suffix
1248
        if ($message === null) {
1249
            return sprintf(' in file %s on line %d', $filename, $lineNumber);
1250
        }
1251
1252
        // concatenate the message with the suffix and return it
1253
        return sprintf('%s in file %s on line %d', $message, $filename, $lineNumber);
1254
    }
1255
1256
    /**
1257
     * Raises the value for the counter with the passed key by one.
1258
     *
1259
     * @param mixed $counterName The name of the counter to raise
1260
     *
1261
     * @return integer The counter's new value
1262
     */
1263
    public function raiseCounter($counterName)
1264
    {
1265
1266
        // raise the counter with the passed name
1267
        return $this->getRegistryProcessor()->raiseCounter(
1268
            RegistryKeys::STATUS,
1269
            $counterName
1270
        );
1271
    }
1272
1273
    /**
1274
     * Merge the passed array into the status of the actual import.
1275
     *
1276
     * @param array $status The status information to be merged
1277
     *
1278
     * @return void
1279
     */
1280
    public function mergeAttributesRecursive(array $status)
1281
    {
1282
1283
        // merge the passed status
1284
        $this->getRegistryProcessor()->mergeAttributesRecursive(
1285
            RegistryKeys::STATUS,
1286
            $status
1287
        );
1288
    }
1289
1290
    /**
1291
     * Return's the entity type code to be used.
1292
     *
1293
     * @return string The entity type code to be used
1294
     */
1295
    public function getEntityTypeCode()
1296
    {
1297
1298
        // load the configuration specific entity type code from the plugin configuration
1299
        $entityTypeCode = $this->getExecutionContext()->getEntityTypeCode();
1300
1301
        // try to map the entity type code
1302
        if (isset($this->entityTypeCodeMappings[$entityTypeCode])) {
1303
            $entityTypeCode = $this->entityTypeCodeMappings[$entityTypeCode];
1304
        }
1305
1306
        // return the (mapped) entity type code
1307
        return $entityTypeCode;
1308
    }
1309
}
1310