Completed
Pull Request — master (#60)
by Tim
03:24
created

Simple::stop()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 9
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 9
ccs 0
cts 4
cp 0
rs 9.6666
cc 1
eloc 3
nc 1
nop 1
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 Psr\Log\LoggerInterface;
27
use Symfony\Component\Console\Input\InputInterface;
28
use Symfony\Component\Console\Output\OutputInterface;
29
use Symfony\Component\Console\Helper\FormatterHelper;
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 system logger implementation.
106
     *
107
     * @var \Psr\Log\LoggerInterface
108
     */
109
    protected $systemLogger;
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 \Psr\Log\LoggerInterface                                 $systemLogger      The system logger
164
     * @param \TechDivision\Import\Services\RegistryProcessorInterface $registryProcessor The registry processor instance
165
     * @param \TechDivision\Import\Services\ImportProcessorInterface   $importProcessor   The import processor instance
166
     * @param \TechDivision\Import\ConfigurationInterface              $configuration     The system configuration
167
     * @param \Symfony\Component\Console\Input\InputInterface          $input             An InputInterface instance
168
     * @param \Symfony\Component\Console\Output\OutputInterface        $output            An OutputInterface instance
169
     */
170 1
    public function __construct(
171
        LoggerInterface $systemLogger,
172
        RegistryProcessorInterface $registryProcessor,
173
        ImportProcessorInterface $importProcessor,
174
        ConfigurationInterface $configuration,
175
        InputInterface $input,
176
        OutputInterface $output
177
    ) {
178
179
        // register the shutdown function
180 1
        register_shutdown_function(array($this, 'shutdown'));
181
182
        // initialize the values
183 1
        $this->systemLogger = $systemLogger;
184 1
        $this->registryProcessor = $registryProcessor;
185 1
        $this->importProcessor = $importProcessor;
186 1
        $this->configuration = $configuration;
187 1
        $this->input = $input;
188 1
        $this->output = $output;
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 system logger.
221
     *
222
     * @return \Psr\Log\LoggerInterface The system logger instance
223
     */
224
    public function getSystemLogger()
225
    {
226
        return $this->systemLogger;
227
    }
228
229
    /**
230
     * Return's the RegistryProcessor instance to handle the running threads.
231
     *
232
     * @return \TechDivision\Import\Services\RegistryProcessor The registry processor instance
233
     */
234
    public function getRegistryProcessor()
235
    {
236
        return $this->registryProcessor;
237
    }
238
239
    /**
240
     * Return's the import processor instance.
241
     *
242
     * @return \TechDivision\Import\Services\ImportProcessorInterface The import processor instance
243
     */
244
    public function getImportProcessor()
245
    {
246
        return $this->importProcessor;
247
    }
248
249
    /**
250
     * Return's the system configuration.
251
     *
252
     * @return \TechDivision\Import\ConfigurationInterface The system configuration
253
     */
254
    public function getConfiguration()
255
    {
256
        return $this->configuration;
257
    }
258
259
    /**
260
     * Return's the input stream to read console information from.
261
     *
262
     * @return \Symfony\Component\Console\Input\InputInterface An IutputInterface instance
263
     */
264
    public function getInput()
265
    {
266
        return $this->input;
267
    }
268
269
    /**
270
     * Return's the output stream to write console information to.
271
     *
272
     * @return \Symfony\Component\Console\Output\OutputInterface An OutputInterface instance
273
     */
274 1
    public function getOutput()
275
    {
276 1
        return $this->output;
277
    }
278
279
    /**
280
     * Return's the unique serial for this import process.
281
     *
282
     * @return string The unique serial
283
     */
284
    public function getSerial()
285
    {
286
        return $this->serial;
287
    }
288
289
    /**
290
     * Persist the UUID of the actual import process to the PID file.
291
     *
292
     * @return void
293
     * @throws \Exception Is thrown, if the PID can not be added
294
     */
295
    public function lock()
296
    {
297
298
        // query whether or not, the PID has already been set
299
        if ($this->pid === $this->getSerial()) {
300
            return;
301
        }
302
303
        // if not, initialize the PID
304
        $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...
305
306
        // open the PID file
307
        $fh = fopen($pidFilename = $this->getPidFilename(), 'a');
308
309
        // append the PID to the PID file
310
        if (fwrite($fh, $this->pid . PHP_EOL) === false) {
311
            throw new \Exception(sprintf('Can\'t write PID %s to PID file %s', $this->pid, $pidFilename));
312
        }
313
314
        // close the file handle
315
        fclose($fh);
316
    }
317
318
    /**
319
     * Remove's the UUID of the actual import process from the PID file.
320
     *
321
     * @return void
322
     * @throws \Exception Is thrown, if the PID can not be removed
323
     */
324
    public function unlock()
325
    {
326
        try {
327
            // remove the PID from the PID file if set
328
            if ($this->pid === $this->getSerial()) {
329
                $this->removeLineFromFile($this->pid, $this->getPidFilename());
330
            }
331
0 ignored issues
show
Coding Style introduced by
Blank line found at end of control structure
Loading history...
332
        } catch (FileNotFoundException $fnfe) {
333
            $this->getSystemLogger()->notice(sprintf('PID file %s doesn\'t exist', $this->getPidFilename()));
334
        } catch (LineNotFoundException $lnfe) {
335
            $this->getSystemLogger()->notice(sprintf('PID %s is can not be found in PID file %s', $this->pid, $this->getPidFilename()));
336
        } catch (\Exception $e) {
337
            throw new \Exception(sprintf('Can\'t remove PID %s from PID file %s', $this->pid, $this->getPidFilename()), null, $e);
338
        }
339
    }
340
341
    /**
342
     * Remove's the passed line from the file with the passed name.
343
     *
344
     * @param string $line     The line to be removed
345
     * @param string $filename The name of the file the line has to be removed
346
     *
347
     * @return void
348
     * @throws \Exception Is thrown, if the file doesn't exists, the line is not found or can not be removed
349
     */
350
    public function removeLineFromFile($line, $filename)
351
    {
352
353
        // query whether or not the filename
354
        if (!file_exists($filename)) {
355
            throw new FileNotFoundException(sprintf('File %s doesn\' exists', $filename));
356
        }
357
358
        // open the PID file
359
        $fh = fopen($filename, 'r+');
360
361
        // initialize the array for the PIDs found in the PID file
362
        $lines = array();
363
364
        // initialize the flag if the line has been found
365
        $found = false;
366
367
        // read the lines with the PIDs from the PID file
368
        while (($buffer = fgets($fh, 4096)) !== false) {
369
            // remove the new line
370
            $buffer = trim($buffer, PHP_EOL);
371
            // if the line is the one to be removed, ignore the line
372
            if ($line === $buffer) {
373
                $found = true;
374
                continue;
375
            }
376
377
            // add the found PID to the array
378
            $lines[] = $buffer;
379
        }
380
381
        // query whether or not, we found the line
382
        if (!$found) {
383
            throw new LineNotFoundException(sprintf('Line %s can not be found in file %s', $line, $filename));
384
        }
385
386
        // if there are NO more lines, delete the file
387
        if (sizeof($lines) === 0) {
388
            fclose($fh);
389
            unlink($filename);
390
            return;
391
        }
392
393
        // empty the file and rewind the file pointer
394
        ftruncate($fh, 0);
395
        rewind($fh);
396
397
        // append the existing lines to the file
398
        foreach ($lines as $ln) {
399
            if (fwrite($fh, $ln . PHP_EOL) === false) {
400
                throw new \Exception(sprintf('Can\'t write %s to file %s', $ln, $filename));
401
            }
402
        }
403
404
        // finally close the file
405
        fclose($fh);
406
    }
407
408
    /**
409
     * Process the given operation.
410
     *
411
     * @return void
412
     * @throws \Exception Is thrown if the operation can't be finished successfully
413
     */
414
    public function process()
415
    {
416
417
        try {
418
            // track the start time
419
            $startTime = microtime(true);
420
421
            // start the transaction
422
            $this->getImportProcessor()->getConnection()->beginTransaction();
423
424
            // prepare the global data for the import process
425
            $this->setUp();
426
427
            // process the plugins defined in the configuration
428
            foreach ($this->getConfiguration()->getPlugins() as $pluginConfiguration) {
429
                // query whether or not the operation has been stopped
430
                if ($this->isStopped()) {
431
                    break;
432
                }
433
                // process the plugin if not
434
                $this->pluginFactory($pluginConfiguration)->process();
435
            }
436
437
            // tear down the  instance
438
            $this->tearDown();
439
440
            // commit the transaction
441
            $this->getImportProcessor()->getConnection()->commit();
442
443
            // track the time needed for the import in seconds
444
            $endTime = microtime(true) - $startTime;
445
446
            // log a message that import has been finished
447
            $this->log(
448
                sprintf(
449
                    'Successfully finished import with serial %s in %f s',
450
                    $this->getSerial(),
451
                    $endTime
452
                ),
453
                LogLevel::INFO
454
            );
455
0 ignored issues
show
Coding Style introduced by
Blank line found at end of control structure
Loading history...
456
        } catch (\Exception $e) {
457
            // tear down
458
            $this->tearDown();
459
460
            // rollback the transaction
461
            $this->getImportProcessor()->getConnection()->rollBack();
462
463
            // finally, if a PID has been set (because CSV files has been found),
464
            // remove it from the PID file to unlock the importer
465
            $this->unlock();
466
467
            // track the time needed for the import in seconds
468
            $endTime = microtime(true) - $startTime;
469
470
            // log a message that the file import failed
471
            $this->getSystemLogger()->error($e->__toString());
472
473
            // log a message that import has been finished
474
            $this->getSystemLogger()->info(
475
                sprintf(
476
                    'Can\'t finish import with serial %s in %f s',
477
                    $this->getSerial(),
478
                    $endTime
479
                )
480
            );
481
482
            // re-throw the exception
483
            throw $e;
484
        }
485
    }
486
487
    /**
488
     * Stop processing the operation.
489
     *
490
     * @param string $reason The reason why the operation has been stopped
491
     *
492
     * @return void
493
     */
494
    public function stop($reason)
495
    {
496
497
        // log a message that the operation has been stopped
498
        $this->log($reason, LogLevel::INFO);
499
500
        // stop processing the plugins by setting the flag to TRUE
501
        $this->stopped = true;
502
    }
503
504
    /**
505
     * Return's TRUE if the operation has been stopped, else FALSE.
506
     *
507
     * @return boolean TRUE if the process has been stopped, else FALSE
508
     */
509
    public function isStopped()
510
    {
511
        return $this->stopped;
512
    }
513
514
    /**
515
     * Factory method to create new plugin instances.
516
     *
517
     * @param \TechDivision\Import\Configuration\PluginConfigurationInterface $pluginConfiguration The plugin configuration instance
518
     *
519
     * @return object The plugin instance
520
     */
521
    protected function pluginFactory(PluginConfigurationInterface $pluginConfiguration)
522
    {
523
524
        // load the plugin class name
525
        $className = $pluginConfiguration->getClassName();
526
527
        // initialize and return the plugin instance
528
        return new $className($this, $pluginConfiguration);
529
    }
530
531
    /**
532
     * Lifecycle callback that will be inovked before the
533
     * import process has been started.
534
     *
535
     * @return void
536
     */
537
    protected function setUp()
538
    {
539
540
        // generate the serial for the new job
541
        $this->serial = Uuid::uuid4()->__toString();
542
543
        // query whether or not an import is running AND an existing PID has to be ignored
544
        if (file_exists($pidFilename = $this->getPidFilename()) && !$this->getConfiguration()->isIgnorePid()) {
545
            throw new \Exception(sprintf('At least one import process is already running (check PID: %s)', $pidFilename));
546
        } elseif (file_exists($pidFilename = $this->getPidFilename()) && $this->getConfiguration()->isIgnorePid()) {
547
            $this->log(sprintf('At least one import process is already running (PID: %s)', $pidFilename), LogLevel::WARNING);
548
        }
549
550
        // write the TechDivision ANSI art icon to the console
551
        $this->log($this->ansiArt);
552
553
        // log the debug information, if debug mode is enabled
554
        if ($this->getConfiguration()->isDebugMode()) {
555
            // log the system's PHP configuration
556
            $this->log(sprintf('PHP version: %s', phpversion()), LogLevel::DEBUG);
557
            $this->log('-------------------- Loaded Extensions -----------------------', LogLevel::DEBUG);
558
            $this->log(implode(', ', $loadedExtensions = get_loaded_extensions()), LogLevel::DEBUG);
559
            $this->log('--------------------------------------------------------------', LogLevel::DEBUG);
560
561
            // write a warning for low performance, if XDebug extension is activated
562
            if (in_array('xdebug', $loadedExtensions)) {
563
                $this->log('Low performance exptected, as result of enabled XDebug extension!', LogLevel::WARNING);
564
            }
565
        }
566
567
        // log a message that import has been started
568
        $this->log(
569
            sprintf(
570
                'Now start import with serial %s (operation: %s)',
571
                $this->getSerial(),
572
                $this->getConfiguration()->getOperationName()
573
            ),
574
            LogLevel::INFO
575
        );
576
577
        // initialize the status
578
        $status = array(
579
            RegistryKeys::STATUS => 1,
580
            RegistryKeys::BUNCHES => 0,
581
            RegistryKeys::SOURCE_DIRECTORY => $this->getConfiguration()->getSourceDir()
582
        );
583
584
        // append it to the registry
585
        $this->getRegistryProcessor()->setAttribute($this->getSerial(), $status);
586
    }
587
588
    /**
589
     * Lifecycle callback that will be inovked after the
590
     * import process has been finished.
591
     *
592
     * @return void
593
     */
594
    protected function tearDown()
595
    {
596
        $this->getRegistryProcessor()->removeAttribute($this->getSerial());
597
    }
598
599
    /**
600
     * Simple method that writes the passed method the the console and the
601
     * system logger, if configured and a log level has been passed.
602
     *
603
     * @param string $msg      The message to log
604
     * @param string $logLevel The log level to use
605
     *
606
     * @return void
607
     */
608
    protected function log($msg, $logLevel = null)
609
    {
610
611
        // initialize the formatter helper
612
        $helper = new FormatterHelper();
613
614
        // map the log level to the console style
615
        $style = $this->mapLogLevelToStyle($logLevel);
616
617
        // format the message, according to the passed log level and write it to the console
618
        $this->getOutput()->writeln($logLevel ? $helper->formatBlock($msg, $style) : $msg);
619
620
        // log the message if a log level has been passed
621
        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...
622
            $systemLogger->log($logLevel, $msg);
623
        }
624
    }
625
626
    /**
627
     * Map's the passed log level to a valid symfony console style.
628
     *
629
     * @param string $logLevel The log level to map
630
     *
631
     * @return string The apropriate symfony console style
632
     */
633
    protected function mapLogLevelToStyle($logLevel)
634
    {
635
636
        // query whether or not the log level is mapped
637
        if (isset($this->logLevelStyleMapping[$logLevel])) {
638
            return $this->logLevelStyleMapping[$logLevel];
639
        }
640
641
        // return the default style => info
642
        return Simple::DEFAULT_STYLE;
643
    }
644
645
    /**
646
     * Return's the PID filename to use.
647
     *
648
     * @return string The PID filename
649
     */
650
    protected function getPidFilename()
651
    {
652
        return $this->getConfiguration()->getPidFilename();
653
    }
654
}
655