Completed
Push — develop ( 57dfb2...713d02 )
by Tom
03:43
created

Application::reinit()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 8
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 8
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 6
nc 1
nop 3
1
<?php
2
3
namespace N98\Magento;
4
5
use Composer\Autoload\ClassLoader;
6
use Exception;
7
use Mage;
8
use Magento\Mtf\EntryPoint\EntryPoint;
9
use N98\Magento\Application\Config;
10
use N98\Magento\Application\ConfigurationLoader;
11
use N98\Magento\Application\Console\Events;
12
use N98\Util\AutoloadRestorer;
13
use N98\Util\Console\Helper\MagentoHelper;
14
use N98\Util\Console\Helper\TwigHelper;
15
use N98\Util\OperatingSystem;
16
use RuntimeException;
17
use Symfony\Component\Console\Application as BaseApplication;
18
use Symfony\Component\Console\Command\Command;
19
use Symfony\Component\Console\Event\ConsoleEvent;
20
use Symfony\Component\Console\Formatter\OutputFormatterStyle;
21
use Symfony\Component\Console\Helper\FormatterHelper;
22
use Symfony\Component\Console\Input\ArgvInput;
23
use Symfony\Component\Console\Input\InputDefinition;
24
use Symfony\Component\Console\Input\InputInterface;
25
use Symfony\Component\Console\Input\InputOption;
26
use Symfony\Component\Console\Output\ConsoleOutput;
27
use Symfony\Component\Console\Output\OutputInterface;
28
use Symfony\Component\EventDispatcher\EventDispatcher;
29
use UnexpectedValueException;
30
31
class Application extends BaseApplication
32
{
33
    /**
34
     * @var string
35
     */
36
    const APP_NAME = 'n98-magerun';
37
38
    /**
39
     * @var string
40
     */
41
    const APP_VERSION = '1.97.29';
42
43
    /**
44
     * @var int
45
     */
46
    const MAGENTO_MAJOR_VERSION_1 = 1;
47
48
    /**
49
     * @var int
50
     */
51
    const MAGENTO_MAJOR_VERSION_2 = 2;
52
53
    /**
54
     * @var string
55
     */
56
    private static $logo = "
57
     ___ ___
58
 _ _/ _ ( _ )___ _ __  __ _ __ _ ___ _ _ _  _ _ _
59
| ' \\_, / _ \\___| '  \\/ _` / _` / -_) '_| || | ' \\
60
|_||_/_/\\___/   |_|_|_\\__,_\\__, \\___|_|  \\_,_|_||_|
61
                           |___/
62
";
63
64
    /**
65
     * Shadow copy of the Application parent when using this concrete setAutoExit() implementation
66
     *
67
     * @see \Symfony\Component\Console\Application::$autoExit
68
     * @var bool
69
     */
70
    private $autoExitShadow = true;
71
72
    /**
73
     * @var ClassLoader
74
     */
75
    protected $autoloader;
76
77
    /**
78
     * @var Config
79
     */
80
    protected $config;
81
82
    /**
83
     * @see \N98\Magento\Application::setConfigurationLoader()
84
     * @var ConfigurationLoader
85
     */
86
    private $configurationLoaderInjected;
87
88
    /**
89
     * @var string
90
     */
91
    protected $_magentoRootFolder = null;
92
93
    /**
94
     * @var bool
95
     */
96
    protected $_magentoEnterprise = false;
97
98
    /**
99
     * @var int
100
     */
101
    protected $_magentoMajorVersion = self::MAGENTO_MAJOR_VERSION_1;
102
103
    /**
104
     * @var EntryPoint
105
     */
106
    protected $_magento2EntryPoint = null;
107
108
    /**
109
     * @var bool
110
     */
111
    protected $_isPharMode = false;
112
113
    /**
114
     * @var bool
115
     */
116
    protected $_magerunStopFileFound = false;
117
118
    /**
119
     * @var string
120
     */
121
    protected $_magerunStopFileFolder = null;
122
123
    /**
124
     * @var bool
125
     */
126
    protected $_isInitialized = false;
127
128
    /**
129
     * @var EventDispatcher
130
     */
131
    protected $dispatcher;
