Completed
Push — develop ( 6f71dd...40edc3 )
by Tom
11s
created

Application::checkVarDir()   B

Complexity

Conditions 8
Paths 6

Size

Total Lines 56
Code Lines 40

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 2 Features 0
Metric Value
c 2
b 2
f 0
dl 0
loc 56
rs 7.3333
cc 8
eloc 40
nc 6
nop 1

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
namespace N98\Magento;
4
5
use Composer\Autoload\ClassLoader;
6
use Exception;
7
use Magento\Mtf\EntryPoint\EntryPoint;
8
use N98\Magento\Application\ConfigurationLoader;
9
use N98\Util\ArrayFunctions;
10
use N98\Util\AutoloadRestorer;
11
use N98\Util\Console\Helper\TwigHelper;
12
use N98\Util\Console\Helper\MagentoHelper;
13
use N98\Util\OperatingSystem;
14
use N98\Util\BinaryString;
15
use RuntimeException;
16
use Symfony\Component\Console\Application as BaseApplication;
17
use Symfony\Component\Console\Command\Command;
18
use Symfony\Component\Console\Event\ConsoleEvent;
19
use Symfony\Component\Console\Formatter\OutputFormatterStyle;
20
use Symfony\Component\Console\Helper\FormatterHelper;
21
use Symfony\Component\Console\Input\ArgvInput;
22
use Symfony\Component\Console\Input\InputDefinition;
23
use Symfony\Component\Console\Input\InputInterface;
24
use Symfony\Component\Console\Input\InputOption;
25
use Symfony\Component\Console\Output\ConsoleOutput;
26
use Symfony\Component\Console\Output\NullOutput;
27
use Symfony\Component\Console\Output\OutputInterface;
28
use Symfony\Component\EventDispatcher\EventDispatcher;
29
30
class Application extends BaseApplication
31
{
32
    /**
33
     * @var string
34
     */
35
    const APP_NAME = 'n98-magerun';
36
37
    /**
38
     * @var string
39
     */
40
    const APP_VERSION = '1.97.15';
41
42
    /**
43
     * @var int
44
     */
45
    const MAGENTO_MAJOR_VERSION_1 = 1;
46
47
    /**
48
     * @var int
49
     */
50
    const MAGENTO_MAJOR_VERSION_2 = 2;
51
52
    /**
53
     * @var string
54
     */
55
    private static $logo = "
56
     ___ ___
57
 _ _/ _ ( _ )___ _ __  __ _ __ _ ___ _ _ _  _ _ _
58
| ' \\_, / _ \\___| '  \\/ _` / _` / -_) '_| || | ' \\
59
|_||_/_/\\___/   |_|_|_\\__,_\\__, \\___|_|  \\_,_|_||_|
60
                           |___/
61
";
62
    /**
63
     * @var ClassLoader
64
     */
65
    protected $autoloader;
66
67
    /**
68
     * @var array
69
     */
70
    protected $config = array();
71
72
    /**
73
     * @var ConfigurationLoader
74
     */
75
    protected $configurationLoader = null;
76
77
    /**
78
     * @var array
79
     */
80
    protected $partialConfig = array();
81
82
    /**
83
     * @var string
84
     */
85
    protected $_magentoRootFolder = null;
86
87
    /**
88
     * @var bool
89
     */
90
    protected $_magentoEnterprise = false;
91
92
    /**
93
     * @var int
94
     */
95
    protected $_magentoMajorVersion = self::MAGENTO_MAJOR_VERSION_1;
96
97
    /**
98
     * @var EntryPoint
99
     */
100
    protected $_magento2EntryPoint = null;
101
102
    /**
103
     * @var bool
104
     */
105
    protected $_isPharMode = false;
106
107
    /**
108
     * @var bool
109
     */
110
    protected $_magerunStopFileFound = false;
111
112
    /**
113
     * @var string
114
     */
115
    protected $_magerunStopFileFolder = null;
116
117
    /**
118
     * @var bool
119
     */
120
    protected $_isInitialized = false;
121
122
    /**
123
     * @var EventDispatcher
124
     */
