Completed
Push — master ( 29ee36...16ede1 )
by Tom
03:58
created

AbstractMagentoCommand::saveCacheStatus()   B

Complexity

Conditions 5
Paths 4

Size

Total Lines 12
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 12
rs 8.8571
c 0
b 0
f 0
cc 5
eloc 7
nc 4
nop 2
1
<?php
2
3
namespace N98\Magento\Command;
4
5
use Composer\Factory as ComposerFactory;
6
use Composer\IO\ConsoleIO;
7
use Composer\Package\Loader\ArrayLoader as PackageLoader;
8
use Composer\Package\PackageInterface;
9
use Magento\Framework\ObjectManager\ObjectManager;
10
use Magento\Framework\ObjectManagerInterface;
11
use N98\Magento\Command\SubCommand\ConfigBag;
12
use N98\Magento\Command\SubCommand\SubCommandFactory;
13
use N98\Util\Console\Helper\InjectionHelper;
14
use N98\Util\Console\Helper\MagentoHelper;
15
use Symfony\Component\Console\Command\Command;
16
use Symfony\Component\Console\Helper\FormatterHelper;
17
use Symfony\Component\Console\Input\InputInterface;
18
use Symfony\Component\Console\Output\OutputInterface;
19
20
/**
21
 * Class AbstractMagentoCommand
22
 *
23
 * @package N98\Magento\Command
24
 *
25
 * @method \N98\Magento\Application getApplication() getApplication()
26
 */