132
133
    /**
134
     * If root dir is set by root-dir option this flag is true
135
     *
136
     * @var bool
137
     */
138
    protected $_directRootDir = false;
139
140
    /**
141
     * @var bool
142
     */
143
    protected $_magentoDetected = false;
144
145
    /**
146
     * @param ClassLoader $autoloader
0 ignored issues
show
Documentation introduced by
Should the type for parameter $autoloader not be ClassLoader|null?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
147
     */
148
    public function __construct($autoloader = null)
149
    {
150
        $this->autoloader = $autoloader;
151
        parent::__construct(self::APP_NAME, self::APP_VERSION);
152
    }
153
154
    /**
155
     * @param bool $boolean
156
     * @return bool previous auto-exit state
157
     */
158
    public function setAutoExit($boolean)
159
    {
160
        $previous = $this->autoExitShadow;
161
        $this->autoExitShadow = $boolean;
162
        parent::setAutoExit($boolean);
163
164
        return $previous;
165
    }
166
167
    /**
168
     * @return InputDefinition
169
     */
170
    protected function getDefaultInputDefinition()
171
    {
172
        $inputDefinition = parent::getDefaultInputDefinition();
173
174
        /**
175
         * Root dir
176
         */
177
        $rootDirOption = new InputOption(
178
            '--root-dir',
179
            '',
180
            InputOption::VALUE_OPTIONAL,
181
            'Force magento root dir. No auto detection'
182
        );
183
        $inputDefinition->addOption($rootDirOption);
184
185
        /**
186
         * Skip config
187
         */
188
        $skipExternalConfig = new InputOption(
189
            '--skip-config',
190
            '',
191
            InputOption::VALUE_NONE,
192
            'Do not load any custom config.'
193
        );
194
        $inputDefinition->addOption($skipExternalConfig);
195
196
        /**
197
         * Skip root check
198
         */
199
        $skipExternalConfig = new InputOption(
200
            '--skip-root-check',
201
            '',
202
            InputOption::VALUE_NONE,
203
            'Do not check if n98-magerun runs as root'
204
        );
205
        $inputDefinition->addOption($skipExternalConfig);
206
207
        return $inputDefinition;
208
    }
209
210
    /**
211
     * Search for magento root folder
212
     *
213
     * @param InputInterface $input [optional]
0 ignored issues
show
Documentation introduced by
Should the type for parameter $input not be null|InputInterface?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
214
     * @param OutputInterface $output [optional]
0 ignored issues
show
Documentation introduced by
Should the type for parameter $output not be null|OutputInterface?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
215
     * @return void
216
     */
217
    public function detectMagento(InputInterface $input = null, OutputInterface $output = null)
218
    {
219
        // do not detect magento twice
220
        if ($this->_magentoDetected) {
221
            return;
222
        }
223
224
        if (null === $input) {
225
            $input = new ArgvInput();
226
        }
227
228
        if (null === $output) {
229
            $output = new ConsoleOutput();
230
        }
231
232
        if ($this->getMagentoRootFolder() === null) {
233
            $this->_checkRootDirOption($input);
234
            $folder = OperatingSystem::getCwd();
235
        } else {
236
            $folder = $this->getMagentoRootFolder();
237
        }
238
239
        $this->getHelperSet()->set(new MagentoHelper($input, $output), 'magento');
240
        $magentoHelper = $this->getHelperSet()->get('magento');
241
        /* @var $magentoHelper MagentoHelper */
242
        if (!$this->_directRootDir) {
243
            $subFolders = $this->config->getDetectSubFolders();
244
        } else {
245
            $subFolders = array();
246
        }
247
248
        $this->_magentoDetected = $magentoHelper->detect($folder, $subFolders);
249
        $this->_magentoRootFolder = $magentoHelper->getRootFolder();
250
        $this->_magentoEnterprise = $magentoHelper->isEnterpriseEdition();
251
        $this->_magentoMajorVersion = $magentoHelper->getMajorVersion();
252
        $this->_magerunStopFileFound = $magentoHelper->isMagerunStopFileFound();
253
        $this->_magerunStopFileFolder = $magentoHelper->getMagerunStopFileFolder();
254
    }
255
256
    /**
257
     * Add own helpers to helperset.
258
     *
259
     * @return void
260
     */
