Completed
Pull Request — master (#62)
by Tim
28:18
created

Simple::getPidFilename()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 2
Bugs 0 Features 1
Metric Value
c 2
b 0
f 1
dl 0
loc 4
ccs 0
cts 2
cp 0
rs 10
cc 1
eloc 2
nc 1
nop 0
crap 2
1
<?php
2
3
/**
4
 * TechDivision\Import\Cli\Simple
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-cli-simple
18
 * @link      http://www.techdivision.com
19
 */
20
21
namespace TechDivision\Import\Cli;
22
23
use Rhumsaa\Uuid\Uuid;
24
use Monolog\Logger;
25
use Psr\Log\LogLevel;
26
use Symfony\Component\Console\Input\InputInterface;
27
use Symfony\Component\Console\Output\OutputInterface;
28
use Symfony\Component\Console\Helper\FormatterHelper;
29
use TechDivision\Import\Utils\LoggerKeys;
30
use TechDivision\Import\Utils\RegistryKeys;
31
use TechDivision\Import\ApplicationInterface;
32
use TechDivision\Import\ConfigurationInterface;
33
use TechDivision\Import\Configuration\PluginConfigurationInterface;
34
use TechDivision\Import\Services\ImportProcessorInterface;
35
use TechDivision\Import\Services\RegistryProcessorInterface;
36
use TechDivision\Import\Cli\Exceptions\LineNotFoundException;
37
use TechDivision\Import\Cli\Exceptions\FileNotFoundException;
38
39
/**
40
 * The M2IF - Console Tool implementation.
41
 *
42
 * This is a example console tool implementation that should give developers an impression
43
 * on how the M2IF could be used to implement their own Magento 2 importer.
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-cli-simple
49
 * @link      http://www.techdivision.com
50
 */
51
class Simple implements ApplicationInterface
52
{
53
54
    /**
55
     * The default style to write messages to the symfony console.
56
     *
57
     * @var string
58
     */
59
    const DEFAULT_STYLE = 'info';
60
61
    /**
62
     * The TechDivision company name as ANSI art.
63
     *
64
     * @var string
65
     */
66
    protected $ansiArt = ' _______        _     _____  _       _     _
67
|__   __|      | |   |  __ \(_)     (_)   (_)
68
   | | ___  ___| |__ | |  | |___   ___ ___ _  ___  _ __
69
   | |/ _ \/ __| \'_ \| |  | | \ \ / / / __| |/ _ \| \'_ \
70
   | |  __/ (__| | | | |__| | |\ V /| \__ \ | (_) | | | |
71
   |_|\___|\___|_| |_|_____/|_| \_/ |_|___/_|\___/|_| |_|
72
';
73
74
    /**
75
     * The log level => console style mapping.
76
     *
77
     * @var array
78
     */
79
    protected $logLevelStyleMapping = array(
80
        LogLevel::INFO      => 'info',
81
        LogLevel::DEBUG     => 'comment',
82
        LogLevel::ERROR     => 'error',
83
        LogLevel::ALERT     => 'error',
84
        LogLevel::CRITICAL  => 'error',
85
        LogLevel::EMERGENCY => 'error',
86
        LogLevel::WARNING   => 'error',
87
        LogLevel::NOTICE    => 'info'
88
    );
89
90
    /**
91
     * The PID for the running processes.
92
     *
93
     * @var array
94
     */
95
    protected $pid;
96
97
    /**
98
     * The actions unique serial.
99
     *
100
     * @var string
101
     */
102
    protected $serial;
103
104
    /**
105
     * The array with the system logger instances.
106
     *
107
     * @var array
108
     */
109
    protected $systemLoggers;
110
111
    /**
112
     * The RegistryProcessor instance to handle running threads.
113
     *
114
     * @var \TechDivision\Import\Services\RegistryProcessorInterface
115
     */
116
    protected $registryProcessor;
117
118
    /**
119
     * The processor to read/write the necessary import data.
120
     *
121
     * @var \TechDivision\Import\Services\ImportProcessorInterface
122
     */
123
    protected $importProcessor;
124
125
    /**
126
     * The system configuration.
127
     *
128
     * @var \TechDivision\Import\ConfigurationInterface
129
     */
130
    protected $configuration;
131
132
    /**
133
     * The input stream to read console information from.
134
     *
135
     * @var \Symfony\Component\Console\Input\InputInterface
136
     */
137
    protected $input;
138
139
    /**
140
     * The output stream to write console information to.
141
     *
142
     * @var \Symfony\Component\Console\Output\OutputInterface
143
     */
144
    protected $output;
145
146
    /**
147
     * The plugins to be processed.
148
     *
149
     * @var array
150
     */
151
    protected $plugins = array();
152
153
    /**
154
     * The flag that stop's processing the operation.
155
     *
156
     * @var boolean
157
     */
158
    protected $stopped = false;
159
160
    /**
161
     * The constructor to initialize the instance.
162
     *
163
     * @param \TechDivision\Import\Services\RegistryProcessorInterface $registryProcessor The registry processor instance
164
     * @param \TechDivision\Import\Services\ImportProcessorInterface   $importProcessor   The import processor instance
165
     * @param \TechDivision\Import\ConfigurationInterface              $configuration     The system configuration
166
     * @param \Symfony\Component\Console\Input\InputInterface          $input             An InputInterface instance
167
     * @param \Symfony\Component\Console\Output\OutputInterface        $output            An OutputInterface instance
168
     * @param array                                                    $systemLoggers     The array with the system logger instances
169
     */
170 1
    public function __construct(
171
        RegistryProcessorInterface $registryProcessor,
172
        ImportProcessorInterface $importProcessor,
173
        ConfigurationInterface $configuration,
174
        InputInterface $input,
175
        OutputInterface $output,
176
        array $systemLoggers
177
    ) {
178
179
        // register the shutdown function
180 1
        register_shutdown_function(array($this, 'shutdown'));
181
182
        // initialize the values
183 1
        $this->registryProcessor = $registryProcessor;
184 1
        $this->importProcessor = $importProcessor;
185 1
        $this->configuration = $configuration;
186 1
        $this->input = $input;
187 1
        $this->output = $output;
188 1
        $this->systemLoggers = $systemLoggers;
189 1
    }
190
191
    /**
192
     * The shutdown handler to catch fatal errors.
193
     *
194
     * This method is need to make sure, that an existing PID file will be removed
195
     * if a fatal error has been triggered.
196
     *
197
     * @return void
198
     */
199
    public function shutdown()
200
    {
201
202
        // check if there was a fatal error caused shutdown
203
        if ($lastError = error_get_last()) {
204
            // initialize error type and message
205
            $type = 0;
206
            $message = '';
207
            // extract the last error values
208
            extract($lastError);
209
            // query whether we've a fatal/user error
210
            if ($type === E_ERROR || $type === E_USER_ERROR) {
211
                // clean-up the PID file
212
                $this->unlock();
213
                // log the fatal error message
214
                $this->log($message, LogLevel::ERROR);
215
            }
216
        }
217
    }
218
219
    /**
220
     * Return's the logger with the passed name, by default the system logger.
221
     *
222
     * @param string $name The name of the requested system logger
223
     *
224
     * @return \Psr\Log\LoggerInterface The logger instance
225
     * @throws \Exception Is thrown, if the requested logger is NOT available
226
     */
227
    public function getSystemLogger($name = LoggerKeys::SYSTEM)
228
    {
229
230
        // query whether or not, the requested logger is available
231
        if (isset($this->systemLoggers[$name])) {
232
            return $this->systemLoggers[$name];
233
        }
234
235
        // throw an exception if the requested logger is NOT available
236
        throw new \Exception(sprintf('The requested logger \'%s\' is not available', $name));
237
    }
238
239
    /**
240
     * Return's the array with the system logger instances.
241
     *
242
     * @return array The logger instance
243
     */
244
    public function getSystemLoggers()
245
    {
246
        return $this->systemLoggers;
247
    }
248
249
    /**
250
     * Return's the RegistryProcessor instance to handle the running threads.
251
     *
252
     * @return \TechDivision\Import\Services\RegistryProcessor The registry processor instance
253
     */
254
    public function getRegistryProcessor()
255
    {
256
        return $this->registryProcessor;
257
    }
258
259
    /**
260
     * Return's the import processor instance.
261
     *
262
     * @return \TechDivision\Import\Services\ImportProcessorInterface The import processor instance
263
     */
264
    public function getImportProcessor()
265
    {
266
        return $this->importProcessor;
267
    }
268
269
    /**
270
     * Return's the system configuration.
271
     *
272
     * @return \TechDivision\Import\ConfigurationInterface The system configuration
273
     */
274
    public function getConfiguration()
275
    {
276
        return $this->configuration;
277
    }
278
279
    /**
280
     * Return's the input stream to read console information from.
281
     *
282
     * @return \Symfony\Component\Console\Input\InputInterface An IutputInterface instance
283
     */
284
    public function getInput()
285
    {
286
        return $this->input;
287
    }
288
289
    /**
290
     * Return's the output stream to write console information to.
291
     *
292
     * @return \Symfony\Component\Console\Output\OutputInterface An OutputInterface instance
293
     */
294 1
    public function getOutput()
295
    {
296 1
        return $this->output;
297
    }
298
299
    /**
300
     * Return's the unique serial for this import process.
301
     *
302
     * @return string The unique serial
303
     */
304
    public function getSerial()
305
    {
306
        return $this->serial;
307
    }
308
309
    /**
310
     * Persist the UUID of the actual import process to the PID file.
311
     *
312
     * @return void
313
     * @throws \Exception Is thrown, if the PID can not be added
314
     */
315
    public function lock()
316
    {
317
318
        // query whether or not, the PID has already been set
319
        if ($this->pid === $this->getSerial()) {
320
            return;
321
        }
322
323
        // if not, initialize the PID
324
        $this->pid = $this->getSerial();
0 ignored issues
show
Documentation Bug introduced by
It seems like $this->getSerial() of type string is incompatible with the declared type array of property $pid.

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...
325
326
        // open the PID file
327
        $fh = fopen($pidFilename = $this->getPidFilename(), 'a');
328
329
        // append the PID to the PID file
330
        if (fwrite($fh, $this->pid . PHP_EOL) === false) {
331
            throw new \Exception(sprintf('Can\'t write PID %s to PID file %s', $this->pid, $pidFilename));
332
        }
333
334
        // close the file handle
335
        fclose($fh);
336
    }
337
338
    /**
339
     * Remove's the UUID of the actual import process from the PID file.
340
     *
341
     * @return void
342
     * @throws \Exception Is thrown, if the PID can not be removed
343
     */
344
    public function unlock()
345
    {
346
        try {
347
            // remove the PID from the PID file if set
348
            if ($this->pid === $this->getSerial()) {
349
                $this->removeLineFromFile($this->pid, $this->getPidFilename());
350
            }
351
0 ignored issues
show
Coding Style introduced by
Blank line found at end of control structure
Loading history...
352
        } catch (FileNotFoundException $fnfe) {
353
            $this->getSystemLogger()->notice(sprintf('PID file %s doesn\'t exist', $this->getPidFilename()));
354
        } catch (LineNotFoundException $lnfe) {
355
            $this->getSystemLogger()->notice(sprintf('PID %s is can not be found in PID file %s', $this->pid, $this->getPidFilename()));
356
        } catch (\Exception $e) {
357
            throw new \Exception(sprintf('Can\'t remove PID %s from PID file %s', $this->pid, $this->getPidFilename()), null, $e);
358
        }
359
    }
360
361
    /**
362
     * Remove's the passed line from the file with the passed name.
363
     *
364
     * @param string $line     The line to be removed
365
     * @param string $filename The name of the file the line has to be removed
366
     *
367
     * @return void
368
     * @throws \Exception Is thrown, if the file doesn't exists, the line is not found or can not be removed
369
     */
370
    public function removeLineFromFile($line, $filename)
371
    {
372
373
        // query whether or not the filename
374
        if (!file_exists($filename)) {
375
            throw new FileNotFoundException(sprintf('File %s doesn\' exists', $filename));
376
        }
377
378
        // open the PID file
379
        $fh = fopen($filename, 'r+');
380
381
        // initialize the array for the PIDs found in the PID file
382
        $lines = array();
383
384
        // initialize the flag if the line has been found
385
        $found = false;
386
387
        // read the lines with the PIDs from the PID file
388
        while (($buffer = fgets($fh, 4096)) !== false) {
389
            // remove the new line
390
            $buffer = trim($buffer, PHP_EOL);
391
            // if the line is the one to be removed, ignore the line
392
            if ($line === $buffer) {
393
                $found = true;
394
                continue;
395
            }
396
397
            // add the found PID to the array
398
            $lines[] = $buffer;
399
        }
400
401
        // query whether or not, we found the line
402
        if (!$found) {
403
            throw new LineNotFoundException(sprintf('Line %s can not be found in file %s', $line, $filename));
404
        }
405
406
        // if there are NO more lines, delete the file
407
        if (sizeof($lines) === 0) {
408
            fclose($fh);
409
            unlink($filename);
410
            return;
411
        }
412
413
        // empty the file and rewind the file pointer
414
        ftruncate($fh, 0);
415
        rewind($fh);
416
417
        // append the existing lines to the file
418
        foreach ($lines as $ln) {
419
            if (fwrite($fh, $ln . PHP_EOL) === false) {
420
                throw new \Exception(sprintf('Can\'t write %s to file %s', $ln, $filename));
421
            }
422
        }
423
424
        // finally close the file
425
        fclose($fh);
426
    }
427
428
    /**
429
     * Process the given operation.
430
     *
431
     * @return void
432
     * @throws \Exception Is thrown if the operation can't be finished successfully
433
     */
434
    public function process()
435
    {
436
437
        try {
438
            // track the start time
439
            $startTime = microtime(true);
440
441
            // start the transaction
442
            $this->getImportProcessor()->getConnection()->beginTransaction();
443
444
            // prepare the global data for the import process
445
            $this->setUp();
446
447
            // process the plugins defined in the configuration
448
            foreach ($this->getConfiguration()->getPlugins() as $pluginConfiguration) {
449
                // query whether or not the operation has been stopped
450
                if ($this->isStopped()) {
451
                    break;
452
                }
453
                // process the plugin if not
454
                $this->pluginFactory($pluginConfiguration)->process();
455
            }
456
457
            // tear down the  instance
458
            $this->tearDown();
459
460
            // commit the transaction
461
            $this->getImportProcessor()->getConnection()->commit();
462
463
            // track the time needed for the import in seconds
464
            $endTime = microtime(true) - $startTime;
465
466
            // log a message that import has been finished
467
            $this->log(
468
                sprintf(
469
                    'Successfully finished import with serial %s in %f s',
470
                    $this->getSerial(),
471
                    $endTime
472
                ),
473
                LogLevel::INFO
474
            );
475
0 ignored issues
show
Coding Style introduced by
Blank line found at end of control structure
Loading history...
476
        } catch (\Exception $e) {
477
            // tear down
478
            $this->tearDown();
479
480
            // rollback the transaction
481
            $this->getImportProcessor()->getConnection()->rollBack();
482
483
            // finally, if a PID has been set (because CSV files has been found),
484
            // remove it from the PID file to unlock the importer
485
            $this->unlock();
486
487
            // track the time needed for the import in seconds
488
            $endTime = microtime(true) - $startTime;
489
490
            // log a message that the file import failed
491
            foreach ($this->systemLoggers as $systemLogger) {
492
                $systemLogger->error($e->__toString());
493
            }
494
495
            // log a message that import has been finished
496
            $this->getSystemLogger()->info(
497
                sprintf(
498
                    'Can\'t finish import with serial %s in %f s',
499
                    $this->getSerial(),
500
                    $endTime
501
                )
502
            );
503
504
            // re-throw the exception
505
            throw $e;
506
        }
507
    }
508
509
    /**
510
     * Stop processing the operation.
511
     *
512
     * @param string $reason The reason why the operation has been stopped
513
     *
514
     * @return void
515
     */
516
    public function stop($reason)
517
    {
518
519
        // log a message that the operation has been stopped
520
        $this->log($reason, LogLevel::INFO);
521
522
        // stop processing the plugins by setting the flag to TRUE
523
        $this->stopped = true;
524
    }
525
526
    /**
527
     * Return's TRUE if the operation has been stopped, else FALSE.
528
     *
529
     * @return boolean TRUE if the process has been stopped, else FALSE
530
     */
531
    public function isStopped()
532
    {
533
        return $this->stopped;
534
    }
535
536
    /**
537
     * Factory method to create new plugin instances.
538
     *
539
     * @param \TechDivision\Import\Configuration\PluginConfigurationInterface $pluginConfiguration The plugin configuration instance
540
     *
541
     * @return object The plugin instance
542
     */
543
    protected function pluginFactory(PluginConfigurationInterface $pluginConfiguration)
544
    {
545
546
        // load the plugin class name
547
        $className = $pluginConfiguration->getClassName();
548
549
        // initialize and return the plugin instance
550
        return new $className($this, $pluginConfiguration);
551
    }
552
553
    /**
554
     * Lifecycle callback that will be inovked before the
555
     * import process has been started.
556
     *
557
     * @return void
558
     */
559
    protected function setUp()
560
    {
561
562
        // generate the serial for the new job
563
        $this->serial = Uuid::uuid4()->__toString();
564
565
        // query whether or not an import is running AND an existing PID has to be ignored
566
        if (file_exists($pidFilename = $this->getPidFilename()) && !$this->getConfiguration()->isIgnorePid()) {
567
            throw new \Exception(sprintf('At least one import process is already running (check PID: %s)', $pidFilename));
568
        } elseif (file_exists($pidFilename = $this->getPidFilename()) && $this->getConfiguration()->isIgnorePid()) {
569
            $this->log(sprintf('At least one import process is already running (PID: %s)', $pidFilename), LogLevel::WARNING);
570
        }
571
572
        // write the TechDivision ANSI art icon to the console
573
        $this->log($this->ansiArt);
574
575
        // log the debug information, if debug mode is enabled
576
        if ($this->getConfiguration()->isDebugMode()) {
577
            // log the system's PHP configuration
578
            $this->log(sprintf('PHP version: %s', phpversion()), LogLevel::DEBUG);
579
            $this->log('-------------------- Loaded Extensions -----------------------', LogLevel::DEBUG);
580
            $this->log(implode(', ', $loadedExtensions = get_loaded_extensions()), LogLevel::DEBUG);
581
            $this->log('--------------------------------------------------------------', LogLevel::DEBUG);
582
583
            // write a warning for low performance, if XDebug extension is activated
584
            if (in_array('xdebug', $loadedExtensions)) {
585
                $this->log('Low performance exptected, as result of enabled XDebug extension!', LogLevel::WARNING);
586
            }
587
        }
588
589
        // log a message that import has been started
590
        $this->log(
591
            sprintf(
592
                'Now start import with serial %s (operation: %s)',
593
                $this->getSerial(),
594
                $this->getConfiguration()->getOperationName()
595
            ),
596
            LogLevel::INFO
597
        );
598
599
        // initialize the status
600
        $status = array(
601
            RegistryKeys::STATUS => 1,
602
            RegistryKeys::BUNCHES => 0,
603
            RegistryKeys::SOURCE_DIRECTORY => $this->getConfiguration()->getSourceDir()
604
        );
605
606
        // append it to the registry
607
        $this->getRegistryProcessor()->setAttribute($this->getSerial(), $status);
608
    }
609
610
    /**
611
     * Lifecycle callback that will be inovked after the
612
     * import process has been finished.
613
     *
614
     * @return void
615
     */
616
    protected function tearDown()
617
    {
618
        $this->getRegistryProcessor()->removeAttribute($this->getSerial());
619
    }
620
621
    /**
622
     * Simple method that writes the passed method the the console and the
623
     * system logger, if configured and a log level has been passed.
624
     *
625
     * @param string $msg      The message to log
626
     * @param string $logLevel The log level to use
627
     *
628
     * @return void
629
     */
630
    protected function log($msg, $logLevel = null)
631
    {
632
633
        // initialize the formatter helper
634
        $helper = new FormatterHelper();
635
636
        // map the log level to the console style
637
        $style = $this->mapLogLevelToStyle($logLevel);
638
639
        // format the message, according to the passed log level and write it to the console
640
        $this->getOutput()->writeln($logLevel ? $helper->formatBlock($msg, $style) : $msg);
641
642
        // log the message if a log level has been passed
643
        if ($logLevel && $systemLogger = $this->getSystemLogger()) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $logLevel of type string|null is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
644
            $systemLogger->log($logLevel, $msg);
645
        }
646
    }
647
648
    /**
649
     * Map's the passed log level to a valid symfony console style.
650
     *
651
     * @param string $logLevel The log level to map
652
     *
653
     * @return string The apropriate symfony console style
654
     */
655
    protected function mapLogLevelToStyle($logLevel)
656
    {
657
658
        // query whether or not the log level is mapped
659
        if (isset($this->logLevelStyleMapping[$logLevel])) {
660
            return $this->logLevelStyleMapping[$logLevel];
661
        }
662
663
        // return the default style => info
664
        return Simple::DEFAULT_STYLE;
665
    }
666
667
    /**
668
     * Return's the PID filename to use.
669
     *
670
     * @return string The PID filename
671
     */
672
    protected function getPidFilename()
673
    {
674
        return $this->getConfiguration()->getPidFilename();
675
    }
676
}
677