125
    protected $dispatcher;
126
127
    /**
128
     * If root dir is set by root-dir option this flag is true
129
     *
130
     * @var bool
131
     */
132
    protected $_directRootDir = false;
133
134
    /**
135
     * @var bool
136
     */
137
    protected $_magentoDetected = false;
138
139
    /**
140
     * @param ClassLoader $autoloader
141
     */
142
    public function __construct($autoloader = null)
143
    {
144
        $this->autoloader = $autoloader;
145
        parent::__construct(self::APP_NAME, self::APP_VERSION);
146
    }
147
148
    /**
149
     * @return InputDefinition
150
     */
151
    protected function getDefaultInputDefinition()
152
    {
153
        $inputDefinition = parent::getDefaultInputDefinition();
154
155
        /**
156
         * Root dir
157
         */
158
        $rootDirOption = new InputOption(
159
            '--root-dir',
160
            '',
161
            InputOption::VALUE_OPTIONAL,
162
            'Force magento root dir. No auto detection'
163
        );
164
        $inputDefinition->addOption($rootDirOption);
165
166
        /**
167
         * Skip config
168
         */
169
        $skipExternalConfig = new InputOption(
170
            '--skip-config',
171
            '',
172
            InputOption::VALUE_NONE,
173
            'Do not load any custom config.'
174
        );
175
        $inputDefinition->addOption($skipExternalConfig);
176
177
        /**
178
         * Skip root check
179
         */
180
        $skipExternalConfig = new InputOption(
181
            '--skip-root-check',
182
            '',
183
            InputOption::VALUE_NONE,
184
            'Do not check if n98-magerun runs as root'
185
        );
186
        $inputDefinition->addOption($skipExternalConfig);
187
188
        return $inputDefinition;
189
    }
190
191
    /**
192
     * Get names of sub-folders to be scanned during Magento detection
193
     * @return array
194
     */
195
    public function getDetectSubFolders()
196
    {
197
        if (isset($this->partialConfig['detect']) && isset($this->partialConfig['detect']['subFolders'])) {
198
            return $this->partialConfig['detect']['subFolders'];
199
        }
200
        return array();
201
    }
202
203
    /**
204
     * Search for magento root folder
205
     *
206
     * @param InputInterface $input [optional]
207
     * @param OutputInterface $output [optional]
208
     * @return void
209
     */
210
    public function detectMagento(InputInterface $input = null, OutputInterface $output = null)
211
    {
212
        // do not detect magento twice
213
        if ($this->_magentoDetected) {
214
            return;
215
        }
216
217
        if (null === $input) {
218
            $input = new ArgvInput();
219
        }
220
221
        if (null === $output) {
222
            $output = new ConsoleOutput();
223
        }
224
225
        if ($this->getMagentoRootFolder() === null) {
226
            $this->_checkRootDirOption($input);
227
            $folder = OperatingSystem::getCwd();
228
        } else {
229
            $folder = $this->getMagentoRootFolder();
230
        }
231
232
        $this->getHelperSet()->set(new MagentoHelper($input, $output), 'magento');
233
        $magentoHelper = $this->getHelperSet()->get('magento');
234
        /* @var $magentoHelper MagentoHelper */
235
        if (!$this->_directRootDir) {
236
            $subFolders = $this->getDetectSubFolders();
237
        } else {
238
            $subFolders = array();
239
        }
240
241
        $this->_magentoDetected = $magentoHelper->detect($folder, $subFolders);
242
        $this->_magentoRootFolder = $magentoHelper->getRootFolder();
243
        $this->_magentoEnterprise = $magentoHelper->isEnterpriseEdition();
244
        $this->_magentoMajorVersion = $magentoHelper->getMajorVersion();
245
        $this->_magerunStopFileFound = $magentoHelper->isMagerunStopFileFound();
246
        $this->_magerunStopFileFolder = $magentoHelper->getMagerunStopFileFolder();
247
    }
248
249
    /**
250
     * Add own helpers to helperset.
251
     *
252
     * @return void
253
     */
