Completed
Push — develop ( 6abc8a...fc21c0 )
by Tom
04:23
created

Application::_initMagento1()   B

Complexity

Conditions 1
Paths 1

Size

Total Lines 34
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 4
Bugs 1 Features 1
Metric Value
c 4
b 1
f 1
dl 0
loc 34
rs 8.8571
cc 1
eloc 12
nc 1
nop 0
1
<?php
2
3
namespace N98\Magento;
4
5
use Composer\Autoload\ClassLoader;
6
use Magento\Framework\ObjectManager\ObjectManager;
7
use Magento\Mtf\EntryPoint\EntryPoint;
8
use N98\Magento\Application\Config;
9
use N98\Magento\Application\ConfigurationLoader;
10
use N98\Magento\Application\Console\Events;
11
use N98\Magento\Application\Option\RootDir as RootDirOption;
12
use N98\Util\Console\Helper\MagentoHelper;
13
use N98\Util\Console\Helper\TwigHelper;
14
use N98\Util\OperatingSystem;
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-magerun2';
35
36
    /**
37
     * @var string
38
     */
39
    const APP_VERSION = '1.1.17';
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
     * @var ClassLoader
64
     */
65
    protected $autoloader;
66
67
    /**
68
     * @var Config
69
     */
70
    protected $config;
71
72
    /**
73
     * @var string
74
     */
75
    protected $_magentoRootFolder = null;
76
77
    /**
78
     * @var bool
79
     */
80
    protected $_magentoEnterprise = false;
81
82
    /**
83
     * @var int
84
     */
85
    protected $_magentoMajorVersion = self::MAGENTO_MAJOR_VERSION_2;
86
87
    /**
88
     * @var EntryPoint
89
     */
90
    protected $_magento2EntryPoint = null;
91
92
    /**
93
     * @var bool
94
     */
95
    protected $_isPharMode = false;
96
97
    /**
98
     * @var bool
99
     */
100
    protected $_magerunStopFileFound = false;
101
102
    /**
103
     * @var string
104
     */
105
    protected $_magerunStopFileFolder = null;
106
107
    /**
108
     * @var bool
109
     */
110
    protected $_isInitialized = false;
111
112
    /**
113
     * @var EventDispatcher
114
     */
115
    protected $dispatcher;
116
117
    /**
118
     * If root dir is set by root-dir option this flag is true
119
     *
120
     * @var bool
121
     */
122
    protected $_directRootDir = false;
123
124
    /**
125
     * @var bool
126
     */
127
    protected $_magentoDetected = false;
128
129
    /**
130
     * @var ObjectManager
131
     */
132
    protected $_objectManager = null;
133
134
    /**
135
     * @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...
136
     */
137
    public function __construct($autoloader = null)
138
    {
139
        $this->autoloader = $autoloader;
140
        parent::__construct(self::APP_NAME, self::APP_VERSION);
141
    }
142
143
    /**
144
     * @return InputDefinition
145
     */
146
    protected function getDefaultInputDefinition()
147
    {
148
        $inputDefinition = parent::getDefaultInputDefinition();
149
150
        /**
151
         * Root dir
152
         */
153
        $rootDirOption = new InputOption(
154
            '--root-dir',
155
            '',
156
            InputOption::VALUE_OPTIONAL,
157
            'Force magento root dir. No auto detection'
158
        );
159
        $inputDefinition->addOption($rootDirOption);
160
161
        /**
162
         * Skip config
163
         */
164
        $skipExternalConfig = new InputOption(
165
            '--skip-config',
166
            '',
167
            InputOption::VALUE_NONE,
168
            'Do not load any custom config.'
169
        );
170
        $inputDefinition->addOption($skipExternalConfig);
171
172
        /**
173
         * Skip root check
174
         */
175
        $skipExternalConfig = new InputOption(
176
            '--skip-root-check',
177
            '',
178
            InputOption::VALUE_NONE,
179
            'Do not check if n98-magerun runs as root'
180
        );
181
        $inputDefinition->addOption($skipExternalConfig);
182
183
        /**
184
         * Skip core commands
185
         */
186
        $skipMagento2CoreCommands = new InputOption(
187
            '--skip-core-commands',
188
            '',
189
            InputOption::VALUE_OPTIONAL,
190
            'Do not include Magento 2 core commands'
191
        );
192
        $inputDefinition->addOption($skipMagento2CoreCommands);
193
194
        return $inputDefinition;
195
    }