261
    protected function registerHelpers()
262
    {
263
        $helperSet = $this->getHelperSet();
264
        $config = $this->config->getConfig();
265
266
        foreach ($config['helpers'] as $helperName => $helperClass) {
267
            if (!class_exists($helperClass)) {
268
                throw new RuntimeException(
269
                    sprintf('Nonexistent helper class: "%s", check helpers configuration', $helperClass)
270
                );
271
            }
272
273
            // Twig helper needs the config-file
274
            $helper = 'N98\Util\Console\Helper\TwigHelper' === $helperClass
275
                ? new $helperClass($this->config)
276
                : new $helperClass()
277
            ;
278
            $helperSet->set($helper, $helperName);
279
        }
280
    }
281
282
    /**
283
     * @param InputInterface $input
284
     *
285
     * @return ArgvInput|InputInterface
286
     */
287
    protected function checkConfigCommandAlias(InputInterface $input)
288
    {
289
        trigger_error(__METHOD__ . ' moved, use getConfig()->checkConfigCommandAlias()', E_USER_DEPRECATED);
290
291
        return $this->config->checkConfigCommandAlias($input);
292
    }
293
294
    /**
295
     * @param Command $command
296
     */
297
    protected function registerConfigCommandAlias(Command $command)
298
    {
299
        trigger_error(__METHOD__ . ' moved, use getConfig()->registerConfigCommandAlias() instead', E_USER_DEPRECATED);
300
301
        return $this->config->registerConfigCommandAlias($command);
302
    }
303
304
    /**
305
     * Adds autoloader prefixes from user's config
306
     */
307
    protected function registerCustomAutoloaders()
308
    {
309
        trigger_error(__METHOD__ . ' moved, use getConfig()->registerCustomAutoloaders() instead', E_USER_DEPRECATED);
310
311
        $this->config->registerCustomAutoloaders($this->autoloader);
312
    }
313
314
    /**
315
     * @return bool
316
     */
317
    protected function hasCustomCommands()
318
    {
319
        trigger_error(__METHOD__ . ' moved, use config directly instead', E_USER_DEPRECATED);
320
321
        $config = $this->config->getConfig();
322
323
        return isset($config['commands']['customCommands']) && is_array($config['commands']['customCommands']);
324
    }
325
326
    /**
327
     * @return void
328
     */
329
    protected function registerCustomCommands()
330
    {
331
        trigger_error(__METHOD__ . ' moved, use getConfig()->registerCustomCommands() instead', E_USER_DEPRECATED);
332
333
        $this->config->registerCustomCommands($this);
334
    }
335
336
    /**
337
     * @param string $class
338
     * @return bool
339
     */
340
    protected function isCommandDisabled($class)
341
    {
342
        trigger_error(__METHOD__ . ' moved, use config directly instead', E_USER_DEPRECATED);
343
344
        $config = $this->config->getConfig();
345
346
        return in_array($class, $config['commands']['disabled']);
347
    }
348
349
    /**
350
     * Override standard command registration. We want alias support.
351
     *
352
     * @param Command $command
353
     *
354
     * @return Command
0 ignored issues
show
Documentation introduced by
Should the return type not be Command|null?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
355
     */
356
    public function add(Command $command)
357
    {
358
        if ($this->config) {
359
            $this->config->registerConfigCommandAlias($command);
360
        }
361
362
        return parent::add($command);
363
    }
364
365
    /**
366
     * @param bool $mode
367
     */
368
    public function setPharMode($mode)
369
    {
370
        $this->_isPharMode = $mode;
371
    }
372
373
    /**
374
     * @return bool
375
     */
376
    public function isPharMode()
377
    {
378
        return $this->_isPharMode;
379
    }
380
381
    /**
382
     * @TODO Move logic into "EventSubscriber"
383
     *
384
     * @param OutputInterface $output
385
     * @return null|false
386
     */
387
    public function checkVarDir(OutputInterface $output)