254
    protected function registerHelpers()
255
    {
256
        $helperSet = $this->getHelperSet();
257
258
        // Twig
259
        $twigBaseDirs = array(
260
            __DIR__ . '/../../../res/twig'
261
        );
262
        if (isset($this->config['twig']['baseDirs']) && is_array($this->config['twig']['baseDirs'])) {
263
            $twigBaseDirs = array_merge(array_reverse($this->config['twig']['baseDirs']), $twigBaseDirs);
264
        }
265
        $helperSet->set(new TwigHelper($twigBaseDirs), 'twig');
266
267
        foreach ($this->config['helpers'] as $helperName => $helperClass) {
268
            if (class_exists($helperClass)) {
269
                $helperSet->set(new $helperClass(), $helperName);
270
            }
271
        }
272
    }
273
274
    /**
275
     * Adds autoloader prefixes from user's config
276
     */
277
    protected function registerCustomAutoloaders()
278
    {
279 View Code Duplication
        if (isset($this->config['autoloaders']) && is_array($this->config['autoloaders'])) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
280
            foreach ($this->config['autoloaders'] as $prefix => $path) {
281
                $this->autoloader->add($prefix, $path);
282
            }
283
        }
284
285 View Code Duplication
        if (isset($this->config['autoloaders_psr4']) && is_array($this->config['autoloaders_psr4'])) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
286
            foreach ($this->config['autoloaders_psr4'] as $prefix => $path) {
287
                $this->autoloader->addPsr4($prefix, $path);
288
            }
289
        }
290
291 View Code Duplication
        if (isset($this->config['autoload_files']) && is_array($this->config['autoload_files'])) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
292
            foreach ($this->config['autoload_files'] as $file) {
293
                require $file;
294
            }
295
        }
296
    }
297
298
    /**
299
     * @return bool
300
     */
301
    protected function hasCustomCommands()
302
    {
303
        return isset($this->config['commands']['customCommands'])
304
        && is_array($this->config['commands']['customCommands']);
305
    }
306
307
    /**
308
     * @return void
309
     */
310
    protected function registerCustomCommands()
311
    {
312
        if (!$this->hasCustomCommands()) {
313
            return;
314
        }
315
316
        foreach ($this->config['commands']['customCommands'] as $commandClass) {
317
            if (is_array($commandClass)) { // Support for key => value (name -> class)
318
                $resolvedCommandClass = current($commandClass);
319
                if ($this->isCommandDisabled($resolvedCommandClass)) {
320
                    continue;
321
                }
322
                $command = new $resolvedCommandClass();
323
                $command->setName(key($commandClass));
324
            } elseif ($this->isCommandDisabled($commandClass)) {
325
                continue;
326
            } else {
327
                $command = new $commandClass();
328
            }
329
            $this->add($command);
330
        }
331
    }
332
333
    /**
334
     * @param string $class
335
     * @return bool
336
     */
337
    protected function isCommandDisabled($class)
338
    {
339
        return in_array($class, $this->config['commands']['disabled']);
340
    }
341
342
    /**
343
     * Override standard command registration. We want alias support.
344
     *
345
     * @param Command $command
346
     *
347
     * @return Command
348
     */
349
    public function add(Command $command)
350
    {
351
        $this->registerConfigCommandAlias($command);
352
353
        return parent::add($command);
354
    }
355
356
    /**
357
     * @param Command $command
358
     */
359
    protected function registerConfigCommandAlias(Command $command)
360
    {
361
        if ($this->hasConfigCommandAliases()) {
362
            foreach ($this->config['commands']['aliases'] as $alias) {
363
                if (!is_array($alias)) {
364
                    continue;
365
                }
366
367
                $aliasCommandName = key($alias);
368
                $commandString = $alias[$aliasCommandName];
369
370
                list($originalCommand) = explode(' ', $commandString);
371
                if ($command->getName() == $originalCommand) {
372
                    $currentCommandAliases = $command->getAliases();
373
                    $currentCommandAliases[] = $aliasCommandName;
374
                    $command->setAliases($currentCommandAliases);
375
                }
376
            }
377
        }
378
    }