196
197
    /**
198
     * Search for magento root folder
199
     *
200
     * @param InputInterface|null $input [optional]
201
     * @param OutputInterface|null $output [optional]
202
     * @return void
203
     */
204
    public function detectMagento(InputInterface $input = null, OutputInterface $output = null)
205
    {
206
        // do not detect magento twice
207
        if ($this->_magentoDetected) {
208
            return;
209
        }
210
211
        if ($this->getMagentoRootFolder() === null) {
212
            $this->_checkRootDirOption();
213
            $folder = OperatingSystem::getCwd();
214
        } else {
215
            $folder = $this->getMagentoRootFolder();
216
        }
217
218
        $this->getHelperSet()->set(new MagentoHelper($input, $output), 'magento');
219
        $magentoHelper = $this->getHelperSet()->get('magento');
220
        /* @var $magentoHelper MagentoHelper */
221
        if (!$this->_directRootDir) {
222
            $subFolders = $this->config->getDetectSubFolders();
223
        } else {
224
            $subFolders = array();
225
        }
226
227
        $this->_magentoDetected = $magentoHelper->detect($folder, $subFolders);
228
        $this->_magentoRootFolder = $magentoHelper->getRootFolder();
229
        $this->_magentoEnterprise = $magentoHelper->isEnterpriseEdition();
230
        $this->_magentoMajorVersion = $magentoHelper->getMajorVersion();
231
        $this->_magerunStopFileFound = $magentoHelper->isMagerunStopFileFound();
232
        $this->_magerunStopFileFolder = $magentoHelper->getMagerunStopFileFolder();
233
    }
234
235
    /**
236
     * Add own helpers to helperset.
237
     *
238
     * @return void
239
     */
240
    protected function registerHelpers()
241
    {
242
        $helperSet = $this->getHelperSet();
243
        $config = $this->config->getConfig();
244
245
        // Twig
246
        $twigBaseDirs = array(
247
            __DIR__ . '/../../../res/twig'
248
        );
249
        if (isset($config['twig']['baseDirs']) && is_array($config['twig']['baseDirs'])) {
250
            $twigBaseDirs = array_merge(array_reverse($config['twig']['baseDirs']), $twigBaseDirs);
251
        }
252
        $helperSet->set(new TwigHelper($twigBaseDirs), 'twig');
253
254
        foreach ($config['helpers'] as $helperName => $helperClass) {
255
            if (class_exists($helperClass)) {
256
                $helperSet->set(new $helperClass(), $helperName);
257
            }
258
        }
259
    }
260
261
    /**
262
     * Try to bootstrap magento 2 and load cli application
263
     *
264
     * @param OutputInterface $output
265
     */
266
    protected function registerMagentoCoreCommands(OutputInterface $output)
267
    {
268
        if ($this->getMagentoRootFolder()) {
269
            // Magento was found -> register core cli commands
270
            require_once $this->getMagentoRootFolder() . '/app/bootstrap.php';
271
272
            $coreCliApplication = new \Magento\Framework\Console\Cli();
273
            $coreCliApplicationCommands = $coreCliApplication->all();
274
275
            foreach ($coreCliApplicationCommands as $coreCliApplicationCommand) {
276
                if (OutputInterface::VERBOSITY_DEBUG <= $output->getVerbosity()) {
277
                    $output->writeln(
278
                        sprintf(
279
                            '<debug>Add core command </debug> <info>%s</info> -> <comment>%s</comment>',
280
                            $coreCliApplicationCommand->getName(),
281
                            get_class($coreCliApplicationCommand)
282
                        )
283
                    );
284
                }
285
                $this->add($coreCliApplicationCommand);
286
            }
287
        }
288
    }
