Completed
Pull Request — develop (#940)
by Luke
03:24
created

Application   F

Complexity

Total Complexity 86

Size/Duplication

Total Lines 873
Duplicated Lines 0 %

Coupling/Cohesion

Components 3
Dependencies 20

Importance

Changes 0
Metric Value
dl 0
loc 873
rs 1.263
c 0
b 0
f 0
wmc 86
lcom 3
cbo 20

42 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
A setAutoExit() 0 8 1
A getDefaultInputDefinition() 0 51 1
B detectMagento() 0 39 6
A registerHelpers() 0 20 4
A checkConfigCommandAlias() 0 6 1
A registerConfigCommandAlias() 0 6 1
A registerCustomAutoloaders() 0 6 1
A hasCustomCommands() 0 6 1
A registerCustomCommands() 0 6 1
A isCommandDisabled() 0 8 1
A add() 0 8 2
A setPharMode() 0 4 1
A isPharMode() 0 4 1
B checkVarDir() 0 57 8
A initMagento() 0 15 3
A getHelp() 0 4 1
A getLongVersion() 0 4 1
A isMagentoEnterprise() 0 4 1
A getMagentoRootFolder() 0 4 1
A setMagentoRootFolder() 0 4 1
A getMagentoMajorVersion() 0 4 1
A getAutoloader() 0 4 1
A setAutoloader() 0 4 1
A getConfig() 0 17 4
A setConfig() 0 4 1
A isMagerunStopFileFound() 0 4 1
A doRun() 0 18 2
B run() 0 32 6
C init() 0 42 7
A reinit() 0 8 1
A registerEventSubscribers() 0 9 2
A _checkSkipConfigOption() 0 9 1
A _checkRootDirOption() 0 7 2
A setRootDir() 0 12 4
A _initMagento1() 0 17 3
A _initMagento2() 0 4 1
B outputMagerunCompatibilityNotice() 0 35 2
A getDispatcher() 0 4 1
A getConfigurationLoader() 0 14 3
A setConfigurationLoader() 0 12 2
A _addOutputStyles() 0 5 1

How to fix   Complexity   

Complex Class

Complex classes like Application often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use Application, and based on these observations, apply Extract Interface, too.

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\Console\Helper\MagentoHelper;
13
use N98\Util\OperatingSystem;
14
use RuntimeException;
15
use Symfony\Component\Console\Application as BaseApplication;
16
use Symfony\Component\Console\Command\Command;
17
use Symfony\Component\Console\Event\ConsoleEvent;
18
use Symfony\Component\Console\Formatter\OutputFormatterStyle;
19
use Symfony\Component\Console\Helper\FormatterHelper;
20
use Symfony\Component\Console\Input\ArgvInput;
21
use Symfony\Component\Console\Input\InputDefinition;
22
use Symfony\Component\Console\Input\InputInterface;
23
use Symfony\Component\Console\Input\InputOption;
24
use Symfony\Component\Console\Output\ConsoleOutput;
25
use Symfony\Component\Console\Output\OutputInterface;
26
use Symfony\Component\EventDispatcher\EventDispatcher;
27
use UnexpectedValueException;
28
29
class Application extends BaseApplication
30
{
31
    /**
32
     * @var string
33
     */
34
    const APP_NAME = 'n98-magerun';
35
36
    /**
37
     * @var string
38
     */
39
    const APP_VERSION = '1.98.0';
40
41
    /**
42
     * @var int
43
     */
44
    const MAGENTO_MAJOR_VERSION_1 = 1;
45
46
    /**
47
     * @var int
48
     */
49
    const MAGENTO_MAJOR_VERSION_2 = 2;
50
51
    /**
52
     * @var string
53
     */
54
    private static $logo = "
55
     ___ ___
56
 _ _/ _ ( _ )___ _ __  __ _ __ _ ___ _ _ _  _ _ _
57
| ' \\_, / _ \\___| '  \\/ _` / _` / -_) '_| || | ' \\
58
|_||_/_/\\___/   |_|_|_\\__,_\\__, \\___|_|  \\_,_|_||_|
59
                           |___/
60
";
61
62
    /**
63
     * Shadow copy of the Application parent when using this concrete setAutoExit() implementation
64
     *
65
     * @see \Symfony\Component\Console\Application::$autoExit
66
     * @var bool
67
     */
68
    private $autoExitShadow = true;
69
70
    /**
71
     * @var ClassLoader
72
     */
73
    protected $autoloader;
74
75
    /**
76
     * @var Config
77
     */
78
    protected $config;
79
80
    /**
81
     * @see \N98\Magento\Application::setConfigurationLoader()
82
     * @var ConfigurationLoader
83
     */
84
    private $configurationLoaderInjected;
85
86
    /**
87
     * @var string
88
     */
89
    protected $_magentoRootFolder = null;
90
91
    /**
92
     * @var bool
93
     */
94
    protected $_magentoEnterprise = false;
95
96
    /**
97
     * @var int
98
     */
99
    protected $_magentoMajorVersion = self::MAGENTO_MAJOR_VERSION_1;
100
101
    /**
102
     * @var EntryPoint
103
     */
104
    protected $_magento2EntryPoint = null;
105
106
    /**
107
     * @var bool
108
     */
109
    protected $_isPharMode = false;
110
111
    /**
112
     * @var bool
113
     */
114
    protected $_magerunStopFileFound = false;
115
116
    /**
117
     * @var string
118
     */
119
    protected $_magerunStopFileFolder = null;
120
121
    /**
122
     * @var null
123
     */
124
    protected $_magerunUseDeveloperMode = null;
125
126
    /**
127
     * @var bool
128
     */
129
    protected $_isInitialized = false;
130
131
    /**
132
     * @var EventDispatcher
133
     */
134
    protected $dispatcher;
135
136
    /**
137
     * If root dir is set by root-dir option this flag is true
138
     *
139
     * @var bool
140
     */
141
    protected $_directRootDir = false;
142
143
    /**
144
     * @var bool
145
     */
146
    protected $_magentoDetected = false;
147
148
    /**
149
     * @param ClassLoader $autoloader
150
     */
151
    public function __construct($autoloader = null)
152
    {
153
        $this->autoloader = $autoloader;
154
        parent::__construct(self::APP_NAME, self::APP_VERSION);
155
    }
156
157
    /**
158
     * @param bool $boolean
159
     * @return bool previous auto-exit state
160
     */
161
    public function setAutoExit($boolean)
162
    {
163
        $previous = $this->autoExitShadow;
164
        $this->autoExitShadow = $boolean;
165
        parent::setAutoExit($boolean);
166
167
        return $previous;
168
    }
169
170
    /**
171
     * @return InputDefinition
172
     */
173
    protected function getDefaultInputDefinition()
174
    {
175
        $inputDefinition = parent::getDefaultInputDefinition();
176
177
        /**
178
         * Root dir
179
         */
180
        $rootDirOption = new InputOption(
181
            '--root-dir',
182
            '',
183
            InputOption::VALUE_OPTIONAL,
184
            'Force magento root dir. No auto detection'
185
        );
186
        $inputDefinition->addOption($rootDirOption);
187
188
        /**
189
         * Skip config
190
         */
191
        $skipExternalConfig = new InputOption(
192
            '--skip-config',
193
            '',
194
            InputOption::VALUE_NONE,
195
            'Do not load any custom config.'
196
        );
197
        $inputDefinition->addOption($skipExternalConfig);
198
199
        /**
200
         * Skip root check
201
         */
202
        $skipExternalConfig = new InputOption(
203
            '--skip-root-check',
204
            '',
205
            InputOption::VALUE_NONE,
206
            'Do not check if n98-magerun runs as root'
207
        );
208
        $inputDefinition->addOption($skipExternalConfig);
209
210
        /**
211
         * Developer Mode
212
         */
213
        $rootDirOption = new InputOption(
214
            '--developer-mode',
215
            '',
216
            InputOption::VALUE_NONE,
217
            'Instantiate Magento in Developer Mode'
218
        );
219
        $inputDefinition->addOption($rootDirOption);
220
221
222
        return $inputDefinition;
223
    }
224
225
    /**
226
     * Search for magento root folder
227
     *
228
     * @param InputInterface $input [optional]
229
     * @param OutputInterface $output [optional]
230
     * @return void
231
     */
232
    public function detectMagento(InputInterface $input = null, OutputInterface $output = null)
233
    {
234
        // do not detect magento twice
235
        if ($this->_magentoDetected) {
236
            return;
237
        }
238
239
        if (null === $input) {
240
            $input = new ArgvInput();
241
        }
242
243
        if (null === $output) {
244
            $output = new ConsoleOutput();
245
        }
246
247
        if ($this->getMagentoRootFolder() === null) {
248
            $this->_checkRootDirOption($input);
249
            $folder = OperatingSystem::getCwd();
250
        } else {
251
            $folder = $this->getMagentoRootFolder();
252
        }
253
254
        $this->getHelperSet()->set(new MagentoHelper($input, $output), 'magento');
255
        $magentoHelper = $this->getHelperSet()->get('magento');
256
        /* @var $magentoHelper MagentoHelper */
257
        if (!$this->_directRootDir) {
258
            $subFolders = $this->config->getDetectSubFolders();
259
        } else {
260
            $subFolders = array();
261
        }
262
263
        $this->_magentoDetected = $magentoHelper->detect($folder, $subFolders);
264
        $this->_magentoRootFolder = $magentoHelper->getRootFolder();
265
        $this->_magentoEnterprise = $magentoHelper->isEnterpriseEdition();
266
        $this->_magentoMajorVersion = $magentoHelper->getMajorVersion();
267
        $this->_magerunStopFileFound = $magentoHelper->isMagerunStopFileFound();
268
        $this->_magerunStopFileFolder = $magentoHelper->getMagerunStopFileFolder();
269
        $this->_magerunUseDeveloperMode = ($input->getParameterOption('--developer-mode'));
270
    }
271
272
    /**
273
     * Add own helpers to helperset.
274
     *
275
     * @return void
276
     */
277
    protected function registerHelpers()
278
    {
279
        $helperSet = $this->getHelperSet();
280
        $config = $this->config->getConfig();
281
282
        foreach ($config['helpers'] as $helperName => $helperClass) {
283
            if (!class_exists($helperClass)) {
284
                throw new RuntimeException(
285
                    sprintf('Nonexistent helper class: "%s", check helpers configuration', $helperClass)
286
                );
287
            }
288
289
            // Twig helper needs the config-file
290
            $helper = 'N98\Util\Console\Helper\TwigHelper' === $helperClass
291
                ? new $helperClass($this->config)
292
                : new $helperClass()
293
            ;
294
            $helperSet->set($helper, $helperName);
295
        }
296
    }
297
298
    /**
299
     * @param InputInterface $input
300
     *
301
     * @return ArgvInput|InputInterface
302
     */
303
    protected function checkConfigCommandAlias(InputInterface $input)
304
    {
305
        trigger_error(__METHOD__ . ' moved, use getConfig()->checkConfigCommandAlias()', E_USER_DEPRECATED);
306
307
        return $this->config->checkConfigCommandAlias($input);
308
    }
309
310
    /**
311
     * @param Command $command
312
     */
313
    protected function registerConfigCommandAlias(Command $command)
314
    {
315
        trigger_error(__METHOD__ . ' moved, use getConfig()->registerConfigCommandAlias() instead', E_USER_DEPRECATED);
316
317
        return $this->config->registerConfigCommandAlias($command);
318
    }
319
320
    /**
321
     * Adds autoloader prefixes from user's config
322
     */
323
    protected function registerCustomAutoloaders()
324
    {
325
        trigger_error(__METHOD__ . ' moved, use getConfig()->registerCustomAutoloaders() instead', E_USER_DEPRECATED);
326
327
        $this->config->registerCustomAutoloaders($this->autoloader);
328
    }
329
330
    /**
331
     * @return bool
332
     */
333
    protected function hasCustomCommands()
334
    {
335
        trigger_error(__METHOD__ . ' moved, use config directly instead', E_USER_DEPRECATED);
336
337
        return 0 < count($this->config->getConfig(array('commands', 'customCommands')));
338
    }
339
340
    /**
341
     * @return void
342
     */
343
    protected function registerCustomCommands()
344
    {
345
        trigger_error(__METHOD__ . ' moved, use getConfig()->registerCustomCommands() instead', E_USER_DEPRECATED);
346
347
        $this->config->registerCustomCommands($this);
348
    }
349
350
    /**
351
     * @param string $class
352
     * @return bool
353
     */
354
    protected function isCommandDisabled($class)
355
    {
356
        trigger_error(__METHOD__ . ' moved, use config directly instead', E_USER_DEPRECATED);
357
358
        $config = $this->config->getConfig();
359
360
        return in_array($class, $config['commands']['disabled']);
361
    }
362
363
    /**
364
     * Override standard command registration. We want alias support.
365
     *
366
     * @param Command $command
367
     *
368
     * @return Command
369
     */
370
    public function add(Command $command)
371
    {
372
        if ($this->config) {
373
            $this->config->registerConfigCommandAlias($command);
374
        }
375
376
        return parent::add($command);
377
    }
378
379
    /**
380
     * @param bool $mode
381
     */
382
    public function setPharMode($mode)
383
    {
384
        $this->_isPharMode = $mode;
385
    }
386
387
    /**
388
     * @return bool
389
     */
390
    public function isPharMode()
391
    {
392
        return $this->_isPharMode;
393
    }
394
395
    /**
396
     * @TODO Move logic into "EventSubscriber"
397
     *
398
     * @param OutputInterface $output
399
     * @return null|false
400
     */
401
    public function checkVarDir(OutputInterface $output)
402
    {
403
        $tempVarDir = sys_get_temp_dir() . '/magento/var';
404
        if (!OutputInterface::VERBOSITY_NORMAL <= $output->getVerbosity() && !is_dir($tempVarDir)) {
405
            return;
406
        }
407
408
        $this->detectMagento(null, $output);
409
        /* If magento is not installed yet, don't check */
410
        if ($this->_magentoRootFolder === null
411
            || !file_exists($this->_magentoRootFolder . '/app/etc/local.xml')
412
        ) {
413
            return;
414
        }
415
416
        try {
417
            $this->initMagento();
418
        } catch (Exception $e) {
419
            $message = 'Cannot initialize Magento. Please check your configuration. '
420
                . 'Some n98-magerun command will not work. Got message: ';
421
            if (OutputInterface::VERBOSITY_VERY_VERBOSE <= $output->getVerbosity()) {
422
                $message .= $e->getTraceAsString();
423
            } else {
424
                $message .= $e->getMessage();
425
            }
426
            $output->writeln($message);
427
428
            return;
429
        }
430
431
        $configOptions = new \Mage_Core_Model_Config_Options();
432
        $currentVarDir = $configOptions->getVarDir();
433
434
        if ($currentVarDir == $tempVarDir) {
435
            $output->writeln(array(
436
                sprintf('<warning>Fallback folder %s is used in n98-magerun</warning>', $tempVarDir),
437
                '',
438
                'n98-magerun is using the fallback folder. If there is another folder configured for Magento, this ' .
439
                'can cause serious problems.',
440
                'Please refer to https://github.com/netz98/n98-magerun/wiki/File-system-permissions ' .
441
                'for more information.',
442
                '',
443
            ));
444
        } else {
445
            $output->writeln(array(
446
                sprintf('<warning>Folder %s found, but not used in n98-magerun</warning>', $tempVarDir),
447
                '',
448
                "This might cause serious problems. n98-magerun is using the configured var-folder " .
449
                "<comment>$currentVarDir</comment>",
450
                'Please refer to https://github.com/netz98/n98-magerun/wiki/File-system-permissions ' .
451
                'for more information.',
452
                '',
453
            ));
454
455
            return false;
456
        }
457
    }
458
459
    /**
460
     * Loads and initializes the Magento application
461
     *
462
     * @param bool $soft
463
     *
464
     * @return bool false if magento root folder is not set, true otherwise
465
     */
466
    public function initMagento($soft = false)
467
    {
468
        if ($this->getMagentoRootFolder() === null) {
469
            return false;
470
        }
471
472
        $isMagento2 = $this->_magentoMajorVersion === self::MAGENTO_MAJOR_VERSION_2;
473
        if ($isMagento2) {
474
            $this->_initMagento2();
475
        } else {
476
            $this->_initMagento1($soft);
477
        }
478
479
        return true;
480
    }
481
482
    /**
483
     * @return string
484
     */
485
    public function getHelp()
486
    {
487
        return self::$logo . parent::getHelp();
488
    }
489
490
    public function getLongVersion()
491
    {
492
        return parent::getLongVersion() . ' by <info>netz98 GmbH</info>';
493
    }
494
495
    /**
496
     * @return boolean
497
     */
498
    public function isMagentoEnterprise()
499
    {
500
        return $this->_magentoEnterprise;
501
    }
502
503
    /**
504
     * @return string
505
     */
506
    public function getMagentoRootFolder()
507
    {
508
        return $this->_magentoRootFolder;
509
    }
510
511
    /**
512
     * @param string $magentoRootFolder
513
     */
514
    public function setMagentoRootFolder($magentoRootFolder)
515
    {
516
        $this->_magentoRootFolder = $magentoRootFolder;
517
    }
518
519
    /**
520
     * @return int
521
     */
522
    public function getMagentoMajorVersion()
523
    {
524
        return $this->_magentoMajorVersion;
525
    }
526
527
    /**
528
     * @return ClassLoader
529
     */
530
    public function getAutoloader()
531
    {
532
        return $this->autoloader;
533
    }
534
535
    /**
536
     * @param ClassLoader $autoloader
537
     */
538
    public function setAutoloader(ClassLoader $autoloader)
539
    {
540
        $this->autoloader = $autoloader;
541
    }
542
543
    /**
544
     * Get config array
545
     *
546
     * Specify one key per parameter to traverse the config. Then returns null
547
     * if the path of the key(s) can not be obtained.
548
     *
549
     * @param string|int $key ... (optional)
550
     *
551
     * @return array|null
552
     */
553
    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...
554
    {
555
        $array = $this->config->getConfig();
556
557
        $keys = func_get_args();
558
        foreach ($keys as $key) {
559
            if (null === $key) {
560
                continue;
561
            }
562
            if (!isset($array[$key])) {
563
                return null;
564
            }
565
            $array = $array[$key];
566
        }
567
568
        return $array;
569
    }
570
571
    /**
572
     * @param array $config
573
     */
574
    public function setConfig($config)
575
    {
576
        $this->config->setConfig($config);
577
    }
578
579
    /**
580
     * @return boolean
581
     */
582
    public function isMagerunStopFileFound()
583
    {
584
        return $this->_magerunStopFileFound;
585
    }
586
587
    /**
588
     * Runs the current application with possible command aliases
589
     *
590
     * @param InputInterface $input An Input instance
591
     * @param OutputInterface $output An Output instance
592
     *
593
     * @return integer 0 if everything went fine, or an error code
594
     */
595
    public function doRun(InputInterface $input, OutputInterface $output)
596
    {
597
        $event = new Application\Console\Event($this, $input, $output);
598
        $this->dispatcher->dispatch(Events::RUN_BEFORE, $event);
599
600
        /**
601
         * only for compatibility to old versions.
602
         */
603
        $event = new ConsoleEvent(new Command('dummy'), $input, $output);
604
        $this->dispatcher->dispatch('console.run.before', $event);
605
606
        $input = $this->config->checkConfigCommandAlias($input);
607
        if ($output instanceof ConsoleOutput) {
608
            $this->checkVarDir($output->getErrorOutput());
609
        }
610
611
        return parent::doRun($input, $output);
612
    }
613
614
    /**
615
     * @param InputInterface $input [optional]
616
     * @param OutputInterface $output [optional]
617
     *
618
     * @return int
619
     */
620
    public function run(InputInterface $input = null, OutputInterface $output = null)
621
    {
622
        if (null === $input) {
623
            $input = new ArgvInput();
624
        }
625
626
        if (null === $output) {
627
            $output = new ConsoleOutput();
628
        }
629
        $this->_addOutputStyles($output);
630
        if ($output instanceof ConsoleOutput) {
631
            $this->_addOutputStyles($output->getErrorOutput());
632
        }
633
634
        $this->configureIO($input, $output);
635
636
        try {
637
            $this->init(array(), $input, $output);
638
        } catch (Exception $e) {
639
            $output = new ConsoleOutput();
640
            $this->renderException($e, $output->getErrorOutput());
641
        }
642
643
        $return = parent::run($input, $output);
644
645
        // Fix for no return values -> used in interactive shell to prevent error output
646
        if ($return === null) {
647
            return 0;
648
        }
649
650
        return $return;
651
    }
652
653
    /**
654
     * @param array $initConfig [optional]
655
     * @param InputInterface $input [optional]
656
     * @param OutputInterface $output [optional]
657
     *
658
     * @return void
659
     */
660
    public function init(array $initConfig = array(), InputInterface $input = null, OutputInterface $output = null)
661
    {
662
        if ($this->_isInitialized) {
663
            return;
664
        }
665
666
        // Suppress DateTime warnings
667
        date_default_timezone_set(@date_default_timezone_get());
668
669
        // Initialize EventDispatcher early
670
        $this->dispatcher = new EventDispatcher();
671
        $this->setDispatcher($this->dispatcher);
672
673
        $input = $input ?: new ArgvInput();
674
        $output = $output ?: new ConsoleOutput();
675
676
        if (null !== $this->config) {
677
            throw new UnexpectedValueException(sprintf('Config already initialized'));
678
        }
679
680
        $loadExternalConfig = !$input->hasParameterOption('--skip-config');
681
682
        $this->config = $config = new Config($initConfig, $this->isPharMode(), $output);
683
        if ($this->configurationLoaderInjected) {
684
            $config->setLoader($this->configurationLoaderInjected);
685
        }
686
        $config->loadPartialConfig($loadExternalConfig);
687
        $this->detectMagento($input, $output);
688
        $configLoader = $config->getLoader();
689
        $configLoader->loadStageTwo($this->_magentoRootFolder, $loadExternalConfig, $this->_magerunStopFileFolder);
690
        $config->load();
691
692
        if ($autoloader = $this->autoloader) {
693
            $config->registerCustomAutoloaders($autoloader);
694
            $this->registerEventSubscribers();
695
            $config->registerCustomCommands($this);
696
        }
697
698
        $this->registerHelpers();
699
700
        $this->_isInitialized = true;
701
    }
702
703
    /**
704
     * @param array $initConfig [optional]
705
     * @param InputInterface $input [optional]
706
     * @param OutputInterface $output [optional]
707
     */
708
    public function reinit($initConfig = array(), InputInterface $input = null, OutputInterface $output = null)
709
    {
710
        $this->_isInitialized = false;
711
        $this->_magentoDetected = false;
712
        $this->_magentoRootFolder = null;
713
        $this->config = null;
714
        $this->init($initConfig, $input, $output);
715
    }
716
717
    /**
718
     * @return void
719
     */
720
    protected function registerEventSubscribers()
721
    {
722
        $config = $this->config->getConfig();
723
        $subscriberClasses = $config['event']['subscriber'];
724
        foreach ($subscriberClasses as $subscriberClass) {
725
            $subscriber = new $subscriberClass();
726
            $this->dispatcher->addSubscriber($subscriber);
727
        }
728
    }
729
730
    /**
731
     * @param InputInterface $input
732
     * @return bool
733
     * @deprecated 1.97.27
734
     */
735
    protected function _checkSkipConfigOption(InputInterface $input)
736
    {
737
        trigger_error(
738
            __METHOD__ . ' removed, use $input->hasParameterOption(\'--skip-config\') instead',
739
            E_USER_DEPRECATED
740
        );
741
742
        return $input->hasParameterOption('--skip-config');
743
    }
744
745
    /**
746
     * @param InputInterface $input
747
     * @return string
748
     */
749
    protected function _checkRootDirOption(InputInterface $input)
750
    {
751
        $rootDir = $input->getParameterOption('--root-dir');
752
        if (is_string($rootDir)) {
753
            $this->setRootDir($rootDir);
754
        }
755
    }
756
757
    /**
758
     * Set root dir (chdir()) of magento directory
759
     *
760
     * @param string $path to Magento directory
761
     */
762
    private function setRootDir($path)
763
    {
764
        if (isset($path[0]) && '~' === $path[0]) {
765
            $path = OperatingSystem::getHomeDir() . substr($path, 1);
766
        }
767
768
        $folder = realpath($path);
769
        $this->_directRootDir = true;
770
        if (is_dir($folder)) {
771
            chdir($folder);
772
        }
773
    }
774
775
    /**
776
     * @param bool $soft
777
     *
778
     * @return void
779
     */
780
    protected function _initMagento1($soft = false)
781
    {
782
        // Load Mage class definition
783
        Initialiser::bootstrap($this->_magentoRootFolder);
784
785
        // skip Mage::app init routine and return
786
        if ($soft === true) {
787
            return;
788
        }
789
790
        $initSettings = $this->config->getConfig('init');
791
792
        Mage::app($initSettings['code'], $initSettings['type'], $initSettings['options']);
793
        if ($this->_magerunUseDeveloperMode) {
794
            Mage::setIsDeveloperMode(true);
795
        }
796
    }
797
798
    /**
799
     * @return void
800
     */
801
    protected function _initMagento2()
802
    {
803
        $this->outputMagerunCompatibilityNotice('2');
804
    }
805
806
    /**
807
     * Show a hint that this is Magento incompatible with Magerun and how to obtain the correct Magerun for it
808
     *
809
     * @param string $version of Magento, "1" or "2", that is incompatible
810
     */
811
    private function outputMagerunCompatibilityNotice($version)
812
    {
813
        $file = $version === '2' ? $version : '';
814
        $magentoHint = <<<MAGENTOHINT
815
You are running a Magento $version.x instance. This version of n98-magerun is not compatible
816
with Magento $version.x. Please use n98-magerun$version (version $version) for this shop.
817
818
A current version of the software can be downloaded on github.
819
820
<info>Download with curl
821
------------------</info>
822
823
    <comment>curl -O https://files.magerun.net/n98-magerun$file.phar</comment>
824
825
<info>Download with wget
826
------------------</info>
827
828
    <comment>wget https://files.magerun.net/n98-magerun$file.phar</comment>
829
830
MAGENTOHINT;
831
832
        $output = new ConsoleOutput();
833
834
        /** @var $formatter FormatterHelper */
835
        $formatter = $this->getHelperSet()->get('formatter');
836
837
        $output->writeln(array(
838
            '',
839
            $formatter->formatBlock('Compatibility Notice', 'bg=blue;fg=white', true),
840
            '',
841
            $magentoHint,
842
        ));
843
844
        throw new RuntimeException('This version of n98-magerun is not compatible with Magento ' . $version);
845
    }
846
847
    /**
848
     * @return EventDispatcher
849
     */
850
    public function getDispatcher()
851
    {
852
        return $this->dispatcher;
853
    }
854
855
    /**
856
     * @param array $initConfig
857
     * @param OutputInterface $output
858
     * @return ConfigurationLoader
859
     */
860
    public function getConfigurationLoader(array $initConfig, OutputInterface $output)
861
    {
862
        trigger_error(__METHOD__ . ' moved, use getConfig()->getLoader()', E_USER_DEPRECATED);
863
864
        unset($initConfig, $output);
865
866
        $loader = $this->config ? $this->config->getLoader() : $this->configurationLoaderInjected;
867
868
        if (!$loader) {
869
            throw new RuntimeException('ConfigurationLoader is not yet available, initialize it or Config first');
870
        }
871
872
        return $loader;
873
    }
874
875
    /**
876
     * @param ConfigurationLoader $configurationLoader
877
     *
878
     * @return $this
879
     */
880
    public function setConfigurationLoader(ConfigurationLoader $configurationLoader)
881
    {
882
        if ($this->config) {
883
            $this->config->setLoader($configurationLoader);
884
        } else {
885
            /* inject loader to be used later when config is created in */
886
            /* @see N98\Magento\Application::init */
887
            $this->configurationLoaderInjected = $configurationLoader;
888
        }
889
890
        return $this;
891
    }
892
893
    /**
894
     * @param OutputInterface $output
895
     */
896
    protected function _addOutputStyles(OutputInterface $output)
897
    {
898
        $output->getFormatter()->setStyle('debug', new OutputFormatterStyle('magenta', 'white'));
899
        $output->getFormatter()->setStyle('warning', new OutputFormatterStyle('red', 'yellow', array('bold')));
900
    }
901
}
902