379
380
    /**
381
     * @return bool
382
     */
383
    private function hasConfigCommandAliases()
384
    {
385
        return isset($this->config['commands']['aliases']) && is_array($this->config['commands']['aliases']);
386
    }
387
388
    /**
389
     * @param bool $mode
390
     */
391
    public function setPharMode($mode)
392
    {
393
        $this->_isPharMode = $mode;
394
    }
395
396
    /**
397
     * @return bool
398
     */
399
    public function isPharMode()
400
    {
401
        return $this->_isPharMode;
402
    }
403
404
    /**
405
     * @TODO Move logic into "EventSubscriber"
406
     *
407
     * @param OutputInterface $output
408
     * @return null|false
409
     */
410
    public function checkVarDir(OutputInterface $output)
411
    {
412
        $tempVarDir = sys_get_temp_dir() . DIRECTORY_SEPARATOR . 'magento' . DIRECTORY_SEPARATOR . 'var';
413
        if (!OutputInterface::VERBOSITY_NORMAL <= $output->getVerbosity() && !is_dir($tempVarDir)) {
414
            return;
415
        }
416
417
        $this->detectMagento(null, $output);
418
        /* If magento is not installed yet, don't check */
419
        if ($this->_magentoRootFolder === null
420
            || !file_exists($this->_magentoRootFolder . '/app/etc/local.xml')
421
        ) {
422
            return;
423
        }
424
425
        try {
426
            $this->initMagento();
427
        } catch (Exception $e) {
428
            $message = 'Cannot initialize Magento. Please check your configuration. '
429
                . 'Some n98-magerun command will not work. Got message: ';
430
            if (OutputInterface::VERBOSITY_VERY_VERBOSE <= $output->getVerbosity()) {
431
                $message .= $e->getTraceAsString();
432
            } else {
433
                $message .= $e->getMessage();
434
            }
435
            $output->writeln($message);
436
437
            return;
438
        }
439
440
        $configOptions = new \Mage_Core_Model_Config_Options();
441
        $currentVarDir = $configOptions->getVarDir();
442
443
        if ($currentVarDir == $tempVarDir) {
444
            $output->writeln(array(
445
                sprintf('<warning>Fallback folder %s is used in n98-magerun</warning>', $tempVarDir),
446
                '',
447
                'n98-magerun is using the fallback folder. If there is another folder configured for Magento, this ' .
448
                'can cause serious problems.',
449
                'Please refer to https://github.com/netz98/n98-magerun/wiki/File-system-permissions ' .
450
                'for more information.',
451
                '',
452
            ));
453
        } else {
454
            $output->writeln(array(
455
                sprintf('<warning>Folder %s found, but not used in n98-magerun</warning>', $tempVarDir),
456
                '',
457
                "This might cause serious problems. n98-magerun is using the configured var-folder " .
458
                "<comment>$currentVarDir</comment>",
459
                'Please refer to https://github.com/netz98/n98-magerun/wiki/File-system-permissions ' .
460
                'for more information.',
461
                '',
462
            ));
463
            return false;
464
        }
465
    }
466
467
    /**
468
     * Loads and initializes the Magento application
469
     *
470
     * @param bool $soft
471
     *
472
     * @return bool false if magento root folder is not set, true otherwise
473
     */
474
    public function initMagento($soft = false)
475
    {
476
        if ($this->getMagentoRootFolder() !== null) {
477
            if ($this->_magentoMajorVersion == self::MAGENTO_MAJOR_VERSION_2) {
478
                $this->_initMagento2();
479
            } else {
480
                $this->_initMagento1($soft);
481
            }
482
483
            return true;
484
        }
485
486
        return false;
487
    }
488
489
    /**
490
     * @return string
491
     */
492
    public function getHelp()
493
    {
494
        return self::$logo . parent::getHelp();
495
    }
496
497
    public function getLongVersion()
498
    {
499
        return parent::getLongVersion() . ' by <info>netz98 new media GmbH</info>';
500
    }