289
290
    /**
291
     * Override standard command registration. We want alias support.
292
     *
293
     * @param \Symfony\Component\Console\Command\Command $command
294
     * @return \Symfony\Component\Console\Command\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...
295
     */
296
    public function add(Command $command)
297
    {
298
        if ($this->config) {
299
            $this->config->registerConfigCommandAlias($command);
300
        }
301
302
        return parent::add($command);
303
    }
304
305
    /**
306
     * @param bool $mode
307
     */
308
    public function setPharMode($mode)
309
    {
310
        $this->_isPharMode = $mode;
311
    }
312
313
    /**
314
     * @return bool
315
     */
316
    public function isPharMode()
317
    {
318
        return $this->_isPharMode;
319
    }
320
321
    /**
322
     * @TODO Move logic into "EventSubscriber"
323
     *
324
     * @param OutputInterface $output
325
     * @return null|false
326
     */
327
    public function checkVarDir(OutputInterface $output)
328
    {
329
        $tempVarDir = sys_get_temp_dir() . '/magento/var';
330
        if (!OutputInterface::VERBOSITY_NORMAL <= $output->getVerbosity() && !is_dir($tempVarDir)) {
331
            return;
332
        }
333
334
        $this->detectMagento(null, $output);
335
        /* If magento is not installed yet, don't check */
336
        if ($this->_magentoRootFolder === null
337
            || !file_exists($this->_magentoRootFolder . '/app/etc/env.php')
338
        ) {
339
            return;
340
        }
341
342
        try {
343
            $this->initMagento();
344
        } catch (\Exception $e) {
345
            $message = 'Cannot initialize Magento. Please check your configuration. '
346
                . 'Some n98-magerun command will not work. Got message: ';
347
            if (OutputInterface::VERBOSITY_VERY_VERBOSE <= $output->getVerbosity()) {
348
                $message .= $e->getTraceAsString();
349
            } else {
350
                $message .= $e->getMessage();
351
            }
352
            $output->writeln($message);
353
354
            return;
355
        }
356
357
        $configOptions = new \Mage_Core_Model_Config_Options();
358
        $currentVarDir = $configOptions->getVarDir();
359
360
        if ($currentVarDir == $tempVarDir) {
361
            $output->writeln(
362
                sprintf('<warning>Fallback folder %s is used in n98-magerun</warning>', $tempVarDir)
363
            );
364
            $output->writeln('');
365
            $output->writeln(
366
                'n98-magerun is using the fallback folder. If there is another folder configured for Magento, '
367
                . 'this can cause serious problems.'
368
            );
369
            $output->writeln(
370
                'Please refer to https://github.com/netz98/n98-magerun/wiki/File-system-permissions '
371
                . 'for more information.'
372
            );
373
            $output->writeln('');
374
        } else {
375
            $output->writeln(sprintf(
376
                '<warning>Folder %s found, but not used in n98-magerun</warning>',
377
                $tempVarDir
378
            ));
379
            $output->writeln('');
380
            $output->writeln(
381
                sprintf(
382
                    'This might cause serious problems. n98-magerun is using the configured var-folder '
383
                    . '<comment>%s</comment>',
384
                    $currentVarDir
385
                )
386
            );
387
            $output->writeln(
388
                'Please refer to https://github.com/netz98/n98-magerun/wiki/File-system-permissions '
389
                . 'for more information.'
390
            );
391
            $output->writeln('');
392
393
            return false;
394
        }
395
    }
396
397
    /**
398
     * Loads and initializes the Magento application
399
     *
400
     * @return bool false if magento root folder is not set, true otherwise
401
     */
402
    public function initMagento()
