Completed
Push — master ( 82e5a1...bffc67 )
by Tim
9s
created

AbstractSubject::resolveOriginalColumnName()   B

Complexity

Conditions 4
Paths 4

Size

Total Lines 22
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 20

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 22
ccs 0
cts 13
cp 0
rs 8.9197
cc 4
eloc 8
nc 4
nop 1
crap 20
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 Psr\Log\LoggerInterface;
24
use Goodby\CSV\Import\Standard\Lexer;
25
use Goodby\CSV\Import\Standard\LexerConfig;
26
use Goodby\CSV\Import\Standard\Interpreter;
27
use TechDivision\Import\Utils\ScopeKeys;
28
use TechDivision\Import\Utils\LoggerKeys;
29
use TechDivision\Import\Utils\ColumnKeys;
30
use TechDivision\Import\Utils\MemberNames;
31
use TechDivision\Import\Utils\RegistryKeys;
32
use TechDivision\Import\Utils\Generators\GeneratorInterface;
33
use TechDivision\Import\Services\RegistryProcessor;
34
use TechDivision\Import\Callbacks\CallbackInterface;
35
use TechDivision\Import\Observers\ObserverInterface;
36
use TechDivision\Import\Exceptions\WrappedColumnException;
37
use TechDivision\Import\Services\RegistryProcessorInterface;
38
use TechDivision\Import\Configuration\SubjectConfigurationInterface;
39
40
/**
41
 * An abstract subject implementation.
42
 *
43
 * @author    Tim Wagner <[email protected]>
44
 * @copyright 2016 TechDivision GmbH <[email protected]>
45
 * @license   http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
46
 * @link      https://github.com/techdivision/import
47
 * @link      http://www.techdivision.com
48
 */