501
502
    /**
503
     * @return boolean
504
     */
505
    public function isMagentoEnterprise()
506
    {
507
        return $this->_magentoEnterprise;
508
    }
509
510
    /**
511
     * @return string
512
     */
513
    public function getMagentoRootFolder()
514
    {
515
        return $this->_magentoRootFolder;
516
    }
517
518
    /**
519
     * @param string $magentoRootFolder
520
     */
521
    public function setMagentoRootFolder($magentoRootFolder)
522
    {
523
        $this->_magentoRootFolder = $magentoRootFolder;
524
    }
525
526
    /**
527
     * @return int
528
     */
529
    public function getMagentoMajorVersion()
530
    {
531
        return $this->_magentoMajorVersion;
532
    }
533
534
    /**
535
     * @return ClassLoader
536
     */
537
    public function getAutoloader()
538
    {
539
        return $this->autoloader;
540
    }
541
542
    /**
543
     * @param ClassLoader $autoloader
544
     */
545
    public function setAutoloader($autoloader)
546
    {
547
        $this->autoloader = $autoloader;
548
    }
549
550
    /**
551
     * @return array
552
     */
553
    public function getConfig()
554
    {
555
        return $this->config;
556
    }
557
558
    /**
559
     * @param array $config
560
     */
561
    public function setConfig($config)
562
    {
563
        $this->config = $config;
564
    }
565
566
    /**
567
     * @return boolean
568
     */
569
    public function isMagerunStopFileFound()
570
    {
571
        return $this->_magerunStopFileFound;
572
    }
573
574
    /**
575
     * Runs the current application with possible command aliases
576
     *
577
     * @param InputInterface $input An Input instance
578
     * @param OutputInterface $output An Output instance
579
     *
580
     * @return integer 0 if everything went fine, or an error code
581
     */
582
    public function doRun(InputInterface $input, OutputInterface $output)
583
    {
584
        $event = new Application\Console\Event($this, $input, $output);
585
        $this->dispatcher->dispatch('n98-magerun.application.console.run.before', $event);
586
587
        /**
588
         * only for compatibility to old versions.
589
         */
590
        $event = new ConsoleEvent(new Command('dummy'), $input, $output);
591
        $this->dispatcher->dispatch('console.run.before', $event);
592
593
        $input = $this->checkConfigCommandAlias($input);
594
        if ($output instanceof ConsoleOutput) {
595
            $this->checkVarDir($output->getErrorOutput());
596
        }
597
598
        return parent::doRun($input, $output);
599
    }
600
601
    /**
602
     * @param InputInterface $input
603
     *
604
     * @return ArgvInput|InputInterface
605
     */
606
    protected function checkConfigCommandAlias(InputInterface $input)
0 ignored issues
show
Coding Style introduced by
checkConfigCommandAlias uses the super-global variable $_SERVER which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

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

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
607
    {
608
        if ($this->hasConfigCommandAliases()) {
609
            foreach ($this->config['commands']['aliases'] as $alias) {
610
                if (is_array($alias)) {
611
                    $aliasCommandName = key($alias);
612
                    if ($input->getFirstArgument() == $aliasCommandName) {
613
                        $aliasCommandParams = array_slice(
614
                            BinaryString::trimExplodeEmpty(' ', $alias[$aliasCommandName]),
615
                            1
616
                        );
617
                        if (count($aliasCommandParams) > 0) {
618
                            // replace with aliased data
619
                            $mergedParams = array_merge(
620
                                array_slice($_SERVER['argv'], 0, 2),
621
                                $aliasCommandParams,
622
                                array_slice($_SERVER['argv'], 2)
623
                            );
624
                            $input = new ArgvInput($mergedParams);
625
                        }
626
                    }
627
                }
628
            }
629
            return $input;
630
        }
631
        return $input;
632
    }
633
634
    /**
635
     * @param InputInterface $input
636
     * @param OutputInterface $output
637
     * @return int
638
     */
639
    public function run(InputInterface $input = null, OutputInterface $output = null)