403
    {
404
        if ($this->getMagentoRootFolder() !== null) {
405
            if (self::MAGENTO_MAJOR_VERSION_2 === $this->_magentoMajorVersion) {
406
                $this->_initMagento2();
407
            } else {
408
                $this->_initMagento1();
409
            }
410
411
            return true;
412
        }
413
414
        return false;
415
    }
416
417
    /**
418
     * @return string
419
     */
420
    public function getHelp()
421
    {
422
        return self::$logo . parent::getHelp();
423
    }
424
425
    public function getLongVersion()
426
    {
427
        return parent::getLongVersion() . ' by <info>netz98 new media GmbH</info>';
428
    }
429
430
    /**
431
     * @return boolean
432
     */
433
    public function isMagentoEnterprise()
434
    {
435
        return $this->_magentoEnterprise;
436
    }
437
438
    /**
439
     * @return string
440
     */
441
    public function getMagentoRootFolder()
442
    {
443
        return $this->_magentoRootFolder;
444
    }
445
446
    /**
447
     * @param string $magentoRootFolder
448
     */
449
    public function setMagentoRootFolder($magentoRootFolder)
450
    {
451
        $this->_magentoRootFolder = $magentoRootFolder;
452
    }
453
454
    /**
455
     * @return int
456
     */
457
    public function getMagentoMajorVersion()
458
    {
459
        return $this->_magentoMajorVersion;
460
    }
461
462
    /**
463
     * @return ClassLoader
464
     */
465
    public function getAutoloader()
466
    {
467
        return $this->autoloader;
468
    }
469
470
    /**
471
     * @param ClassLoader $autoloader
472
     */
473
    public function setAutoloader(ClassLoader $autoloader)
474
    {
475
        $this->autoloader = $autoloader;
476
    }
477
478
    /**
479
     * @return array
480
     */
481
    public function getConfig()
482
    {
483
        return $this->config->getConfig();
484
    }
485
486
    /**
487
     * @param array $config
488
     */
489
    public function setConfig($config)
490
    {
491
        $this->config->setConfig($config);
492
    }
493
494
    /**
495
     * @return boolean
496
     */
497
    public function isMagerunStopFileFound()
498
    {
499
        return $this->_magerunStopFileFound;
500
    }
501
502
    /**
503
     * Runs the current application with possible command aliases
504
     *
505
     * @param InputInterface $input An Input instance
506
     * @param OutputInterface $output An Output instance
507
     *
508
     * @return integer 0 if everything went fine, or an error code
509
     */
510
    public function doRun(InputInterface $input, OutputInterface $output)
511
    {
512
        $event = new Application\Console\Event($this, $input, $output);
513
        $this->dispatcher->dispatch(Events::RUN_BEFORE, $event);
514
515
        /**
516
         * only for compatibility to old versions.
517
         */
518
        $event = new ConsoleEvent(new Command('dummy'), $input, $output);
519
        $this->dispatcher->dispatch('console.run.before', $event);
520
521
        $input = $this->config->checkConfigCommandAlias($input);
522
        if ($output instanceof ConsoleOutput) {
523
            $this->checkVarDir($output->getErrorOutput());
524
        }
525
526
        return parent::doRun($input, $output);
527
    }
528
529
    /**
530
     * @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...
531
     * @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...
532
     *
533
     * @return int
534
     */
535
    public function run(InputInterface $input = null, OutputInterface $output = null)
536
    {
537
        if (null === $input) {
538
            $input = new ArgvInput();
539
        }
540
541
        if (null === $output) {
542
            $output = new ConsoleOutput();
543
        }
544
        $this->_addOutputStyles($output);
545
        if ($output instanceof ConsoleOutput) {
546
            $this->_addOutputStyles($output->getErrorOutput());
547
        }
548
549
        $this->configureIO($input, $output);
550
551
        try {
552
            $this->init(array(), $input, $output);
553
        } catch (\Exception $e) {
554
            $output = new ConsoleOutput();
555
            $this->renderException($e, $output);
556
        }
557
558
        $return = parent::run($input, $output);
559
560
        // Fix for no return values -> used in interactive shell to prevent error output
561
        if ($return === null) {
562
            return 0;
563
        }
564
565
        return $return;
566
    }