388
    {
389
        $tempVarDir = sys_get_temp_dir() . '/magento/var';
390
        if (!OutputInterface::VERBOSITY_NORMAL <= $output->getVerbosity() && !is_dir($tempVarDir)) {
391
            return;
392
        }
393
394
        $this->detectMagento(null, $output);
395
        /* If magento is not installed yet, don't check */
396
        if ($this->_magentoRootFolder === null
397
            || !file_exists($this->_magentoRootFolder . '/app/etc/local.xml')
398
        ) {
399
            return;
400
        }
401
402
        try {
403
            $this->initMagento();
404
        } catch (Exception $e) {
405
            $message = 'Cannot initialize Magento. Please check your configuration. '
406
                . 'Some n98-magerun command will not work. Got message: ';
407
            if (OutputInterface::VERBOSITY_VERY_VERBOSE <= $output->getVerbosity()) {
408
                $message .= $e->getTraceAsString();
409
            } else {
410
                $message .= $e->getMessage();
411
            }
412
            $output->writeln($message);
413
414
            return;
415
        }
416
417
        $configOptions = new \Mage_Core_Model_Config_Options();
418
        $currentVarDir = $configOptions->getVarDir();
419
420
        if ($currentVarDir == $tempVarDir) {
421
            $output->writeln(array(
422
                sprintf('<warning>Fallback folder %s is used in n98-magerun</warning>', $tempVarDir),
423
                '',
424
                'n98-magerun is using the fallback folder. If there is another folder configured for Magento, this ' .
425
                'can cause serious problems.',
426
                'Please refer to https://github.com/netz98/n98-magerun/wiki/File-system-permissions ' .
427
                'for more information.',
428
                '',
429
            ));
430
        } else {
431
            $output->writeln(array(
432
                sprintf('<warning>Folder %s found, but not used in n98-magerun</warning>', $tempVarDir),
433
                '',
434
                "This might cause serious problems. n98-magerun is using the configured var-folder " .
435
                "<comment>$currentVarDir</comment>",
436
                'Please refer to https://github.com/netz98/n98-magerun/wiki/File-system-permissions ' .
437
                'for more information.',
438
                '',
439
            ));
440
441
            return false;
442
        }
443
    }
444
445
    /**
446
     * Loads and initializes the Magento application
447
     *
448
     * @param bool $soft
449
     *
450
     * @return bool false if magento root folder is not set, true otherwise
451
     */
452
    public function initMagento($soft = false)
453
    {
454
        if ($this->getMagentoRootFolder() === null) {
455
            return false;
456
        }
457
458
        $isMagento2 = $this->_magentoMajorVersion === self::MAGENTO_MAJOR_VERSION_2;
459
        if ($isMagento2) {
460
            $this->_initMagento2();
461
        } else {
462
            $this->_initMagento1($soft);
463
        }
464
465
        return true;
466
    }
467
468
    /**
469
     * @return string
470
     */
471
    public function getHelp()
472
    {
473
        return self::$logo . parent::getHelp();
474
    }
475
476
    public function getLongVersion()
477
    {
478
        return parent::getLongVersion() . ' by <info>netz98 GmbH</info>';
479
    }
480
481
    /**
482
     * @return boolean
483
     */
484
    public function isMagentoEnterprise()
485
    {
486
        return $this->_magentoEnterprise;
487
    }
488
489
    /**
490
     * @return string
491
     */
492
    public function getMagentoRootFolder()
493
    {
494
        return $this->_magentoRootFolder;
495
    }
496
497
    /**
498
     * @param string $magentoRootFolder
499
     */
500
    public function setMagentoRootFolder($magentoRootFolder)
501
    {
502
        $this->_magentoRootFolder = $magentoRootFolder;
503
    }
504
505
    /**
506
     * @return int
507
     */
508
    public function getMagentoMajorVersion()
509
    {
510
        return $this->_magentoMajorVersion;
511
    }
512
513
    /**
514
     * @return ClassLoader
515
     */
516
    public function getAutoloader()
517
    {
518
        return $this->autoloader;
519
    }
520
521
    /**
522
     * @param ClassLoader $autoloader
523
     */
524
    public function setAutoloader(ClassLoader $autoloader)
525
    {
526
        $this->autoloader = $autoloader;
527
    }
528
529
    /**
530
     * Get config array
531
     *
532
     * Specify one key per parameter to traverse the config. Then returns null
533
     * if the path of the key(s) can not be obtained.
534
     *
535
     * @param string|int $key ... (optional)
0 ignored issues
show
Documentation introduced by
Should the type for parameter $key not be string|integer|null?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
536
     *
537
     * @return array|null
538
     */