640
    {
641
        if (null === $input) {
642
            $input = new ArgvInput();
643
        }
644
645
        if (null === $output) {
646
            $output = new ConsoleOutput();
647
        }
648
        $this->_addOutputStyles($output);
649
        if ($output instanceof ConsoleOutput) {
650
            $this->_addOutputStyles($output->getErrorOutput());
651
        }
652
653
        $this->configureIO($input, $output);
654
655
        try {
656
            $this->init(array(), $input, $output);
657
        } catch (Exception $e) {
658
            $output = new ConsoleOutput();
659
            $this->renderException($e, $output->getErrorOutput());
660
        }
661
662
        $return = parent::run($input, $output);
663
664
        // Fix for no return values -> used in interactive shell to prevent error output
665
        if ($return === null) {
666
            return 0;
667
        }
668
669
        return $return;
670
    }
671
672
    /**
673
     * @param array $initConfig
674
     * @param InputInterface $input
675
     * @param OutputInterface $output
676
     *
677
     * @return void
678
     */
679
    public function init(array $initConfig = array(), InputInterface $input = null, OutputInterface $output = null)
680
    {
681
        if ($this->_isInitialized) {
682
            return;
683
        }
684
685
        // Suppress DateTime warnings
686
        date_default_timezone_set(@date_default_timezone_get());
687
688
        // Initialize EventDispatcher early
689
        $this->dispatcher = new EventDispatcher();
690
        $this->setDispatcher($this->dispatcher);
691
692
        if (null === $input) {
693
            $input = new ArgvInput();
694
        }
695
696
        if (null === $output) {
697
            $output = new NullOutput();
698
        }
699
700
        // initialize config
701
        $configLoader        = $this->getConfigurationLoader($initConfig, $output);
702
        $loadExternalConfig  = !$this->_checkSkipConfigOption($input);
703
        $this->partialConfig = $configLoader->getPartialConfig($loadExternalConfig);
704
        $this->detectMagento($input, $output);
705
        $configLoader->loadStageTwo($this->_magentoRootFolder, $loadExternalConfig, $this->_magerunStopFileFolder);
706
707
        $this->config = $configLoader->toArray();
708
709
        if ($this->autoloader) {
710
            $this->registerCustomAutoloaders();
711
            $this->registerEventSubscribers();
712
            $this->registerCustomCommands();
713
        }
714
715
        $this->registerHelpers();
716
717
        $this->_isInitialized = true;
718
    }
719
720
    /**
721
     * @param array $initConfig
722
     * @param InputInterface $input
723
     * @param OutputInterface $output
724
     */
725
    public function reinit($initConfig = array(), InputInterface $input = null, OutputInterface $output = null)
726
    {
727
        $this->_isInitialized = false;
728
        $this->_magentoDetected = false;
729
        $this->_magentoRootFolder = null;
730
        $this->init($initConfig, $input, $output);
731
    }
732
733
    /**
734
     * @return void
735
     */
736
    protected function registerEventSubscribers()
737
    {
738
        foreach ($this->config['event']['subscriber'] as $subscriberClass) {
739
            $subscriber = new $subscriberClass();
740
            $this->dispatcher->addSubscriber($subscriber);
741
        }
742
    }
743
744
    /**
745
     * @param InputInterface $input
746
     * @return bool
747
     */
748
    protected function _checkSkipConfigOption(InputInterface $input)
749
    {
750
        return $input->hasParameterOption('--skip-config');
751
    }
752
753
    /**
754
     * @param InputInterface $input
755
     * @return string
756
     */
757
    protected function _checkRootDirOption(InputInterface $input)
758
    {
759
        $definedRootDir = $input->getParameterOption('--root-dir');
760
761
        if (!empty($definedRootDir)) {
762
            if ($definedRootDir[0] == '~') {
763
                $definedRootDir = OperatingSystem::getHomeDir() . substr($definedRootDir, 1);
764
            }
765
766
            $folder = realpath($definedRootDir);
767
            $this->_directRootDir = true;
768
            if (is_dir($folder)) {
769
                \chdir($folder);
770
771
                return;
772
            }
773
        }
774
    }
