NewCommand::findComposer()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 8
rs 10
c 0
b 0
f 0
cc 2
nc 2
nop 0
1
<?php
2
3
namespace Cortex\Installer\Console;
4
5
use ZipArchive;
6
use RuntimeException;
7
use GuzzleHttp\Client;
8
use Symfony\Component\Process\Process;
9
use Symfony\Component\Filesystem\Filesystem;
10
use Symfony\Component\Console\Command\Command;
11
use Symfony\Component\Console\Input\InputOption;
12
use Symfony\Component\Console\Input\InputArgument;
13
use Symfony\Component\Console\Input\InputInterface;
14
use Symfony\Component\Console\Output\OutputInterface;
15
use Symfony\Component\Filesystem\Exception\IOExceptionInterface;
16
17
class NewCommand extends Command
18
{
19
    /**
20
     * Configure the command options.
21
     *
22
     * @return void
23
     */
24
    protected function configure()
25
    {
26
        $this
27
            ->setName('new')
28
            ->setDescription('Create a new Cortex application')
29
            ->addArgument('name', InputArgument::OPTIONAL)
30
            ->addOption('dev', null, InputOption::VALUE_NONE, 'Installs the latest "development" release')
31
            ->addOption('force', 'f', InputOption::VALUE_NONE, 'Forces install even if the directory already exists');
32
    }
33
34
    /**
35
     * Execute the command.
36
     *
37
     * @param  \Symfony\Component\Console\Input\InputInterface  $input
38
     * @param  \Symfony\Component\Console\Output\OutputInterface  $output
39
     * @return void
40
     */
41
    protected function execute(InputInterface $input, OutputInterface $output)
42
    {
43
        if (! class_exists('ZipArchive')) {
44
            throw new RuntimeException('The Zip PHP extension is not installed. Please install it and try again.');
45
        }
46
47
        $directory = ($input->getArgument('name')) ? getcwd().'/'.$input->getArgument('name') : getcwd();
48
49
        if (! $input->getOption('force')) {
50
            $this->verifyApplicationDoesntExist($directory);
51
        }
52
53
        $output->writeln('<info>Crafting application...</info>');
54
55
        $version = $this->getVersion($input);
56
57
        $this->download($zipFile = $this->makeFilename(), $version)
58
             ->extract($zipFile, $directory)
59
             ->prepareWritableDirectories($directory, $output)
60
             ->cleanUp($zipFile);
61
62
        $composer = $this->findComposer();
63
64
        $commands = [
65
            $composer.' install --no-scripts',
66
            $composer.' run-script post-root-package-install',
67
            $composer.' run-script post-create-project-cmd',
68
            $composer.' run-script post-autoload-dump',
69
        ];
70
71
        if ($input->getOption('no-ansi')) {
72
            $commands = array_map(function ($value) {
73
                return $value.' --no-ansi';
74
            }, $commands);
75
        }
76
77
        if ($input->getOption('quiet')) {
78
            $commands = array_map(function ($value) {
79
                return $value.' --quiet';
80
            }, $commands);
81
        }
82
83
        $process = new Process(implode(' && ', $commands), $directory, null, null, null);
0 ignored issues
show
Documentation introduced by
implode(' && ', $commands) is of type string, but the function expects a array.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
84
85
        if ('\\' !== DIRECTORY_SEPARATOR && file_exists('/dev/tty') && is_readable('/dev/tty')) {
86
            $process->setTty(true);
87
        }
88
89
        $process->run(function ($type, $line) use ($output) {
90
            $output->write($line);
91
        });
92
93
        $output->writeln('<comment>Application ready! Build something amazing.</comment>');
94
    }
95
96
    /**
97
     * Verify that the application does not already exist.
98
     *
99
     * @param  string  $directory
100
     * @return void
101
     */
102
    protected function verifyApplicationDoesntExist($directory)
103
    {
104
        if ((is_dir($directory) || is_file($directory)) && $directory != getcwd()) {
105
            throw new RuntimeException('Application already exists!');
106
        }
107
    }
108
109
    /**
110
     * Generate a random temporary filename.
111
     *
112
     * @return string
113
     */
114
    protected function makeFilename()
115
    {
116
        return getcwd().'/cortex_'.md5(time().uniqid()).'.zip';
117
    }
118
119
    /**
120
     * Download the temporary Zip to the given file.
121
     *
122
     * @param  string  $zipFile
123
     * @param  string  $version
124
     * @return $this
125
     */
126
    protected function download($zipFile, $version = 'master')
127
    {
128
        switch ($version) {
129
            case 'develop':
130
                $filename = 'develop.zip';
131
                break;
132
            case 'master':
133
                $filename = 'master.zip';
134
                break;
135
        }
136
137
        $response = (new Client)->get('https://github.com/rinvex/cortex/archive/'.$filename);
0 ignored issues
show
Bug introduced by
The variable $filename does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
138
139
        file_put_contents($zipFile, $response->getBody());
140
141
        return $this;
142
    }
143
144
    /**
145
     * Extract the Zip file into the given directory.
146
     *
147
     * @param  string  $zipFile
148
     * @param  string  $directory
149
     * @return $this
150
     */
151
    protected function extract($zipFile, $directory)
152
    {
153
        $archive = new ZipArchive;
154
155
        $archive->open($zipFile);
156
157
        $archive->extractTo($directory);
158
159
        $archive->close();
160
161
        return $this;
162
    }
163
164
    /**
165
     * Clean-up the Zip file.
166
     *
167
     * @param  string  $zipFile
168
     * @return $this
169
     */
170
    protected function cleanUp($zipFile)
171
    {
172
        @chmod($zipFile, 0777);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
173
174
        @unlink($zipFile);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
175
176
        return $this;
177
    }
178
179
    /**
180
     * Make sure the storage and bootstrap cache directories are writable.
181
     *
182
     * @param  string  $appDirectory
183
     * @param  \Symfony\Component\Console\Output\OutputInterface  $output
184
     * @return $this
185
     */
186
    protected function prepareWritableDirectories($appDirectory, OutputInterface $output)
187
    {
188
        $filesystem = new Filesystem;
189
190
        try {
191
            $filesystem->chmod($appDirectory.DIRECTORY_SEPARATOR."bootstrap/cache", 0755, 0000, true);
0 ignored issues
show
Coding Style Comprehensibility introduced by
The string literal bootstrap/cache does not require double quotes, as per coding-style, please use single quotes.

PHP provides two ways to mark string literals. Either with single quotes 'literal' or with double quotes "literal". The difference between these is that string literals in double quotes may contain variables with are evaluated at run-time as well as escape sequences.

String literals in single quotes on the other hand are evaluated very literally and the only two characters that needs escaping in the literal are the single quote itself (\') and the backslash (\\). Every other character is displayed as is.

Double quoted string literals may contain other variables or more complex escape sequences.

<?php

$singleQuoted = 'Value';
$doubleQuoted = "\tSingle is $singleQuoted";

print $doubleQuoted;

will print an indented: Single is Value

If your string literal does not contain variables or escape sequences, it should be defined using single quotes to make that fact clear.

For more information on PHP string literals and available escape sequences see the PHP core documentation.

Loading history...
192
            $filesystem->chmod($appDirectory.DIRECTORY_SEPARATOR."storage", 0755, 0000, true);
0 ignored issues
show
Coding Style Comprehensibility introduced by
The string literal storage does not require double quotes, as per coding-style, please use single quotes.

PHP provides two ways to mark string literals. Either with single quotes 'literal' or with double quotes "literal". The difference between these is that string literals in double quotes may contain variables with are evaluated at run-time as well as escape sequences.

String literals in single quotes on the other hand are evaluated very literally and the only two characters that needs escaping in the literal are the single quote itself (\') and the backslash (\\). Every other character is displayed as is.

Double quoted string literals may contain other variables or more complex escape sequences.

<?php

$singleQuoted = 'Value';
$doubleQuoted = "\tSingle is $singleQuoted";

print $doubleQuoted;

will print an indented: Single is Value

If your string literal does not contain variables or escape sequences, it should be defined using single quotes to make that fact clear.

For more information on PHP string literals and available escape sequences see the PHP core documentation.

Loading history...
193
        } catch (IOExceptionInterface $e) {
194
            $output->writeln('<comment>You should verify that the "storage" and "bootstrap/cache" directories are writable.</comment>');
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 136 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
195
        }
196
197
        return $this;
198
    }
199
200
    /**
201
     * Get the version that should be downloaded.
202
     *
203
     * @param  \Symfony\Component\Console\Input\InputInterface  $input
204
     * @return string
205
     */
206
    protected function getVersion(InputInterface $input)
207
    {
208
        if ($input->getOption('dev')) {
209
            return 'develop';
210
        }
211
212
        return 'master';
213
    }
214
215
    /**
216
     * Get the composer command for the environment.
217
     *
218
     * @return string
219
     */
220
    protected function findComposer()
221
    {
222
        if (file_exists(getcwd().'/composer.phar')) {
223
            return '"'.PHP_BINARY.'" composer.phar';
224
        }
225
226
        return 'composer';
227
    }
228
}
229