539
    public function getConfig($key = null)
0 ignored issues
show
Unused Code introduced by
The parameter $key is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
540
    {
541
        $array = $this->config->getConfig();
542
543
        $keys = func_get_args();
544
        foreach ($keys as $key) {
545
            if (null === $key) {
546
                continue;
547
            }
548
            if (!isset($array[$key])) {
549
                return null;
550
            }
551
            $array = $array[$key];
552
        }
553
554
        return $array;
555
    }
556
557
    /**
558
     * @param array $config
559
     */
560
    public function setConfig($config)
561
    {
562
        $this->config->setConfig($config);
563
    }
564
565
    /**
566
     * @return boolean
567
     */
568
    public function isMagerunStopFileFound()
569
    {
570
        return $this->_magerunStopFileFound;
571
    }
572
573
    /**
574
     * Runs the current application with possible command aliases
575
     *
576
     * @param InputInterface $input An Input instance
577
     * @param OutputInterface $output An Output instance
578
     *
579
     * @return integer 0 if everything went fine, or an error code
580
     */
581
    public function doRun(InputInterface $input, OutputInterface $output)
582
    {
583
        $event = new Application\Console\Event($this, $input, $output);
584
        $this->dispatcher->dispatch(Events::RUN_BEFORE, $event);
585
586
        /**
587
         * only for compatibility to old versions.
588
         */
589
        $event = new ConsoleEvent(new Command('dummy'), $input, $output);
590
        $this->dispatcher->dispatch('console.run.before', $event);
591
592
        $input = $this->config->checkConfigCommandAlias($input);
593
        if ($output instanceof ConsoleOutput) {
594
            $this->checkVarDir($output->getErrorOutput());
595
        }
596
597
        return parent::doRun($input, $output);
598
    }
599
600
    /**
601
     * @param InputInterface $input [optional]
0 ignored issues
show
Documentation introduced by
Should the type for parameter $input not be null|InputInterface?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
602
     * @param OutputInterface $output [optional]
0 ignored issues
show
Documentation introduced by
Should the type for parameter $output not be null|OutputInterface?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
603
     *
604
     * @return int
605
     */
606
    public function run(InputInterface $input = null, OutputInterface $output = null)
607
    {
608
        if (null === $input) {
609
            $input = new ArgvInput();
610
        }
611
612
        if (null === $output) {
613
            $output = new ConsoleOutput();
614
        }
615
        $this->_addOutputStyles($output);
616
        if ($output instanceof ConsoleOutput) {
617
            $this->_addOutputStyles($output->getErrorOutput());
618
        }
619
620
        $this->configureIO($input, $output);
621
622
        try {
623
            $this->init(array(), $input, $output);
624
        } catch (Exception $e) {
625
            $output = new ConsoleOutput();
626
            $this->renderException($e, $output->getErrorOutput());
627
        }
628
629
        $return = parent::run($input, $output);
630
631
        // Fix for no return values -> used in interactive shell to prevent error output
632
        if ($return === null) {
633
            return 0;
634
        }
635
636
        return $return;
637
    }
638
639
    /**
640
     * @param array $initConfig [optional]
641
     * @param InputInterface $input [optional]
0 ignored issues
show
Documentation introduced by
Should the type for parameter $input not be null|InputInterface?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
642
     * @param OutputInterface $output [optional]
0 ignored issues
show
Documentation introduced by
Should the type for parameter $output not be null|OutputInterface?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
643
     *
644
     * @return void
645
     */
646
    public function init(array $initConfig = array(), InputInterface $input = null, OutputInterface $output = null)