27
abstract class AbstractMagentoCommand extends Command
28
{
29
    /**
30
     * @var int
31
     */
32
    const MAGENTO_MAJOR_VERSION_2 = 2;
33
34
    /**
35
     * @var string
36
     */
37
    const CONFIG_KEY_COMMANDS = 'commands';
38
39
    /**
40
     * @var string
41
     */
42
    protected $_magentoRootFolder = null;
43
44
    /**
45
     * @var int
46
     */
47
    protected $_magentoMajorVersion = self::MAGENTO_MAJOR_VERSION_2;
48
49
    /**
50
     * @var bool
51
     */
52
    protected $_magentoEnterprise = false;
53
54
    /**
55
     * @var array
56
     */
57
    protected $_deprecatedAlias = array();
58
59
    /**
60
     * @var array
61
     */
62
    protected $_websiteCodeMap = array();
63
64
    /**
65
     * @var ObjectManager
66
     */
67
    protected $_objectManager = null;
68
69
    /**
70
     * Initializes the command just after the input has been validated.
71
     *
72
     * This is mainly useful when a lot of commands extends one main command
73
     * where some things need to be initialized based on the input arguments and options.
74
     *
75
     * @param InputInterface $input An InputInterface instance
76
     * @param OutputInterface $output An OutputInterface instance
77
     */
78
    protected function initialize(InputInterface $input, OutputInterface $output)
79
    {
80
        $this->checkDeprecatedAliases($input, $output);
81
    }
82
83
    /**
84
     * @return ObjectManagerInterface
85
     */
86
    protected function getObjectManager()
87
    {
88
        return $this->getApplication()->getObjectManager();
89
    }
90
91
    /**
92
     * @param string|null $commandClass
93
     * @return array
94
     */
95
    protected function getCommandConfig($commandClass = null)
96
    {
97
        if ($commandClass === null) {
98
            $commandClass = get_class($this);
99
        }
100
        $configArray = $this->getApplication()->getConfig();
101
        if (isset($configArray[self::CONFIG_KEY_COMMANDS][$commandClass])) {
102
            return $configArray[self::CONFIG_KEY_COMMANDS][$commandClass];
103
        }
104
105
        return [];
106
    }
107
108
    /**
109
     * @param OutputInterface $output
110
     * @param string $text
111
     * @param string $style
112
     */
113
    protected function writeSection(OutputInterface $output, $text, $style = 'bg=blue;fg=white')
114
    {
115
        /** @var $formatter FormatterHelper */
116
        $formatter = $this->getHelper('formatter');
117
118
        $output->writeln(array(
119
            '',
120
            $formatter->formatBlock($text, $style, true),
121
            '',
122
        ));
123
    }
124
125
    /**
126
     * Bootstrap magento shop
127
     *
128
     * @return bool
129
     */
130
    protected function initMagento()
131
    {
132
        $init = $this->getApplication()->initMagento();
133
        if ($init) {
134
            $this->_magentoRootFolder = $this->getApplication()->getMagentoRootFolder();
135
        }
136
137
        return $init;
138
    }
139
140
    /**
141
     * Search for magento root folder
142
     *
143
     * @param OutputInterface $output
144
     * @param bool $silent print debug messages
145
     * @throws \RuntimeException
146
     */
147
    public function detectMagento(OutputInterface $output, $silent = true)
148
    {
149
        $this->getApplication()->detectMagento();
150
151
        $this->_magentoEnterprise = $this->getApplication()->isMagentoEnterprise();
152
        $this->_magentoRootFolder = $this->getApplication()->getMagentoRootFolder();
153
        $this->_magentoMajorVersion = $this->getApplication()->getMagentoMajorVersion();
154
155
        if (!$silent) {
156
            $editionString = ($this->_magentoEnterprise ? ' (Enterprise Edition) ' : '');
157
            $output->writeln(
158
                '<info>Found Magento ' . $editionString . 'in folder "' . $this->_magentoRootFolder . '"</info>'
159
            );
160
        }
161
162
        if (!empty($this->_magentoRootFolder)) {
163
            return;
164
        }
165
166
        throw new \RuntimeException('Magento folder could not be detected');
167
    }
168
169
    /**
170
     * @param InputInterface $input
171
     * @param OutputInterface $output
172
     * @return \Composer\Downloader\DownloadManager
173
     */
174
    public function getComposerDownloadManager($input, $output)
175
    {
176
        return $this->getComposer($input, $output)->getDownloadManager();
177
    }
178
179
    /**
180
     * @param array $config
181
     * @return PackageInterface
182
     */
183
    public function createComposerPackageByConfig(array $config)
184
    {
185
        $packageLoader = new PackageLoader();
186
187
        return $packageLoader->load($config);
188
    }
189
190
    /**
191
     * @param InputInterface $input
192
     * @param OutputInterface $output
193
     * @param array|PackageInterface $config
194
     * @param string $targetFolder
195
     * @param bool $preferSource
196
     * @return \Composer\Package\PackageInterface
197
     */
198
    public function downloadByComposerConfig(
199
        InputInterface $input,
200
        OutputInterface $output,
201
        $config,
202
        $targetFolder,
203
        $preferSource = true
204
    ) {
205
        $dm = $this->getComposerDownloadManager($input, $output);
206
        if (!$config instanceof PackageInterface) {
207
            $package = $this->createComposerPackageByConfig($config);
208
        } else {
209
            $package = $config;
210
        }
211
212
        $helper = new MagentoHelper();
213
        $helper->detect($targetFolder);
214
        if ($this->isSourceTypeRepository($package->getSourceType()) && $helper->getRootFolder() == $targetFolder) {
215
            $package->setInstallationSource('source');
216
            $this->checkRepository($package, $targetFolder);
217
            $dm->update($package, $package, $targetFolder);
218
        } else {
219
            $dm->download($package, $targetFolder, $preferSource);
220
        }
221
222
        return $package;
223
    }
224
225
    /**
226
     * brings locally cached repository up to date if it is missing the requested tag
227
     *
228
     * @param PackageInterface $package
229
     * @param string $targetFolder
230
     */
231
    protected function checkRepository(PackageInterface $package, $targetFolder)
232
    {
233
        if ($package->getSourceType() == 'git') {
234
            $command = sprintf(
235
                'cd %s && git rev-parse refs/tags/%s',
236
                escapeshellarg($targetFolder),
237
                escapeshellarg($package->getSourceReference())
238
            );
239
            $existingTags = shell_exec($command);
240
            if (!$existingTags) {
241
                $command = sprintf('cd %s && git fetch', escapeshellarg($targetFolder));
242
                shell_exec($command);
243
            }
244
        } elseif ($package->getSourceType() == 'hg') {
245
            $command = sprintf(
246
                'cd %s && hg log --template "{tags}" -r %s',
247
                escapeshellarg($targetFolder),
248
                escapeshellarg($package->getSourceReference())
249
            );
250
            $existingTag = shell_exec($command);
251
            if ($existingTag === $package->getSourceReference()) {
252
                $command = sprintf('cd %s && hg pull', escapeshellarg($targetFolder));
253
                shell_exec($command);
254
            }
255
        }
256
    }
257
258
    /**
259
     * @param string $type
260
     *
261
     * @return bool
262
     */
263
    public function isSourceTypeRepository($type)
264
    {
265
        return in_array($type, array('git', 'hg'));
266
    }
267
268
    /**
269
     * obtain composer
270
     *
271
     * @param InputInterface $input
272
     * @param OutputInterface $output
273
     *
274
     * @return \Composer\Composer
275
     */
276
    public function getComposer(InputInterface $input, OutputInterface $output)
277
    {
278
        $io = new ConsoleIO($input, $output, $this->getHelperSet());
0 ignored issues
show
Bug introduced by
It seems like $this->getHelperSet() can be null; however, __construct() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
279
        $config = array(
280
            'config' => array(
281
                'secure-http' => false,
282
            ),
283
        );
284
285
        return ComposerFactory::create($io, $config);
286
    }
287
288
    /**
289
     * @param string $alias
290
     * @param string $message
291
     * @return AbstractMagentoCommand
292
     */
293
    protected function addDeprecatedAlias($alias, $message)
294
    {
295
        $this->_deprecatedAlias[$alias] = $message;
296
297
        return $this;
298
    }
299
300
    /**
301
     * @param InputInterface $input
302
     * @param OutputInterface $output
303
     */
304
    protected function checkDeprecatedAliases(InputInterface $input, OutputInterface $output)
305
    {
306
        if (isset($this->_deprecatedAlias[$input->getArgument('command')])) {
307
            $output->writeln(
308
                '<error>Deprecated:</error> <comment>' . $this->_deprecatedAlias[$input->getArgument('command')] .
309
                '</comment>'
310
            );
311
        }
312
    }
313
314
    /**
315
     * @param string $value
316
     * @return bool
317
     */
318
    protected function _parseBoolOption($value)
319
    {
320
        return in_array(strtolower($value), array('y', 'yes', 1, 'true'));
321
    }
322
323
    /**
324
     * @param string $value
325
     * @return bool
326
     */
327
    public function parseBoolOption($value)
328
    {
329
        return $this->_parseBoolOption($value);
330
    }
331
332
    /**
333
     * @param string $value
334
     * @return string
335
     */
336
    public function formatActive($value)
337
    {
338
        if (in_array($value, array(1, 'true'))) {
339
            return 'active';
340
        }
341
342
        return 'inactive';
343
    }
344
345
    /**
346
     * @param InputInterface $input
347
     * @param OutputInterface $output
348
     *
349
     * @return int
350
     */
351
    public function run(InputInterface $input, OutputInterface $output)
352
    {
353
        $this->getHelperSet()->setCommand($this);
354
355
        $this->injectObjects($output);
356
357
        return parent::run($input, $output);
358
    }
359
360
    /**
361
     * @param OutputInterface $output
362
     */
363
    public function injectObjects(OutputInterface $output)
364
    {
365
        /* @var $injectionHelper InjectionHelper */
366
        if (method_exists($this, 'inject')) {
367
            $this->detectMagento($output);
368
            $this->initMagento();
369
370
            /* @var $injectionHelper InjectionHelper */
371
            $injectionHelper = $this->getHelper('injection');
372
            $injectionHelper->methodInjection(
373
                $this,
374
                'inject',
375
                $this->getObjectManager()
376
            );
377
        }
378
    }
379
380
    /**
381
     * @param InputInterface $input
382
     * @param OutputInterface $output
383
     * @param string $baseNamespace If this is set we can use relative class names.
384
     *
385
     * @return SubCommandFactory
386
     */
387
    protected function createSubCommandFactory(
388
        InputInterface $input,
389
        OutputInterface $output,
390
        $baseNamespace = ''
391
    ) {
392
        $configBag = new ConfigBag();
393
394
        $commandConfig = $this->getCommandConfig();
395
        if (empty($commandConfig)) {
396
            $commandConfig = array();
397
        }
398
399
        return new SubCommandFactory(
400
            $this,
401
            $baseNamespace,
402
            $input,
403
            $output,
404
            $commandConfig,
405
            $configBag
406
        );
407
    }
408
}
409