Completed
Push — master ( 1dd7d1...0c5b7b )
by Tom
09:54 queued 05:02
created

Application::checkVarDir()   B

Complexity

Conditions 8
Paths 6

Size

Total Lines 57
Code Lines 40

Duplication

Lines 0
Ratio 0 %

Importance

Changes 4
Bugs 1 Features 1
Metric Value
c 4
b 1
f 1
dl 0
loc 57
rs 7.2648
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\Framework\ObjectManager\ObjectManager;
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\Console\Helper\TwigHelper;
14
use N98\Util\OperatingSystem;
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\OutputInterface;
27
use Symfony\Component\EventDispatcher\EventDispatcher;
28
use UnexpectedValueException;
29
30
class Application extends BaseApplication
31
{
32
    /**
33
     * @var string
34
     */
35
    const APP_NAME = 'n98-magerun2';
36
37
    /**
38
     * @var string
39
     */
40
    const APP_VERSION = '1.1.17';
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 Config
69
     */
70
    protected $config;
71
72
    /**
73
     * @see \N98\Magento\Application::setConfigurationLoader()
74
     * @var ConfigurationLoader
75
     */
76
    private $configurationLoaderInjected;
77
78
    /**
79
     * @var string
80
     */
81
    protected $_magentoRootFolder = null;
82
83
    /**
84
     * @var bool
85
     */
86
    protected $_magentoEnterprise = false;
87
88
    /**
89
     * @var int
90
     */
91
    protected $_magentoMajorVersion = self::MAGENTO_MAJOR_VERSION_2;
92
93
    /**
94
     * @var EntryPoint
95
     */
96
    protected $_magento2EntryPoint = null;
97
98
    /**
99
     * @var bool
100
     */
101
    protected $_isPharMode = false;
102
103
    /**
104
     * @var bool
105
     */
106
    protected $_magerunStopFileFound = false;
107
108
    /**
109
     * @var string
110
     */
111
    protected $_magerunStopFileFolder = null;
112
113
    /**
114
     * @var bool
115
     */
116
    protected $_isInitialized = false;
117
118
    /**
119
     * @var EventDispatcher
120
     */
121
    protected $dispatcher;
122
123
    /**
124
     * If root dir is set by root-dir option this flag is true
125
     *
126
     * @var bool
127
     */
128
    protected $_directRootDir = false;
129
130
    /**
131
     * @var bool
132
     */
133
    protected $_magentoDetected = false;
134
135
    /**
136
     * @var ObjectManager
137
     */
138
    protected $_objectManager = null;
139
140
    /**
141
     * @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...
142
     */
143
    public function __construct($autoloader = null)
144
    {
145
        $this->autoloader = $autoloader;
146
        parent::__construct(self::APP_NAME, self::APP_VERSION);
147
    }
148
149
    /**
150
     * @return InputDefinition
151
     */
152
    protected function getDefaultInputDefinition()
153
    {
154
        $inputDefinition = parent::getDefaultInputDefinition();
155
156
        /**
157
         * Root dir
158
         */
159
        $rootDirOption = new InputOption(
160
            '--root-dir',
161
            '',
162
            InputOption::VALUE_OPTIONAL,
163
            'Force magento root dir. No auto detection'
164
        );
165
        $inputDefinition->addOption($rootDirOption);
166
167
        /**
168
         * Skip config
169
         */
170
        $skipExternalConfig = new InputOption(
171
            '--skip-config',
172
            '',
173
            InputOption::VALUE_NONE,
174
            'Do not load any custom config.'
175
        );
176
        $inputDefinition->addOption($skipExternalConfig);
177
178
        /**
179
         * Skip root check
180
         */
181
        $skipExternalConfig = new InputOption(
182
            '--skip-root-check',
183
            '',
184
            InputOption::VALUE_NONE,
185
            'Do not check if n98-magerun runs as root'
186
        );
187
        $inputDefinition->addOption($skipExternalConfig);
188
189
        /**
190
         * Skip core commands
191
         */
192
        $skipMagento2CoreCommands = new InputOption(
193
            '--skip-core-commands',
194
            '',
195
            InputOption::VALUE_OPTIONAL,
196
            'Do not include Magento 2 core commands'
197
        );
198
        $inputDefinition->addOption($skipMagento2CoreCommands);
199
200
        return $inputDefinition;
201
    }
202
203
    /**
204
     * Search for magento root folder
205
     *
206
     * @param InputInterface $input [optional]
1 ignored issue
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...
207
     * @param OutputInterface $output [optional]
1 ignored issue
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...
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->config->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
        $config = $this->config->getConfig();
258
259
        // Twig
260
        $twigBaseDirs = array(
261
            __DIR__ . '/../../../res/twig',
262
        );
263
        if (isset($config['twig']['baseDirs']) && is_array($config['twig']['baseDirs'])) {
264
            $twigBaseDirs = array_merge(array_reverse($config['twig']['baseDirs']), $twigBaseDirs);
265
        }
266
        $helperSet->set(new TwigHelper($twigBaseDirs), 'twig');
267
268
        foreach ($config['helpers'] as $helperName => $helperClass) {
269
            if (class_exists($helperClass)) {
270
                $helperSet->set(new $helperClass(), $helperName);
271
            }
272
        }
273
    }
274
275
    /**
276
     * Try to bootstrap magento 2 and load cli application
277
     *
278
     * @param OutputInterface $output
279
     */
280
    protected function registerMagentoCoreCommands(OutputInterface $output)
281
    {
282
        if (!$this->getMagentoRootFolder()) {
283
            return;
284
        }
285
286
        // Magento was found -> register core cli commands
287
        $this->requireOnce($this->_magentoRootFolder . '/app/bootstrap.php');
288
289
        $coreCliApplication = new \Magento\Framework\Console\Cli();
290
        $coreCliApplicationCommands = $coreCliApplication->all();
291
292
        foreach ($coreCliApplicationCommands as $coreCliApplicationCommand) {
293
            if (OutputInterface::VERBOSITY_DEBUG <= $output->getVerbosity()) {
294
                $output->writeln(
295
                    sprintf(
296
                        '<debug>Add core command </debug> <info>%s</info> -> <comment>%s</comment>',
297
                        $coreCliApplicationCommand->getName(),
298
                        get_class($coreCliApplicationCommand)
299
                    )
300
                );
301
            }
302
            $this->add($coreCliApplicationCommand);
303
        }
304
    }
305
306
    /**
307
     * Override standard command registration. We want alias support.
308
     *
309
     * @param Command $command
310
     *
311
     * @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...
312
     */
313
    public function add(Command $command)
314
    {
315
        if ($this->config) {
316
            $this->config->registerConfigCommandAlias($command);
317
        }
318
319
        return parent::add($command);
320
    }
321
322
    /**
323
     * @param bool $mode
324
     */
325
    public function setPharMode($mode)
326
    {
327
        $this->_isPharMode = $mode;
328
    }
329
330
    /**
331
     * @return bool
332
     */
333
    public function isPharMode()
334
    {
335
        return $this->_isPharMode;
336
    }
337
338
    /**
339
     * @TODO Move logic into "EventSubscriber"
340
     *
341
     * @param OutputInterface $output
342
     * @return null|false
343
     */
344
    public function checkVarDir(OutputInterface $output)
345
    {
346
        $tempVarDir = sys_get_temp_dir() . '/magento/var';
347
        if (!OutputInterface::VERBOSITY_NORMAL <= $output->getVerbosity() && !is_dir($tempVarDir)) {
348
            return;
349
        }
350
351
        $this->detectMagento(null, $output);
352
        /* If magento is not installed yet, don't check */
353
        if ($this->_magentoRootFolder === null
354
            || !file_exists($this->_magentoRootFolder . '/app/etc/env.php')
355
        ) {
356
            return;
357
        }
358
359
        try {
360
            $this->initMagento();
361
        } catch (Exception $e) {
362
            $message = 'Cannot initialize Magento. Please check your configuration. '
363
                . 'Some n98-magerun command will not work. Got message: ';
364
            if (OutputInterface::VERBOSITY_VERY_VERBOSE <= $output->getVerbosity()) {
365
                $message .= $e->getTraceAsString();
366
            } else {
367
                $message .= $e->getMessage();
368
            }
369
            $output->writeln($message);
370
371
            return;
372
        }
373
374
        $configOptions = new \Mage_Core_Model_Config_Options();
375
        $currentVarDir = $configOptions->getVarDir();
376
377
        if ($currentVarDir == $tempVarDir) {
378
            $output->writeln(array(
379
                sprintf('<warning>Fallback folder %s is used in n98-magerun</warning>', $tempVarDir),
380
                '',
381
                'n98-magerun is using the fallback folder. If there is another folder configured for Magento, this ' .
382
                'can cause serious problems.',
383
                'Please refer to https://github.com/netz98/n98-magerun/wiki/File-system-permissions ' .
384
                'for more information.',
385
                '',
386
            ));
387
        } else {
388
            $output->writeln(array(
389
                sprintf('<warning>Folder %s found, but not used in n98-magerun</warning>', $tempVarDir),
390
                '',
391
                "This might cause serious problems. n98-magerun is using the configured var-folder " .
392
                "<comment>$currentVarDir</comment>",
393
                'Please refer to https://github.com/netz98/n98-magerun/wiki/File-system-permissions ' .
394
                'for more information.',
395
                '',
396
            ));
397
398
            return false;
399
        }
400
    }
401
402
    /**
403
     * Loads and initializes the Magento application
404
     *
405
     * @param bool $soft
406
     *
407
     * @return bool false if magento root folder is not set, true otherwise
408
     */
409
    public function initMagento($soft = false)
410
    {
411
        if ($this->getMagentoRootFolder() === null) {
412
            return false;
413
        }
414
415
        $isMagento2 = $this->_magentoMajorVersion === self::MAGENTO_MAJOR_VERSION_2;
416
        if ($isMagento2) {
417
            $this->_initMagento2();
418
        } else {
419
            $this->_initMagento1($soft);
420
        }
421
422
        return true;
423
    }
424
425
    /**
426
     * @return string
427
     */
428
    public function getHelp()
429
    {
430
        return self::$logo . parent::getHelp();
431
    }
432
433
    public function getLongVersion()
434
    {
435
        return parent::getLongVersion() . ' by <info>netz98 new media GmbH</info>';
436
    }
437
438
    /**
439
     * @return boolean
440
     */
441
    public function isMagentoEnterprise()
442
    {
443
        return $this->_magentoEnterprise;
444
    }
445
446
    /**
447
     * @return string
448
     */
449
    public function getMagentoRootFolder()
450
    {
451
        return $this->_magentoRootFolder;
452
    }
453
454
    /**
455
     * @param string $magentoRootFolder
456
     */
457
    public function setMagentoRootFolder($magentoRootFolder)
458
    {
459
        $this->_magentoRootFolder = $magentoRootFolder;
460
    }
461
462
    /**
463
     * @return int
464
     */
465
    public function getMagentoMajorVersion()
466
    {
467
        return $this->_magentoMajorVersion;
468
    }
469
470
    /**
471
     * @return ClassLoader
472
     */
473
    public function getAutoloader()
474
    {
475
        return $this->autoloader;
476
    }
477
478
    /**
479
     * @param ClassLoader $autoloader
480
     */
481
    public function setAutoloader(ClassLoader $autoloader)
482
    {
483
        $this->autoloader = $autoloader;
484
    }
485
486
    /**
487
     * @return array
488
     */
489
    public function getConfig()
490
    {
491
        return $this->config->getConfig();
492
    }
493
494
    /**
495
     * @param array $config
496
     */
497
    public function setConfig($config)
498
    {
499
        $this->config->setConfig($config);
500
    }
501
502
    /**
503
     * @return boolean
504
     */
505
    public function isMagerunStopFileFound()
506
    {
507
        return $this->_magerunStopFileFound;
508
    }
509
510
    /**
511
     * Runs the current application with possible command aliases
512
     *
513
     * @param InputInterface $input An Input instance
514
     * @param OutputInterface $output An Output instance
515
     *
516
     * @return integer 0 if everything went fine, or an error code
517
     */
518
    public function doRun(InputInterface $input, OutputInterface $output)
519
    {
520
        $event = new Application\Console\Event($this, $input, $output);
521
        $this->dispatcher->dispatch(Events::RUN_BEFORE, $event);
522
523
        /**
524
         * only for compatibility to old versions.
525
         */
526
        $event = new ConsoleEvent(new Command('dummy'), $input, $output);
527
        $this->dispatcher->dispatch('console.run.before', $event);
528
529
        $input = $this->config->checkConfigCommandAlias($input);
530
        if ($output instanceof ConsoleOutput) {
531
            $this->checkVarDir($output->getErrorOutput());
532
        }
533
534
        return parent::doRun($input, $output);
535
    }
536
537
    /**
538
     * @param InputInterface $input [optional]
1 ignored issue
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...
539
     * @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...
540
     *
541
     * @return int
542
     */
543
    public function run(InputInterface $input = null, OutputInterface $output = null)
544
    {
545
        if (null === $input) {
546
            $input = new ArgvInput();
547
        }
548
549
        if (null === $output) {
550
            $output = new ConsoleOutput();
551
        }
552
        $this->_addOutputStyles($output);
553
        if ($output instanceof ConsoleOutput) {
554
            $this->_addOutputStyles($output->getErrorOutput());
555
        }
556
557
        $this->configureIO($input, $output);
558
559
        try {
560
            $this->init(array(), $input, $output);
561
        } catch (Exception $e) {
562
            $output = new ConsoleOutput();
563
            $this->renderException($e, $output->getErrorOutput());
564
        }
565
566
        $return = parent::run($input, $output);
567
568
        // Fix for no return values -> used in interactive shell to prevent error output
569
        if ($return === null) {
570
            return 0;
571
        }
572
573
        return $return;
574
    }
575
576
    /**
577
     * @param array $initConfig [optional]
578
     * @param InputInterface $input [optional]
1 ignored issue
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...
579
     * @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...
580
     *
581
     * @return void
582
     */
583
    public function init(array $initConfig = array(), InputInterface $input = null, OutputInterface $output = null)
584
    {
585
        if ($this->_isInitialized) {
586
            return;
587
        }
588
589
        // Suppress DateTime warnings
590
        date_default_timezone_set(@date_default_timezone_get());
591
592
        // Initialize EventDispatcher early
593
        $this->dispatcher = new EventDispatcher();
594
        $this->setDispatcher($this->dispatcher);
595
596
        if (null === $input) {
597
            $input = new ArgvInput();
598
        }
599
600
        if (null === $output) {
601
            $output = new ConsoleOutput();
602
        }
603
604
        if (null !== $this->config) {
605
            throw new UnexpectedValueException(sprintf('Config already initialized'));
606
        }
607
608
        $loadExternalConfig = !$this->_checkSkipConfigOption($input);
609
610
        $this->config = $config = new Config($initConfig, $this->isPharMode(), $output);
611
        if ($this->configurationLoaderInjected) {
612
            $config->setLoader($this->configurationLoaderInjected);
613
        }
614
        $config->loadPartialConfig($loadExternalConfig);
615
        $this->detectMagento($input, $output);
616
        $configLoader = $config->getLoader();
617
        $configLoader->loadStageTwo($this->_magentoRootFolder, $loadExternalConfig, $this->_magerunStopFileFolder);
618
        $config->load();
619
620
        if ($autoloader = $this->autoloader) {
621
            /**
622
             * Include commands shipped by Magento 2 core
623
             */
624
            if (!$this->_checkSkipMagento2CoreCommandsOption($input)) {
625
                $this->registerMagentoCoreCommands($output);
626
            }
627
            $config->registerCustomAutoloaders($autoloader);
628
            $this->registerEventSubscribers();
629
            $config->registerCustomCommands($this);
630
        }
631
632
        $this->registerHelpers();
633
634
        $this->_isInitialized = true;
635
    }
636
637
    /**
638
     * @param array $initConfig [optional]
639
     * @param InputInterface $input [optional]
1 ignored issue
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...
640
     * @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...
641
     */
642
    public function reinit($initConfig = array(), InputInterface $input = null, OutputInterface $output = null)
643
    {
644
        $this->_isInitialized = false;
645
        $this->_magentoDetected = false;
646
        $this->_magentoRootFolder = null;
647
        $this->config = null;
648
        $this->init($initConfig, $input, $output);
649
    }
650
651
    /**
652
     * @return void
653
     */
654
    protected function registerEventSubscribers()
655
    {
656
        $config = $this->config->getConfig();
657
        $subscriberClasses = $config['event']['subscriber'];
658
        foreach ($subscriberClasses as $subscriberClass) {
659
            $subscriber = new $subscriberClass();
660
            $this->dispatcher->addSubscriber($subscriber);
661
        }
662
    }
663
664
    /**
665
     * @param InputInterface $input
666
     * @return bool
667
     */
668
    protected function _checkSkipConfigOption(InputInterface $input)
669
    {
670
        return $input->hasParameterOption('--skip-config');
671
    }
672
673
    /**
674
     * @return bool
675
     */
676
    protected function _checkSkipMagento2CoreCommandsOption(InputInterface $input)
677
    {
678
        return $input->hasParameterOption('--skip-core-commands') || getenv('MAGERUN_SKIP_CORE_COMMANDS');
679
    }
680
681
    /**
682
     * @param InputInterface $input
683
     * @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...
684
     */
685
    protected function _checkRootDirOption(InputInterface $input)
686
    {
687
        $rootDir = $input->getParameterOption('--root-dir');
688
        if (is_string($rootDir)) {
689
            $this->setRootDir($rootDir);
690
        }
691
    }
692
693
    /**
694
     * Set root dir (chdir()) of magento directory
695
     *
696
     * @param string $path to Magento directory
697
     */
698
    private function setRootDir($path)
699
    {
700
        if (isset($path[0]) && '~' === $path[0]) {
701
            $path = OperatingSystem::getHomeDir() . substr($path, 1);
702
        }
703
704
        $folder = realpath($path);
705
        $this->_directRootDir = true;
706
        if (is_dir($folder)) {
707
            chdir($folder);
708
        }
709
    }
710
711
    /**
712
     * use require-once inside a function with it's own variable scope w/o any other variables
713
     * and $this unbound.
714
     *
715
     * @param string $path
716
     */
717
    private function requireOnce($path)
718
    {
719
        $requireOnce = function () {
720
            require_once func_get_arg(0);
721
        };
722
        if (50400 <= PHP_VERSION_ID) {
723
            $requireOnce->bindTo(null);
724
        }
725
726
        $requireOnce($path);
727
    }
728
729
    /**
730
     * @param bool $soft
731
     *
732
     * @return void
733
     */
734
    protected function _initMagento1($soft = false)
0 ignored issues
show
Unused Code introduced by
The parameter $soft 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...
735
    {
736
        $this->outputMagerunCompatibilityNotice('1');
737
    }
738
739
    /**
740
     * @return void
741
     */
742
    protected function _initMagento2()
0 ignored issues
show
Coding Style introduced by
_initMagento2 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...
743
    {
744
        $this->requireOnce($this->_magentoRootFolder . '/app/bootstrap.php');
745
746
        $params = $_SERVER;
747
        $params[\Magento\Store\Model\StoreManager::PARAM_RUN_CODE] = 'admin';
748
        $params[\Magento\Store\Model\Store::CUSTOM_ENTRY_POINT_PARAM] = true;
749
        $params['entryPoint'] = basename(__FILE__);
750
751
        $bootstrap = \Magento\Framework\App\Bootstrap::create(BP, $params);
752
        /** @var \Magento\Framework\App\Cron $app */
753
        $app = $bootstrap->createApplication('N98\Magento\Framework\App\Magerun', []);
754
        /* @var $app \N98\Magento\Framework\App\Magerun */
755
        $app->launch();
756
757
        $this->_objectManager = $app->getObjectManager();
0 ignored issues
show
Documentation Bug introduced by
It seems like $app->getObjectManager() of type object<Magento\Framework\ObjectManagerInterface> is incompatible with the declared type object<Magento\Framework...tManager\ObjectManager> of property $_objectManager.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
758
    }
759
760
    /**
761
     * Show a hint that this is Magento incompatible with Magerun and how to obtain the correct Magerun for it
762
     *
763
     * @param string $version of Magento, "1" or "2", that is incompatible
764
     */
765
    private function outputMagerunCompatibilityNotice($version)
766
    {
767
        $file = $version === '2' ? $version : '';
768
        $magentoHint = <<<MAGENTOHINT
769
You are running a Magento $version.x instance. This version of n98-magerun is not compatible
770
with Magento $version.x. Please use n98-magerun$version (version $version) for this shop.
771
772
A current version of the software can be downloaded on github.
773
774
<info>Download with curl
775
------------------</info>
776
777
    <comment>curl -O https://files.magerun.net/n98-magerun$file.phar</comment>
778
779
<info>Download with wget
780
------------------</info>
781
782
    <comment>wget https://files.magerun.net/n98-magerun$file.phar</comment>
783
784
MAGENTOHINT;
785
786
        $output = new ConsoleOutput();
787
788
        /** @var $formatter FormatterHelper */
789
        $formatter = $this->getHelperSet()->get('formatter');
790
791
        $output->writeln(array(
792
            '',
793
            $formatter->formatBlock('Compatibility Notice', 'bg=blue;fg=white', true),
794
            '',
795
            $magentoHint,
796
        ));
797
798
        throw new RuntimeException('This version of n98-magerun is not compatible with Magento ' . $version);
799
    }
800
801
    /**
802
     * @return EventDispatcher
803
     */
804
    public function getDispatcher()
805
    {
806
        return $this->dispatcher;
807
    }
808
809
    /**
810
     * @param ConfigurationLoader $configurationLoader
811
     */
812
    public function setConfigurationLoader(ConfigurationLoader $configurationLoader)
813
    {
814
        if ($this->config) {
815
            $this->config->setLoader($configurationLoader);
816
        } else {
817
            /* inject loader to be used later when config is created in */
818
            /* @see N98\Magento\Application::init() */
0 ignored issues
show
Unused Code Comprehensibility introduced by
38% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
819
            $this->configurationLoaderInjected = $configurationLoader;
820
        }
821
    }
822
823
    /**
824
     * @param OutputInterface $output
825
     */
826
    protected function _addOutputStyles(OutputInterface $output)
827
    {
828
        $output->getFormatter()->setStyle('debug', new OutputFormatterStyle('magenta', 'white'));
829
        $output->getFormatter()->setStyle('warning', new OutputFormatterStyle('red', 'yellow', array('bold')));
830
    }
831
832
    /**
833
     * @return ObjectManager
834
     */
835
    public function getObjectManager()
836
    {
837
        return $this->_objectManager;
838
    }
839
}
840