647
    {
648
        if ($this->_isInitialized) {
649
            return;
650
        }
651
652
        // Suppress DateTime warnings
653
        date_default_timezone_set(@date_default_timezone_get());
654
655
        // Initialize EventDispatcher early
656
        $this->dispatcher = new EventDispatcher();
657
        $this->setDispatcher($this->dispatcher);
658
659
        $input = $input ?: new ArgvInput();
660
        $output = $output ?: new ConsoleOutput();
661
662
        if (null !== $this->config) {
663
            throw new UnexpectedValueException(sprintf('Config already initialized'));
664
        }
665
666
        $loadExternalConfig = !$input->hasParameterOption('--skip-config');
667
668
        $this->config = $config = new Config($initConfig, $this->isPharMode(), $output);
669
        if ($this->configurationLoaderInjected) {
670
            $config->setLoader($this->configurationLoaderInjected);
671
        }
672
        $config->loadPartialConfig($loadExternalConfig);
673
        $this->detectMagento($input, $output);
674
        $configLoader = $config->getLoader();
675
        $configLoader->loadStageTwo($this->_magentoRootFolder, $loadExternalConfig, $this->_magerunStopFileFolder);
676
        $config->load();
677
678
        if ($autoloader = $this->autoloader) {
679
            $config->registerCustomAutoloaders($autoloader);
680
            $this->registerEventSubscribers();
681
            $config->registerCustomCommands($this);
682
        }
683
684
        $this->registerHelpers();
685
686
        $this->_isInitialized = true;
687
    }
688
689
    /**
690
     * @param array $initConfig [optional]
691
     * @param InputInterface $input [optional]
0 ignored issues
show
Documentation introduced by
Should the type for parameter $input not be null|InputInterface?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
692
     * @param OutputInterface $output [optional]
0 ignored issues
show
Documentation introduced by
Should the type for parameter $output not be null|OutputInterface?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
693
     */
694
    public function reinit($initConfig = array(), InputInterface $input = null, OutputInterface $output = null)
695
    {
696
        $this->_isInitialized = false;
697
        $this->_magentoDetected = false;
698
        $this->_magentoRootFolder = null;
699
        $this->config = null;
700
        $this->init($initConfig, $input, $output);
701
    }
702
703
    /**
704
     * @return void
705
     */
706
    protected function registerEventSubscribers()
707
    {
708
        $config = $this->config->getConfig();
709
        $subscriberClasses = $config['event']['subscriber'];
710
        foreach ($subscriberClasses as $subscriberClass) {
711
            $subscriber = new $subscriberClass();
712
            $this->dispatcher->addSubscriber($subscriber);
713
        }
714
    }
715
716
    /**
717
     * @param InputInterface $input
718
     * @return bool
719
     * @deprecated 1.97.27
720
     */
721
    protected function _checkSkipConfigOption(InputInterface $input)
722
    {
723
        trigger_error(
724
            __METHOD__ . ' removed, use $input->hasParameterOption(\'--skip-config\') instead',
725
            E_USER_DEPRECATED
726
        );
727
728
        return $input->hasParameterOption('--skip-config');
729
    }
730
731
    /**
732
     * @param InputInterface $input
733
     * @return string
0 ignored issues
show
Documentation introduced by
Should the return type not be string|null?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
734
     */
735
    protected function _checkRootDirOption(InputInterface $input)
736
    {
737
        $rootDir = $input->getParameterOption('--root-dir');
738
        if (is_string($rootDir)) {
739
            $this->setRootDir($rootDir);
740
        }
741
    }
742
743
    /**
744
     * Set root dir (chdir()) of magento directory
745
     *
746
     * @param string $path to Magento directory
747
     */
748
    private function setRootDir($path)
749
    {
750
        if (isset($path[0]) && '~' === $path[0]) {
751
            $path = OperatingSystem::getHomeDir() . substr($path, 1);
752
        }
753
754
        $folder = realpath($path);
755
        $this->_directRootDir = true;
756
        if (is_dir($folder)) {
757
            chdir($folder);
758
        }
759
    }
760
761
    /**
762
     * use require-once inside a function with it's own variable scope w/o any other variables
763
     * and $this unbound.
764
     *
765
     * @param string $path
766
     */
767
    private function requireOnce($path)
768
    {
769
        $requireOnce = function () {
770
            require_once func_get_arg(0);
771
        };
772
        if (50400 <= PHP_VERSION_ID) {
773
            $requireOnce->bindTo(null);
774
        }
775
776
        $requireOnce($path);
777
    }
778
779
    /**
780
     * @param bool $soft
781
     *
782
     * @return void
783
     */
784
    protected function _initMagento1($soft = false)