775
776
    /**
777
     * @param bool $soft
778
     * @return void
779
     */
780
    protected function _initMagento1($soft = false)
781
    {
782
        if (!class_exists('Mage', false)) {
783
            // Create a new AutoloadRestorer to capture currenjt auto-öpaders
784
            $restorer = new AutoloadRestorer();
785
            // require app/Mage.php from Magento in a function of it's own to have it's own variable scope
786
            $this->requireOnce($this->_magentoRootFolder . '/app/Mage.php');
787
            // Restore auto-loaders that might be removed by extensions that overwrite Varien/Autoload
788
            $restorer->restore();
789
        }
790
791
        // skip Mage::app init routine and return
792
        if ($soft === true) {
793
            return;
794
        }
795
796
        $initSettings = $this->config['init'];
797
798
        \Mage::app($initSettings['code'], $initSettings['type'], $initSettings['options']);
799
    }
800
801
    /**
802
     * use require-once inside a function with it's own variable scope w/o any other variables
803
     * and $this unbound.
804
     *
805
     * @param string $path
806
     */
807
    private function requireOnce($path)
808
    {
809
        $requireOnce = function () {
810
            require_once  func_get_arg(0);
811
        };
812
        if (50400 <= PHP_VERSION_ID) {
813
            $requireOnce->bindTo(null);
814
        }
815
816
        $requireOnce($path);
817
    }
818
819
    /**
820
     * show compatibility notice about Magento 2
821
     */
822
    protected function _initMagento2()
823
    {
824
        $magento2Hint = <<<'MAGENTO2HINT'
825
You are running a Magento 2 instance. This version of n98-magerun is not compatible
826
with Magento 2. Please use n98-magerun2 for this shop.
827
828
A current version of the software can be downloaded on github.
829
830
<info>Download with curl
831
------------------</info>
832
833
    <comment>curl -sS https://files.magerun.net/n98-magerun2.phar -O</comment>
834
835
<info>Download with wget
836
------------------</info>
837
838
    <comment>wget https://files.magerun.net/n98-magerun2.phar</comment>
839
840
MAGENTO2HINT;
841
842
        $output = new ConsoleOutput();
843
844
845
        /** @var $formatter FormatterHelper */
846
        $formatter = $this->getHelperSet()->get('formatter');
847
848
        $output->writeln(array(
849
            '',
850
            $formatter->formatBlock('Compatibility Notice', 'bg=blue;fg=white', true),
851
            ''
852
        ));
853
854
        $output->writeln($magento2Hint);
855
856
        throw new RuntimeException('This version of n98-magerun is not compatible with Magento 2');
857
    }
858
859
    /**
860
     * @return EventDispatcher
861
     */
862
    public function getDispatcher()
863
    {
864
        return $this->dispatcher;
865
    }
866
867
    /**
868
     * @param array $initConfig
869
     * @param OutputInterface $output
870
     * @return ConfigurationLoader
871
     */
872
    public function getConfigurationLoader(array $initConfig, OutputInterface $output)
873
    {
874
        if ($this->configurationLoader === null) {
875
            $this->configurationLoader = new ConfigurationLoader(
876
                ArrayFunctions::mergeArrays($this->config, $initConfig),
877
                $this->isPharMode(),
878
                $output
879
            );
880
        }
881
882
        return $this->configurationLoader;
883
    }
884
885
    /**
886
     * @param ConfigurationLoader $configurationLoader
887
     *
888
     * @return $this
889
     */
890
    public function setConfigurationLoader($configurationLoader)
891
    {
892
        $this->configurationLoader = $configurationLoader;
893
894
        return $this;
895
    }
896
897
    /**
898
     * @param OutputInterface $output
899
     */
900
    protected function _addOutputStyles(OutputInterface $output)
901
    {
902
        $output->getFormatter()->setStyle('debug', new OutputFormatterStyle('magenta', 'white'));
903
        $output->getFormatter()->setStyle('warning', new OutputFormatterStyle('red', 'yellow', array('bold')));
904
    }
905
}
906