567
568
    /**
569
     * @param array $initConfig
570
     * @param InputInterface $input
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...
571
     * @param OutputInterface $output
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...
572
     *
573
     * @return void
574
     */
575
    public function init(array $initConfig = array(), InputInterface $input = null, OutputInterface $output = null)
576
    {
577
        if ($this->_isInitialized) {
578
            return;
579
        }
580
581
        // Suppress DateTime warnings
582
        date_default_timezone_set(@date_default_timezone_get());
583
584
        // Initialize EventDispatcher early
585
        $this->dispatcher = new EventDispatcher();
586
        $this->setDispatcher($this->dispatcher);
587
588
        if (null === $input) {
589
            $input = new ArgvInput();
590
        }
591
592
        if (null === $output) {
593
            $output = new ConsoleOutput();
594
        }
595
596
        if (null !== $this->config) {
597
            throw new UnexpectedValueException(sprintf('Config already initialized'));
598
        }
599
600
        $loadExternalConfig = !$this->_checkSkipConfigOption();
601
602
        $this->config = $config = new Config($initConfig, $this->isPharMode(), $output);
603
        $configLoader = $config->getLoader();
604
        $config->loadPartialConfig($loadExternalConfig);
605
        $this->detectMagento($input, $output);
606
        $configLoader->loadStageTwo($this->_magentoRootFolder, $loadExternalConfig, $this->_magerunStopFileFolder);
607
        $config->load();
608
609
        if ($autoloader = $this->autoloader) {
610
611
            /**
612
             * Include commands shipped by Magento 2 core
613
             */
614
            if (!$this->_checkSkipMagento2CoreCommandsOption()) {
615
                $this->registerMagentoCoreCommands($output);
616
            }
617
618
            $this->config->registerCustomAutoloaders($autoloader);
619
            $this->registerEventSubscribers();
620
            $config->registerCustomCommands($this);
621
        }
622
623
        $this->registerHelpers();
624
625
        $this->_isInitialized = true;
626
    }
627
628
    /**
629
     * @param array $initConfig [optional]
630
     * @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...
631
     * @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...
632
     */
633
    public function reinit($initConfig = array(), InputInterface $input = null, OutputInterface $output = null)
634
    {
635
        $this->_isInitialized = false;
636
        $this->config = null;
637
        $this->init($initConfig, $input, $output);
638
    }
639
640
    /**
641
     * @return void
642
     */
643
    protected function registerEventSubscribers()
644
    {
645
        $subscriberClasses = $this->config->getConfig()['event']['subscriber'];
646
        foreach ($subscriberClasses as $subscriberClass) {
647
            $subscriber = new $subscriberClass();
648
            $this->dispatcher->addSubscriber($subscriber);
649
        }
650
    }
651
652
    /**
653
     * @return bool
654
     */
655
    protected function _checkSkipConfigOption()
656
    {
657
        $skipConfigOption = getopt('', array('skip-config'));
658
659
        return count($skipConfigOption) > 0;
660
    }
661
662
    /**
663
     * @return bool
664
     */
665
    protected function _checkSkipMagento2CoreCommandsOption()
666
    {
667
        $skipConfigOption = getopt('', array('skip-core-commands'));
668
669
        getenv('MAGERUN_SKIP_CORE_COMMANDS') && $skipConfigOption[] = 1;
670
671
        return count($skipConfigOption) > 0;
672
    }
673
674
    /**
675
     * @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...
676
     */
677
    protected function _checkRootDirOption()