785
    {
786
        if (!class_exists('Mage', false)) {
787
            // Create a new AutoloadRestorer to capture currenjt auto-öpaders
788
            $restorer = new AutoloadRestorer();
789
            // require app/Mage.php from Magento in a function of it's own to have it's own variable scope
790
            $this->requireOnce($this->_magentoRootFolder . '/app/Mage.php');
791
            // Restore auto-loaders that might be removed by extensions that overwrite Varien/Autoload
792
            $restorer->restore();
793
        }
794
795
        // skip Mage::app init routine and return
796
        if ($soft === true) {
797
            return;
798
        }
799
800
        $config = $this->config->getConfig();
801
        $initSettings = $config['init'];
802
803
        Mage::app($initSettings['code'], $initSettings['type'], $initSettings['options']);
804
    }
805
806
    /**
807
     * @return void
808
     */
809
    protected function _initMagento2()
810
    {
811
        $this->outputMagerunCompatibilityNotice('2');
812
    }
813
814
    /**
815
     * Show a hint that this is Magento incompatible with Magerun and how to obtain the correct Magerun for it
816
     *
817
     * @param string $version of Magento, "1" or "2", that is incompatible
818
     */
819
    private function outputMagerunCompatibilityNotice($version)
820
    {
821
        $file = $version === '2' ? $version : '';
822
        $magentoHint = <<<MAGENTOHINT
823
You are running a Magento $version.x instance. This version of n98-magerun is not compatible
824
with Magento $version.x. Please use n98-magerun$version (version $version) for this shop.
825
826
A current version of the software can be downloaded on github.
827
828
<info>Download with curl
829
------------------</info>
830
831
    <comment>curl -O https://files.magerun.net/n98-magerun$file.phar</comment>
832
833
<info>Download with wget
834
------------------</info>
835
836
    <comment>wget https://files.magerun.net/n98-magerun$file.phar</comment>
837
838
MAGENTOHINT;
839
840
        $output = new ConsoleOutput();
841
842
        /** @var $formatter FormatterHelper */
843
        $formatter = $this->getHelperSet()->get('formatter');
844
845
        $output->writeln(array(
846
            '',
847
            $formatter->formatBlock('Compatibility Notice', 'bg=blue;fg=white', true),
848
            '',
849
            $magentoHint,
850
        ));
851
852
        throw new RuntimeException('This version of n98-magerun is not compatible with Magento ' . $version);
853
    }
854
855
    /**
856
     * @return EventDispatcher
857
     */
858
    public function getDispatcher()
859
    {
860
        return $this->dispatcher;
861
    }
862
863
    /**
864
     * @param array $initConfig
865
     * @param OutputInterface $output
866
     * @return ConfigurationLoader
867
     */
868
    public function getConfigurationLoader(array $initConfig, OutputInterface $output)
869
    {
870
        trigger_error(__METHOD__ . ' moved, use getConfig()->getLoader()', E_USER_DEPRECATED);
871
872
        unset($initConfig, $output);
873
874
        $loader = $this->config ? $this->config->getLoader() : $this->configurationLoaderInjected;
875
876
        if (!$loader) {
877
            throw new RuntimeException('ConfigurationLoader is not yet available, initialize it or Config first');
878
        }
879
880
        return $loader;
881
    }
882
883
    /**
884
     * @param ConfigurationLoader $configurationLoader
885
     *
886
     * @return $this
887
     */
888
    public function setConfigurationLoader(ConfigurationLoader $configurationLoader)
889
    {
890
        if ($this->config) {
891
            $this->config->setLoader($configurationLoader);
892
        } else {
893
            /* inject loader to be used later when config is created in */
894
            /* @see N98\Magento\Application::init */
895
            $this->configurationLoaderInjected = $configurationLoader;
896
        }
897
898
        return $this;
899
    }
900
901
    /**
902
     * @param OutputInterface $output
903
     */
904
    protected function _addOutputStyles(OutputInterface $output)
905
    {
906
        $output->getFormatter()->setStyle('debug', new OutputFormatterStyle('magenta', 'white'));
907
        $output->getFormatter()->setStyle('warning', new OutputFormatterStyle('red', 'yellow', array('bold')));
908
    }
909
}
910