Completed
Push — develop ( 4c52c4...388caf )
by Tom
08:17
created

DownloadMagento::execute()   C

Complexity

Conditions 10
Paths 212

Size

Total Lines 63
Code Lines 35

Duplication

Lines 0
Ratio 0 %

Importance

Changes 5
Bugs 1 Features 0
Metric Value
dl 0
loc 63
rs 5.7241
c 5
b 1
f 0
cc 10
eloc 35
nc 212
nop 0

How to fix   Long Method    Complexity   

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\Command\Installer\SubCommand;
4
5
use N98\Magento\Command\SubCommand\AbstractSubCommand;
6
use N98\Util\Console\Helper\ComposerHelper;
7
use RuntimeException;
8
use Symfony\Component\Console\Output\OutputInterface;
9
use Symfony\Component\Process\ProcessBuilder;
10
11
class DownloadMagento extends AbstractSubCommand
12
{
13
    /**
14
     * @return void
15
     */
16
    public function execute()
17
    {
18
        if ($this->input->getOption('noDownload')) {
19
            return;
20
        }
21
22
        try {
23
            $this->checkMagentoConnectCredentials($this->output);
24
25
            $package = $this->config['magentoVersionData'];
26
            $this->config->setArray('magentoPackage', $package);
27
28
            if (file_exists($this->config->getString('installationFolder') . '/app/etc/env.php')) {
29
                $this->output->writeln('<error>A magento installation already exists in this folder </error>');
30
                return;
31
            }
32
33
            $args = [
34
                $this->config['composer_bin'],
35
                'create-project',
36
            ];
37
38
            // Add composer options
39
            foreach ($package['options'] as $optionName => $optionValue) {
40
                $args[] = '--' . $optionName . ($optionValue === true ? '' : '=' . $optionValue);
41
            }
42
43
            // Add arguments
44
            $args[] = $package['package'];
45
            $args[] = $this->config->getString('installationFolder');
46
            $args[] = $package['version'];
47
48
            if (OutputInterface::VERBOSITY_VERBOSE <= $this->output->getVerbosity()) {
49
                $args[] = '-vvv';
50
            }
51
52
            /**
53
             * @TODO use composer helper
54
             */
55
            $processBuilder = new ProcessBuilder($args);
56
57
            $process = $processBuilder->getProcess();
58
            $process->setInput($this->input);
59
            if (OutputInterface::VERBOSITY_VERBOSE <= $this->output->getVerbosity()) {
60
                $this->output->writeln($process->getCommandLine());
61
            }
62
63
            $process->setTimeout(86400);
64
            $process->start();
65
            $code =
66
            $process->wait(function ($type, $buffer) {
67
                $this->output->write($buffer, false, OutputInterface::OUTPUT_RAW);
68
            });
69
        } catch (\Exception $e) {
70
            $this->output->writeln('<error>' . $e->getMessage() . '</error>');
71
        }
72
73
        if (isset($code) && 0 !== $code) {
74
            throw new RuntimeException(
75
                'Non-zero exit code for composer create-project command: ' . $process->getCommandLine()
76
            );
77
        }
78
    }
79
80
    /**
81
     * construct a folder to where magerun will download the source to,
82
     * cache git/hg repositories under COMPOSER_HOME
83
     *
84
     * @param $composer
85
     * @param $package
86
     * @param $installationFolder
87
     *
88
     * @return string
89
     */
90
    protected function getTargetFolderByType($composer, $package, $installationFolder)
91
    {
92
        $type = $package->getSourceType();
93
        if ($this->getCommand()->isSourceTypeRepository($type)) {
94
            $targetPath = sprintf(
95
                '%s/%s/%s/%s',
96
                $composer->getConfig()->get('cache-dir'),
97
                '_n98_magerun_download',
98
                $type,
99
                preg_replace('{[^a-z0-9.]}i', '-', $package->getSourceUrl())
100
            );
101
        } else {
102
            $targetPath = sprintf(
103
                '%s/%s',
104
                $installationFolder,
105
                '_n98_magerun_download'
106
            );
107
        }
108
109
        return $targetPath;
110
    }
111
112
    /**
113
     * @param OutputInterface $output
114
     */
115
    protected function checkMagentoConnectCredentials(OutputInterface $output)
116
    {
117
        $configKey = 'http-basic.repo.magento.com';
118
119
        $composerHelper = $this->getCommand()->getHelper('composer');
120
        /** @var $composerHelper ComposerHelper */
121
        $authConfig = $composerHelper->getConfigValue($configKey);
122
123
        if (!isset($authConfig->username)
124
            || !isset($authConfig->password)
125
        ) {
126
            $this->output->writeln(array(
127
                '',
128
                $this->getCommand()
129
                    ->getHelperSet()
130
                    ->get('formatter')
131
                    ->formatBlock('Authentication', 'bg=blue;fg=white', true),
132
                '',
133
            ));
134
135
            $this->output->writeln(array(
136
                'You need to create a secury key. Login at magentocommerce.com.',
137
                'Developers -> Secure Keys. <info>Use public key as username and private key as password</info>',
138
                ''
139
            ));
140
            $dialog = $this->getCommand()->getHelper('dialog');
141
142
            $username = $dialog->askAndValidate(
143
                $output,
144
                '<comment>Please enter your public key: </comment>',
145
                function ($value) {
146
                    if ('' === trim($value)) {
147
                        throw new \Exception('The private key (auth token) can not be empty');
148
                    }
149
150
                    return $value;
151
                },
152
                20,
153
                false
154
            );
155
156
157
            $password = $dialog->askHiddenResponseAndValidate(
158
                $output,
159
                '<comment>Please enter your private key: </comment>',
160
                function ($value) {
161
                    if ('' === trim($value)) {
162
                        throw new \Exception('The private key (auth token) can not be empty');
163
                    }
164
165
                    return $value;
166
                },
167
                20,
168
                false
169
            );
170
171
            $composerHelper->setConfigValue($configKey, [$username, $password]);
172
        }
173
    }
174
}
175