678
    {
679
        if (null !== $rootDir = RootDirOption::getArgument()) {
680
            $this->setRootDir($rootDir);
681
682
            return;
683
        }
684
685
        // TODO old-style getopt() check kept for transition reasons, other getopt() uses 2b removed as well
686
        $specialGlobalOptions = getopt('', array('root-dir:'));
687
        if (!$specialGlobalOptions) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $specialGlobalOptions of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
688
            return;
689
        }
690
        trigger_error('root-dir option should have been detected earlier');
691
        $this->setRootDir($specialGlobalOptions['root-dir']);
692
    }
693
694
    /**
695
     * @param string $path
696
     */
697
    private function setRootDir($path)
698
    {
699
        if (isset($path[0]) && '~' === $path[0]) {
700
            $path = OperatingSystem::getHomeDir() . substr($path, 1);
701
        }
702
703
        $folder = realpath($path);
704
        $this->_directRootDir = true;
705
        if (is_dir($folder)) {
706
            chdir($folder);
707
        }
708
    }
709
710
    /**
711
     * Show a hint that this is Magento 1 and how to obtain magerun for it
712
     */
713
    protected function _initMagento1()
714
    {
715
        $magento1Hint = <<<'MAGENTO1HINT'
716
You are running a Magento 1.x instance. This version of n98-magerun is not compatible
717
with Magento 1.x. Please use n98-magerun (version 1) for this shop.
718
719
A current version of the software can be downloaded on github.
720
721
<info>Download with curl
722
------------------</info>
723
724
    <comment>curl -O https://files.magerun.net/n98-magerun.phar</comment>
725
726
<info>Download with wget
727
------------------</info>
728
729
    <comment>wget https://files.magerun.net/n98-magerun.phar</comment>
730
731
MAGENTO1HINT;
732
733
        $output = new ConsoleOutput();
734
735
        /** @var $formatter FormatterHelper */
736
        $formatter = $this->getHelperSet()->get('formatter');
737
738
        $output->writeln(array(
739
            '',
740
            $formatter->formatBlock('Compatibility Notice', 'bg=blue;fg=white', true),
741
            '',
742
            $magento1Hint,
743
        ));
744
745
        throw new \RuntimeException('Incompatible Magento version');
746
    }
747
748
    /**
749
     * @return void
750
     */
751
    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...
752
    {
753
        require_once $this->getMagentoRootFolder() . '/app/bootstrap.php';
754
755
        $params = $_SERVER;
756
        $params[\Magento\Store\Model\StoreManager::PARAM_RUN_CODE] = 'admin';
757
        $params[\Magento\Store\Model\Store::CUSTOM_ENTRY_POINT_PARAM] = true;
758
        $params['entryPoint'] = basename(__FILE__);
759
760
        $bootstrap = \Magento\Framework\App\Bootstrap::create(BP, $params);
761
        /** @var \Magento\Framework\App\Cron $app */
762
        $app = $bootstrap->createApplication('N98\Magento\Framework\App\Magerun', []);
763
        /* @var $app \N98\Magento\Framework\App\Magerun */
764
        $app->launch();
765
766
        $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...
767
    }
768
769
    /**
770
     * @return EventDispatcher
771
     */
772
    public function getDispatcher()
773
    {
774
        return $this->dispatcher;
775
    }
776
777
    /**
778
     * @param ConfigurationLoader $configurationLoader
779
     */
780
    public function setConfigurationLoader(ConfigurationLoader $configurationLoader)
781
    {
782
        $this->config->setConfigurationLoader($configurationLoader);
783
    }
784
785
    /**
786
     * @param OutputInterface $output
787
     */
788
    protected function _addOutputStyles(OutputInterface $output)
789
    {
790
        $output->getFormatter()->setStyle('debug', new OutputFormatterStyle('magenta', 'white'));
791
        $output->getFormatter()->setStyle('warning', new OutputFormatterStyle('red', 'yellow', array('bold')));
792
    }
793
794
    /**
795
     * @return ObjectManager
796
     */
797
    public function getObjectManager()
798
    {
799
        return $this->_objectManager;
800
    }
801
}
802