49
abstract class AbstractSubject implements SubjectInterface
50
{
51
52
    /**
53
     * The trait that provides basic filesystem handling functionality.
54
     *
55
     * @var TechDivision\Import\Subjects\FilesystemTrait
56
     */
57
    use FilesystemTrait;
58
59
    /**
60
     * The system configuration.
61
     *
62
     * @var \TechDivision\Import\Configuration\SubjectConfigurationInterface
63
     */
64
    protected $configuration;
65
66
    /**
67
     * The array with the system logger instances.
68
     *
69
     * @var array
70
     */
71
    protected $systemLoggers = array();
72
73
    /**
74
     * The RegistryProcessor instance to handle running threads.
75
     *
76
     * @var \TechDivision\Import\Services\RegistryProcessorInterface
77
     */
78
    protected $registryProcessor;
79
80
    /**
81
     * The actions unique serial.
82
     *
83
     * @var string
84
     */
85
    protected $serial;
86
87
    /**
88
     * The name of the file to be imported.
89
     *
90
     * @var string
91
     */
92
    protected $filename;
93
94
    /**
95
     * Array with the subject's observers.
96
     *
97
     * @var array
98
     */
99
    protected $observers = array();
100
101
    /**
102
     * Array with the subject's callbacks.
103
     *
104
     * @var array
105
     */
106
    protected $callbacks = array();
107
108
    /**
109
     * The subject's callback mappings.
110
     *
111
     * @var array
112
     */
113
    protected $callbackMappings = array();
114
115
    /**
116
     * Contain's the column names from the header line.
117
     *
118
     * @var array
119
     */
120
    protected $headers = array();
121
122
    /**
123
     * The actual line number.
124
     *
125
     * @var integer
126
     */
127
    protected $lineNumber = 0;
128
129
    /**
130
     * The actual operation name.
131
     *
132
     * @var string
133
     */
134
    protected $operationName ;
135
136
    /**
137
     * The flag that stop's overserver execution on the actual row.
138
     *
139
     * @var boolean
140
     */
141
    protected $skipRow = false;
142
143
    /**
144
     * The available root categories.
145
     *
146
     * @var array
147
     */
148
    protected $rootCategories = array();
149
150
    /**
151
     * The Magento configuration.
152
     *
153
     * @var array
154
     */
155
    protected $coreConfigData = array();
156
157
    /**
158
     * The available stores.
159
     *
160
     * @var array
161
     */
162
    protected $stores = array();
163
164
    /**
165
     * The default store.
166
     *
167
     * @var array
168
     */
169
    protected $defaultStore;
170
171
    /**
172
     * The store view code the create the product/attributes for.
173
     *
174
     * @var string
175
     */
176
    protected $storeViewCode;
177
178
    /**
179
     * The UID generator for the core config data.
180
     *
181
     * @var \TechDivision\Import\Utils\Generators\GeneratorInterface
182
     */
183
    protected $coreConfigDataUidGenerator;
184
185
    /**
186
     * The actual row.
187
     *
188
     * @var array
189
     */
190
    protected $row = array();
191
192
    /**
193
     * Initialize the subject instance.
194
     *
195
     * @param \TechDivision\Import\Configuration\SubjectConfigurationInterface $configuration              The subject configuration instance
196
     * @param \TechDivision\Import\Services\RegistryProcessorInterface         $registryProcessor          The registry processor instance
197
     * @param \TechDivision\Import\Utils\Generators\GeneratorInterface         $coreConfigDataUidGenerator The UID generator for the core config data
198
     * @param array                                                            $systemLoggers              The array with the system loggers instances
199
     */
200
    public function __construct(
201
        SubjectConfigurationInterface $configuration,
202
        RegistryProcessorInterface $registryProcessor,
203
        GeneratorInterface $coreConfigDataUidGenerator,
204
        array $systemLoggers
205
    ) {
206
        $this->configuration = $configuration;
207
        $this->registryProcessor = $registryProcessor;
208
        $this->coreConfigDataUidGenerator = $coreConfigDataUidGenerator;
209
        $this->systemLoggers = $systemLoggers;
210
    }
211
212
    /**
213
     * Return's the default callback mappings.
214
     *
215
     * @return array The default callback mappings
216
     */
217
    public function getDefaultCallbackMappings()
218
    {
219
        return array();
220
    }
221
222
    /**
223
     * Return's the actual row.
224
     *
225
     * @return array The actual row
226
     */
227
    public function getRow()
228
    {
229
        return $this->row;
230
    }
231
232
    /**
233
     * Stop's observer execution on the actual row.
234
     *
235
     * @return void
236
     */
237
    public function skipRow()
238
    {
239
        $this->skipRow = true;
240
    }
241
242
    /**
243
     * Return's the actual line number.
244
     *
245
     * @return integer The line number
246
     */
247
    public function getLineNumber()
248
    {
249
        return $this->lineNumber;
250
    }
251
252
    /**
253
     * Return's the actual operation name.
254
     *
255
     * @return string
256
     */
257
    public function getOperationName()
258
    {
259
        return $this->operationName;
260
    }
261
262
    /**
263
     * Set's the array containing header row.
264
     *
265
     * @param array $headers The array with the header row
266
     *
267
     * @return void
268
     */
269
    public function setHeaders(array $headers)
270
    {
271
        $this->headers = $headers;
272
    }
273
274
    /**
275
     * Return's the array containing header row.
276
     *
277
     * @return array The array with the header row
278
     */
279
    public function getHeaders()
280
    {
281
        return $this->headers;
282
    }
283
284
    /**
285
     * Queries whether or not the header with the passed name is available.
286
     *
287
     * @param string $name The header name to query
288
     *
289
     * @return boolean TRUE if the header is available, else FALSE
290
     */
291
    public function hasHeader($name)
292
    {
293
        return isset($this->headers[$name]);
294
    }
295
296
    /**
297
     * Return's the header value for the passed name.
298
     *
299
     * @param string $name The name of the header to return the value for
300
     *
301
     * @return mixed The header value
302
     * \InvalidArgumentException Is thrown, if the header with the passed name is NOT available
303
     */
304
    public function getHeader($name)
305
    {
306
307
        // query whether or not, the header is available
308
        if (isset($this->headers[$name])) {
309
            return $this->headers[$name];
310
        }
311
312
        // throw an exception, if not
313
        throw new \InvalidArgumentException(sprintf('Header %s is not available', $name));
314
    }
315
316
    /**
317
     * Add's the header with the passed name and position, if not NULL.
318
     *
319
     * @param string $name The header name to add
320
     *
321
     * @return integer The new headers position
322
     */
323
    public function addHeader($name)
324
    {
325
326
        // add the header
327
        $this->headers[$name] = $position = sizeof($this->headers);
328
329
        // return the new header's position
330
        return $position;
331
    }
332
333
    /**
334
     * Query whether or not a value for the column with the passed name exists.
335
     *
336
     * @param string $name The column name to query for a valid value
337
     *
338
     * @return boolean TRUE if the value is set, else FALSE
339
     */
340 View Code Duplication
    public function hasValue($name)
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...
341
    {
342
343
        // query whether or not the header is available
344
        if ($this->hasHeader($name)) {
345
            // load the key for the row
346
            $headerValue = $this->getHeader($name);
347
348
            // query whether the rows column has a vaild value
349
            return (isset($this->row[$headerValue]) && $this->row[$headerValue] != '');
350
        }
351
352
        // return FALSE if not
353
        return false;
354
    }
355
356
    /**
357
     * Set the value in the passed column name.
358
     *
359
     * @param string $name  The column name to set the value for
360
     * @param mixed  $value The value to set
361
     *
362
     * @return void
363
     */
364
    public function setValue($name, $value)
365
    {
366
        $this->row[$this->getHeader($name)] = $value;
367
    }
368
369
    /**
370
     * Resolve's the value with the passed colum name from the actual row. If a callback will
371
     * be passed, the callback will be invoked with the found value as parameter. If
372
     * the value is NULL or empty, the default value will be returned.
373
     *
374
     * @param string        $name     The name of the column to return the value for
375
     * @param mixed|null    $default  The default value, that has to be returned, if the row's value is empty
376
     * @param callable|null $callback The callback that has to be invoked on the value, e. g. to format it
377
     *
378
     * @return mixed|null The, almost formatted, value
379
     */
380 View Code Duplication
    public function getValue($name, $default = null, callable $callback = null)
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...
381
    {
382
383
        // initialize the value
384
        $value = null;
385
386
        // query whether or not the header is available
387
        if ($this->hasHeader($name)) {
388
            // load the header value
389
            $headerValue = $this->getHeader($name);
390
            // query wheter or not, the value with the requested key is available
391
            if ((isset($this->row[$headerValue]) && $this->row[$headerValue] != '')) {
392
                $value = $this->row[$headerValue];
393
            }
394
        }
395
396
        // query whether or not, a callback has been passed
397
        if ($value != null && is_callable($callback)) {
398
            $value = call_user_func($callback, $value);
399
        }
400
401
        // query whether or not
402
        if ($value == null && $default !== null) {
403
            $value = $default;
404
        }
405
406
        // return the value
407
        return $value;
408
    }
409
410
    /**
411
     * Tries to format the passed value to a valid date with format 'Y-m-d H:i:s'.
412
     * If the passed value is NOT a valid date, NULL will be returned.
413
     *
414
     * @param string|null $value The value to format
415
     *
416
     * @return string The formatted date
417
     */
418
    public function formatDate($value)
419
    {
420
421
        // create a DateTime instance from the passed value
422
        if ($dateTime = \DateTime::createFromFormat($this->getSourceDateFormat(), $value)) {
423
            return $dateTime->format('Y-m-d H:i:s');
424
        }
425
426
        // return NULL, if the passed value is NOT a valid date
427
        return null;
428
    }
429
430
    /**
431
     * Extracts the elements of the passed value by exploding them
432
     * with the also passed delimiter.
433
     *
434
     * @param string      $value     The value to extract
435
     * @param string|null $delimiter The delimiter used to extrace the elements
436
     *
437
     * @return array The exploded values
438
     */
439
    public function explode($value, $delimiter = null)
440
    {
441
442
        // load the default multiple field delimiter
443
        if ($delimiter === null) {
444
            $delimiter = $this->getMultipleFieldDelimiter();
445
        }
446
447
        // explode and return the array with the values, by using the delimiter
448
        return explode($delimiter, $value);
449
    }
450
451
    /**
452
     * Queries whether or not debug mode is enabled or not, default is TRUE.
453
     *
454
     * @return boolean TRUE if debug mode is enabled, else FALSE
455
     */
456
    public function isDebugMode()
457
    {
458
        return $this->getConfiguration()->isDebugMode();
459
    }
460
461
    /**
462
     * Return's the system configuration.
463
     *
464
     * @return \TechDivision\Import\Configuration\SubjectConfigurationInterface The system configuration
465
     */
466
    public function getConfiguration()
467
    {
468
        return $this->configuration;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $this->configuration; (TechDivision\Import\Conf...tConfigurationInterface) is incompatible with the return type declared by the interface TechDivision\Import\Subj...rface::getConfiguration of type TechDivision\Import\Configuration\SubjectInterface.

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

Let’s take a look at an example:

class Author {
    private $name;

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

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

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

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

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

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

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

Loading history...
469
    }
470
471
    /**
472
     * Return's the logger with the passed name, by default the system logger.
473
     *
474
     * @param string $name The name of the requested system logger
475
     *
476
     * @return \Psr\Log\LoggerInterface The logger instance
477
     * @throws \Exception Is thrown, if the requested logger is NOT available
478
     */
479
    public function getSystemLogger($name = LoggerKeys::SYSTEM)
480
    {
481
482
        // query whether or not, the requested logger is available
483
        if (isset($this->systemLoggers[$name])) {
484
            return $this->systemLoggers[$name];
485
        }
486
487
        // throw an exception if the requested logger is NOT available
488
        throw new \Exception(sprintf('The requested logger \'%s\' is not available', $name));
489
    }
490
491
    /**
492
     * Return's the array with the system logger instances.
493
     *
494
     * @return array The logger instance
495
     */
496
    public function getSystemLoggers()
497
    {
498
        return $this->systemLoggers;
499
    }
500
501
    /**
502
     * Return's the RegistryProcessor instance to handle the running threads.
503
     *
504
     * @return \TechDivision\Import\Services\RegistryProcessorInterface The registry processor instance
505
     */
506
    public function getRegistryProcessor()
507
    {
508
        return $this->registryProcessor;
509
    }
510
511
    /**
512
     * Set's the unique serial for this import process.
513
     *
514
     * @param string $serial The unique serial
515
     *
516
     * @return void
517
     */
518
    public function setSerial($serial)
519
    {
520
        $this->serial = $serial;
521
    }
522
523
    /**
524
     * Return's the unique serial for this import process.
525
     *
526
     * @return string The unique serial
527
     */
528
    public function getSerial()
529
    {
530
        return $this->serial;
531
    }
532
533
    /**
534
     * Set's the name of the file to import
535
     *
536
     * @param string $filename The filename
537
     *
538
     * @return void
539
     */
540
    public function setFilename($filename)
541
    {
542
        $this->filename = $filename;
543
    }
544
545
    /**
546
     * Return's the name of the file to import.
547
     *
548
     * @return string The filename
549
     */
550
    public function getFilename()
551
    {
552
        return $this->filename;
553
    }
554
555
    /**
556
     * Return's the source date format to use.
557
     *
558
     * @return string The source date format
559
     */
560
    public function getSourceDateFormat()
561
    {
562
        return $this->getConfiguration()->getSourceDateFormat();
563
    }
564
565
    /**
566
     * Return's the multiple field delimiter character to use, default value is comma (,).
567
     *
568
     * @return string The multiple field delimiter character
569
     */
570
    public function getMultipleFieldDelimiter()
571
    {
572
        return $this->getConfiguration()->getMultipleFieldDelimiter();
0 ignored issues
show
Bug introduced by
The method getMultipleFieldDelimiter() 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...
573
    }
574
575
    /**
576
     * Return's the initialized PDO connection.
577
     *
578
     * @return \PDO The initialized PDO connection
579
     */
580
    public function getConnection()
581
    {
582
        return $this->getProductProcessor()->getConnection();
0 ignored issues
show
Bug introduced by
The method getProductProcessor() does not seem to exist on object<TechDivision\Impo...bjects\AbstractSubject>.

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...
583
    }
584
585
    /**
586
     * Intializes the previously loaded global data for exactly one bunch.
587
     *
588
     * @param string $serial The serial of the actual import
589
     *
590
     * @return void
591
     * @see \Importer\Csv\Actions\ProductImportAction::prepare()
592
     */
593
    public function setUp($serial)
594
    {
595
596
        // load the status of the actual import
597
        $status = $this->getRegistryProcessor()->getAttribute($serial);
598
599
        // load the global data we've prepared initially
600
        $this->stores = $status[RegistryKeys::GLOBAL_DATA][RegistryKeys::STORES];
601
        $this->defaultStore = $status[RegistryKeys::GLOBAL_DATA][RegistryKeys::DEFAULT_STORE];
602
        $this->rootCategories = $status[RegistryKeys::GLOBAL_DATA][RegistryKeys::ROOT_CATEGORIES];
603
        $this->coreConfigData = $status[RegistryKeys::GLOBAL_DATA][RegistryKeys::CORE_CONFIG_DATA];
604
605
        // initialize the operation name
606
        $this->operationName = $this->getConfiguration()->getConfiguration()->getOperationName();
607
608
        // merge the callback mappings with the mappings from the child instance
609
        $this->callbackMappings = array_merge($this->callbackMappings, $this->getDefaultCallbackMappings());
610
611
        // merge the callback mappings the the one from the configuration file
612
        foreach ($this->getConfiguration()->getCallbacks() as $callbackMappings) {
613
            foreach ($callbackMappings as $attributeCode => $mappings) {
614
                // write a log message, that default callback configuration will
615
                // be overwritten with the one from the configuration file
616
                if (isset($this->callbackMappings[$attributeCode])) {
617
                    $this->getSystemLogger()->notice(
618
                        sprintf('Now override callback mappings for attribute %s with values found in configuration file', $attributeCode)
619
                    );
620
                }
621
622
                // override the attributes callbacks
623
                $this->callbackMappings[$attributeCode] = $mappings;
624
            }
625
        }
626
    }
627
628
    /**
629
     * Clean up the global data after importing the variants.
630
     *
631
     * @param string $serial The serial of the actual import
632
     *
633
     * @return void
634
     */
635
    public function tearDown($serial)
636
    {
637
638
        // load the registry processor
639
        $registryProcessor = $this->getRegistryProcessor();
640
641
        // update the source directory for the next subject
642
        $registryProcessor->mergeAttributesRecursive(
643
            $serial,
644
            array(RegistryKeys::SOURCE_DIRECTORY => $this->getNewSourceDir($serial))
645
        );
646
647
        // log a debug message with the new source directory
648
        $this->getSystemLogger()->debug(
649
            sprintf('Subject %s successfully updated source directory to %s', __CLASS__, $this->getNewSourceDir($serial))
650
        );
651
    }
652
653
    /**
654
     * Return's the next source directory, which will be the target directory
655
     * of this subject, in most cases.
656
     *
657
     * @param string $serial The serial of the actual import
658
     *
659
     * @return string The new source directory
660
     */
661
    protected function getNewSourceDir($serial)
662
    {
663
        return sprintf('%s/%s', $this->getConfiguration()->getTargetDir(), $serial);
664
    }
665
666
    /**
667
     * Register the passed observer with the specific type.
668
     *
669
     * @param \TechDivision\Import\Observers\ObserverInterface $observer The observer to register
670
     * @param string                                           $type     The type to register the observer with
671
     *
672
     * @return void
673
     */
674
    public function registerObserver(ObserverInterface $observer, $type)
675
    {
676
677
        // query whether or not the array with the callbacks for the
678
        // passed type has already been initialized, or not
679
        if (!isset($this->observers[$type])) {
680
            $this->observers[$type] = array();
681
        }
682
683
        // append the callback with the instance of the passed type
684
        $this->observers[$type][] = $observer;
685
    }
686
687
    /**
688
     * Register the passed callback with the specific type.
689
     *
690
     * @param \TechDivision\Import\Callbacks\CallbackInterface $callback The subject to register the callbacks for
691
     * @param string                                           $type     The type to register the callback with
692
     *
693
     * @return void
694
     */
695
    public function registerCallback(CallbackInterface $callback, $type)
696
    {
697
698
        // query whether or not the array with the callbacks for the
699
        // passed type has already been initialized, or not
700
        if (!isset($this->callbacks[$type])) {
701
            $this->callbacks[$type] = array();
702
        }
703
704
        // append the callback with the instance of the passed type
705
        $this->callbacks[$type][] = $callback;
706
    }
707
708
    /**
709
     * Return's the array with callbacks for the passed type.
710
     *
711
     * @param string $type The type of the callbacks to return
712
     *
713
     * @return array The callbacks
714
     */
715
    public function getCallbacksByType($type)
716
    {
717
718
        // initialize the array for the callbacks
719
        $callbacks = array();
720
721
        // query whether or not callbacks for the type are available
722
        if (isset($this->callbacks[$type])) {
723
            $callbacks = $this->callbacks[$type];
724
        }
725
726
        // return the array with the type's callbacks
727
        return $callbacks;
728
    }
729
730
    /**
731
     * Return's the array with the available observers.
732
     *
733
     * @return array The observers
734
     */
735
    public function getObservers()
736
    {
737
        return $this->observers;
738
    }
739
740
    /**
741
     * Return's the array with the available callbacks.
742
     *
743
     * @return array The callbacks
744
     */
745
    public function getCallbacks()
746
    {
747
        return $this->callbacks;
748
    }
749
750
    /**
751
     * Return's the callback mappings for this subject.
752
     *
753
     * @return array The array with the subject's callback mappings
754
     */
755
    public function getCallbackMappings()
756
    {
757
        return $this->callbackMappings;
758
    }
759
760
    /**
761
     * Imports the content of the file with the passed filename.
762
     *
763
     *
764
     * @param string $serial   The serial of the actual import
765
     * @param string $filename The filename to process
766
     *
767
     * @return void
768
     * @throws \Exception Is thrown, if the import can't be processed
769
     */
770
    public function import($serial, $filename)
771
    {
772
773
        try {
774
            // stop processing, if the filename doesn't match
775
            if (!$this->match($filename)) {
776
                return;
777
            }
778
779
            // load the system logger instance
780
            $systemLogger = $this->getSystemLogger();
781
782
            // prepare the flag filenames
783
            $inProgressFilename = sprintf('%s.inProgress', $filename);
784
            $importedFilename = sprintf('%s.imported', $filename);
785
            $failedFilename = sprintf('%s.failed', $filename);
786
787
            // query whether or not the file has already been imported
788
            if (is_file($failedFilename) ||
789
                is_file($importedFilename) ||
790
                is_file($inProgressFilename)
791
            ) {
792
                // log a debug message and exit
793
                $systemLogger->debug(sprintf('Import running, found inProgress file %s', $inProgressFilename));
794
                return;
795
            }
796
797
            // flag file as in progress
798
            touch($inProgressFilename);
799
800
            // track the start time
801
            $startTime = microtime(true);
802
803
            // initialize the serial/filename
804
            $this->setSerial($serial);
805
            $this->setFilename($filename);
806
807
            // load the system logger
808
            $systemLogger = $this->getSystemLogger();
809
810
            // initialize the lexer instance itself
811
            $lexer = new Lexer($this->getLexerConfig());
812
813
            // initialize the interpreter
814
            $interpreter = new Interpreter();
815
            $interpreter->addObserver(array($this, 'importRow'));
816
817
            // query whether or not we want to use the strict mode
818
            if (!$this->getConfiguration()->isStrictMode()) {
819
                $interpreter->unstrict();
820
            }
821
822
            // log a message that the file has to be imported
823
            $systemLogger->debug(sprintf('Now start importing file %s', $filename));
824
825
            // parse the CSV file to be imported
826
            $lexer->parse($filename, $interpreter);
827
828
            // track the time needed for the import in seconds
829
            $endTime = microtime(true) - $startTime;
830
831
            // log a message that the file has successfully been imported
832
            $systemLogger->debug(sprintf('Successfully imported file %s in %f s', $filename, $endTime));
833
834
            // rename flag file, because import has been successfull
835
            rename($inProgressFilename, $importedFilename);
836
0 ignored issues
show
Coding Style introduced by
Blank line found at end of control structure
Loading history...
837
        } catch (\Exception $e) {
838
            // rename the flag file, because import failed and write the stack trace
839
            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...
840
            file_put_contents($failedFilename, $e->__toString());
841
842
            // do not wrap the exception if not already done
843
            if ($e instanceof WrappedColumnException) {
844
                throw $e;
845
            }
846
847
            // else wrap and throw the exception
848
            throw $this->wrapException(array(), $e);
849
        }
850
    }
851
852
    /**
853
     * This method queries whether or not the passed filename matches
854
     * the pattern, based on the subjects configured prefix.
855
     *
856
     * @param string $filename The filename to match
857
     *
858
     * @return boolean TRUE if the filename matches, else FALSE
859
     */
860
    protected function match($filename)
861
    {
862
863
        // prepare the pattern to query whether the file has to be processed or not
864
        $pattern = sprintf('/^.*\/%s.*\\.csv$/', $this->getConfiguration()->getPrefix());
865
866
        // stop processing, if the filename doesn't match
867
        return (boolean) preg_match($pattern, $filename);
868
    }
869
870
    /**
871
     * Initialize and return the lexer configuration.
872
     *
873
     * @return \Goodby\CSV\Import\Standard\LexerConfig The lexer configuration
874
     */
875
    protected function getLexerConfig()
876
    {
877
878
        // initialize the lexer configuration
879
        $config = new LexerConfig();
880
881
        // query whether or not a delimiter character has been configured
882
        if ($delimiter = $this->getConfiguration()->getDelimiter()) {
883
            $config->setDelimiter($delimiter);
884
        }
885
886
        // query whether or not a custom escape character has been configured
887
        if ($escape = $this->getConfiguration()->getEscape()) {
888
            $config->setEscape($escape);
889
        }
890
891
        // query whether or not a custom enclosure character has been configured
892
        if ($enclosure = $this->getConfiguration()->getEnclosure()) {
893
            $config->setEnclosure($enclosure);
894
        }
895
896
        // query whether or not a custom source charset has been configured
897
        if ($fromCharset = $this->getConfiguration()->getFromCharset()) {
898
            $config->setFromCharset($fromCharset);
899
        }
900
901
        // query whether or not a custom target charset has been configured
902
        if ($toCharset = $this->getConfiguration()->getToCharset()) {
903
            $config->setToCharset($toCharset);
904
        }
905
906
        // return the lexer configuratio
907
        return $config;
908
    }
909
910
    /**
911
     * Imports the passed row into the database. If the import failed, the exception
912
     * will be catched and logged, but the import process will be continued.
913
     *
914
     * @param array $row The row with the data to be imported
915
     *
916
     * @return void
917
     */
918
    public function importRow(array $row)
919
    {
920
921
        // initialize the row
922
        $this->row = $row;
923
924
        // raise the line number and reset the skip row flag
925
        $this->lineNumber++;
926
        $this->skipRow = false;
927
928
        // initialize the headers with the columns from the first line
929
        if (sizeof($this->headers) === 0) {
930
            foreach ($this->row as $value => $key) {
931
                $this->headers[$this->mapAttributeCodeByHeaderMapping($key)] = $value;
932
            }
933
            return;
934
        }
935
936
        // process the observers
937
        foreach ($this->getObservers() as $observers) {
938
            // invoke the pre-import/import and post-import observers
939
            foreach ($observers as $observer) {
940
                // query whether or not we have to skip the row
941
                if ($this->skipRow) {
942
                    break;
943
                }
944
945
                // if not, process the next observer
946
                if ($observer instanceof ObserverInterface) {
947
                    $this->row = $observer->handle($this->row);
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface TechDivision\Import\Observers\ObserverInterface as the method handle() does only exist in the following implementations of said interface: TechDivision\Import\Obse...stractAttributeObserver, TechDivision\Import\Obse...tractFileUploadObserver, TechDivision\Import\Obse...tionalAttributeObserver, TechDivision\Import\Observers\AttributeSetObserver.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

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