Completed
Pull Request — master (#3)
by Greg
02:49
created

Application::getCommandsToExec()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 20
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 20
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 9
nc 3
nop 4
1
<?php
2
3
namespace Consolidation\Cgr;
4
5
class Application
6
{
7
    protected $outputFile = '';
8
9
    /**
10
     * Run the cgr tool, a safer alternative to `composer global require`.
11
     *
12
     * @param array $argv The global $argv array passed in by PHP
13
     * @param string $home The path to the user's home directory
14
     * @return integer
15
     */
16
    public function run($argv, $home)
17
    {
18
        $optionDefaultValues = $this->getDefaultOptionValues($home);
19
        $optionDefaultValues = $this->overlayEnvironmentValues($optionDefaultValues);
20
21
        list($argv, $options) = $this->parseOutOurOptions($argv, $optionDefaultValues);
22
        $commandList = $this->separateProjectAndGetCommandList($argv, $home, $options);
23
        return $this->runCommandList($commandList, $options);
0 ignored issues
show
Documentation introduced by
$commandList is of type object<Consolidation\Cgr\CommandToExec>, 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...
24
    }
25
26
    /**
27
     * Set up output redirection. Used by tests.
28
     */
29
    public function setOutputFile($outputFile)
30
    {
31
        $this->outputFile = $outputFile;
32
    }
33
34
    /**
35
     * Figure out everything we're going to do, but don't do any of it
36
     * yet, just return the command objects to run.
37
     */
38
    public function parseArgvAndGetCommandList($argv, $home)
39
    {
40
        $optionDefaultValues = $this->getDefaultOptionValues($home);
41
        $optionDefaultValues = $this->overlayEnvironmentValues($optionDefaultValues);
42
43
        list($argv, $options) = $this->parseOutOurOptions($argv, $optionDefaultValues);
44
        return $this->separateProjectAndGetCommandList($argv, $home, $options);
45
    }
46
47
    /**
48
     * Figure out everything we're going to do, but don't do any of it
49
     * yet, just return the command objects to run.
50
     */
51
    public function separateProjectAndGetCommandList($argv, $home, $options)
0 ignored issues
show
Unused Code introduced by
The parameter $home 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...
52
    {
53
        list($command, $projects, $composerArgs) = $this->separateProjectsFromArgs($argv, $options);
54
        $commandList = $this->getCommandsToExec($command, $composerArgs, $projects, $options);
55
        return $commandList;
56
    }
57
58
    /**
59
     * Run all of the commands in a list.  Abort early if any fail.
60
     *
61
     * @param array $commandList An array of CommandToExec
62
     * @return integer
63
     */
64
    public function runCommandList($commandList, $options)
0 ignored issues
show
Unused Code introduced by
The parameter $options 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...
65
    {
66
        foreach ($commandList as $command) {
67
            $exitCode = $command->run($this->outputFile);
68
            if ($exitCode) {
69
                return $exitCode;
70
            }
71
        }
72
        return 0;
73
    }
74
75
    /**
76
     * Return an array containing a list of commands to execute.  Depending on
77
     * the composition of the aguments and projects parameters, this list will
78
     * contain either a single command string to call through to composer (if
79
     * cgr is being used as a composer alias), or it will contain a list of
80
     * appropriate replacement 'composer global require' commands that install
81
     * each project in its own installation directory, while installing each
82
     * projects' binaries in the global Composer bin directory,
83
     * ~/.composer/vendor/bin.
84
     *
85
     * @param array $composerArgs
86
     * @param array $projects
87
     * @param array $options
88
     * @return CommandToExec
89
     */
90
    public function getCommandsToExec($command, $composerArgs, $projects, $options)
91
    {
92
        $execPath = $options['composer-path'];
93
        // If command was not 'global require', 'global update' or
94
        // 'global remove', then call through to the standard composer
95
        // with all of the original args.
96
        if (empty($command)) {
97
            return array(new CommandToExec($execPath, $composerArgs));
0 ignored issues
show
Bug Best Practice introduced by
The return type of return array(new \Consol...cPath, $composerArgs)); (Consolidation\Cgr\CommandToExec[]) is incompatible with the return type documented by Consolidation\Cgr\Application::getCommandsToExec of type Consolidation\Cgr\CommandToExec.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
98
        }
99
        // Call requireCommand, updateCommand, or removeCommand, as appropriate.
100
        $methodName = "{$command}Command";
101
        if (function_exists($methodName)) {
102
            return $this->$methodName($execPath, $composerArgs, $projects, $options);
103
        }
104
        // If there is no specific implementation for the requested command, then
105
        // call 'generalCommand'.
106
        else {
107
            return $this->generalCommand($command, $execPath, $composerArgs, $projects, $options);
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $this->generalCom..., $projects, $options); (array) is incompatible with the return type documented by Consolidation\Cgr\Application::getCommandsToExec of type Consolidation\Cgr\CommandToExec.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
108
        }
109
    }
110
111
    /**
112
     * Return our list of default option values, with paths relative to
113
     * the provided home directory.
114
     * @param string $home The user's home directory
115
     * @return array
116
     */
117
    public function getDefaultOptionValues($home)
118
    {
119
        return array(
120
            'composer' => false,
121
            'composer-path' => 'composer',
122
            'base-dir' => "$home/.composer/global",
123
            'bin-dir' => "$home/.composer/vendor/bin",
124
        );
125
    }
126
127
    /**
128
     * Replace option default values with the corresponding
129
     * environment variable value, if it is set.
130
     */
131
    protected function overlayEnvironmentValues($defaults)
132
    {
133
        foreach ($defaults as $key => $value) {
134
            $envKey = 'CGR_' . strtoupper(strtr($key, '-', '_'));
135
            $envValue = getenv($envKey);
136
            if ($envValue) {
137
                $defaults[$key] = $envValue;
138
            }
139
        }
140
141
        return $defaults;
142
    }
143
144
    /**
145
     * We use our own special-purpose argv parser. The options that apply
146
     * to this tool are identified by a simple associative array, where
147
     * the key is the option name, and the value is its default value.
148
     * The result of this function is an array of two items containing:
149
     *  - An array of the items in $argv not used to set an option value
150
     *  - An array of options containing the user-specified or default values
151
     *
152
     * @param array $argv The global $argv passed in by php
153
     * @param array $optionDefaultValues An associative array
154
     * @return array
155
     */
156
    public function parseOutOurOptions($argv, $optionDefaultValues)
157
    {
158
        $argv0 = array_shift($argv);
159
        $options['composer'] = (strpos($argv0, 'composer') !== false);
0 ignored issues
show
Coding Style Comprehensibility introduced by
$options was never initialized. Although not strictly required by PHP, it is generally a good practice to add $options = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
160
        $passAlongArgvItems = array();
161
        $options = array();
162
        while (!empty($argv)) {
163
            $arg = array_shift($argv);
164
            if ((substr($arg, 0, 2) == '--') && array_key_exists(substr($arg, 2), $optionDefaultValues)) {
165
                $options[substr($arg, 2)] = array_shift($argv);
166
            } else {
167
                $passAlongArgvItems[] = $arg;
168
            }
169
        }
170
        return array($passAlongArgvItems, $options + $optionDefaultValues);
171
    }
172
173
    /**
174
     * After our options are removed by parseOutOurOptions, those items remaining
175
     * in $argv will be separated into a list of projects and versions, and
176
     * anything else that is not a project:version. Returns an array of two
177
     * items containing:
178
     *  - An associative array, where the key is the project name and the value
179
     *    is the version (or an empty string, if no version was specified)
180
     *  - The remaining $argv items not used to build the projects array.
181
     *
182
     * @param array $argv The $argv array from parseOutOurOptions()
183
     * @return array
184
     */
185
    public function separateProjectsFromArgs($argv, $options)
186
    {
187
        $cgrCommands = array('require', 'update', 'remove');
188
        $command = 'require';
189
        $composerArgs = array();
190
        $projects = array();
191
        $globalMode = !$options['composer'];
192
        foreach ($argv as $arg) {
193
            if ($arg[0] == '-') {
194
                // Any flags (first character is '-') will just be passed
195
                // through to to composer. Flags interpreted by cgr have
196
                // already been removed from $argv.
197
                $composerArgs[] = $arg;
198
            } elseif (strpos($arg, '/') !== false) {
199
                // Arguments containing a '/' name projects.  We will split
200
                // the project from its version, allowing the separator
201
                // character to be either a '=' or a ':', and then store the
202
                // result in the $projects array.
203
                $projectAndVersion = explode(':', strtr($arg, '=', ':'), 2) + array('', '');
204
                list($project, $version) = $projectAndVersion;
205
                $projects[$project] = $version;
206
            } elseif ($this->isComposerVersion($arg)) {
207
                // If an argument is a composer version, then we will alter
208
                // the last project we saw, attaching this version to it.
209
                // This allows us to handle 'a/b:1.0' and 'a/b 1.0' equivalently.
210
                $keys = array_keys($projects);
211
                $lastProject = array_pop($keys);
212
                unset($projects[$lastProject]);
213
                $projects[$lastProject] = $arg;
214
            } elseif ($arg == 'global') {
215
                // Make note if we see the 'global' command.
216
                $globalMode = true;
217
            } else {
218
                // If we see any command other than 'global [require|update|remove]',
219
                // then we will pass *all* of the arguments through to
220
                // composer unchanged. We return an empty projects array
221
                // to indicate that this should be a pass-through call
222
                // to composer, rather than one or more calls to
223
                // 'composer require' to install global projects.
224
                if ((!$globalMode) || (!in_array($arg, $cgrCommands))) {
225
                    return array('', array(), $argv);
226
                }
227
                // Remember which command we saw
228
                $command = $arg;
229
            }
230
        }
231
        return array($command, $projects, $composerArgs);
232
    }
233
234
    /**
235
     * Provide a safer version of `composer global require`.  Each project
236
     * listed in $projects will be installed into its own project directory.
237
     * The binaries from each project will still be placed in the global
238
     * composer bin directory.
239
     *
240
     * @param string $composerCommand The composer command to run e.g. require
241
     * @param string $execPath The path to composer
242
     * @param array $composerArgs Anything from the global $argv to be passed
243
     *   on to Composer
244
     * @param array $projects A list of projects to install, with the key
245
     *   specifying the project name, and the value specifying its version.
246
     * @param array $options User options from the command line; see
247
     *   $optionDefaultValues in the main() function.
248
     * @return array
249
     */
250
    public function generalCommand($composerCommand, $execPath, $composerArgs, $projects, $options)
251
    {
252
        $globalBaseDir = $options['base-dir'];
253
        $binDir = $options['bin-dir'];
254
        $env = array("COMPOSER_BIN_DIR" => $binDir);
255
        $result = array();
256
        foreach ($projects as $project => $version) {
257
            $installLocation = "$globalBaseDir/$project";
258
            $projectWithVersion = $this->projectWithVersion($project, $version);
259
            $commandToExec = $this->buildGlobalCommand($composerCommand, $execPath, $composerArgs, $projectWithVersion, $env, $installLocation);
260
            $result[] = $commandToExec;
261
        }
262
        return $result;
263
    }
264
265
    /**
266
     * Run `composer global update`. Not only do we want to update the
267
     * "global" Composer project, we also want to update all of the
268
     * "isolated" projects installed via cgr in ~/.composer/global.
269
     *
270
     * @param string $command The path to composer
0 ignored issues
show
Bug introduced by
There is no parameter named $command. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
271
     * @param array $composerArgs Anything from the global $argv to be passed
272
     *   on to Composer
273
     * @param array $projects A list of projects to update.
274
     * @param array $options User options from the command line; see
275
     *   $optionDefaultValues in the main() function.
276
     * @return array
277
     */
278
    public function updateCommand($execPath, $composerArgs, $projects, $options)
279
    {
280
        // TODO: if projects are empty, make a list of everything currently installed
281
        return $this->generalCommand('update', $execPath, $composerArgs, $projects, $options);
282
    }
283
284
    /**
285
     * Return $project:$version, or just $project if there is no $version.
286
     *
287
     * @param string $project The project to install
288
     * @param string $version The version desired
289
     * @return string
290
     */
291
    public function projectWithVersion($project, $version)
292
    {
293
        if (empty($version)) {
294
            return $project;
295
        }
296
        return "$project:$version";
297
    }
298
299
    /**
300
     * Generate command string to call `composer require` to install one project.
301
     *
302
     * @param string $command The path to composer
0 ignored issues
show
Documentation introduced by
There is no parameter named $command. Did you maybe mean $composerCommand?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function. It has, however, found a similar but not annotated parameter which might be a good fit.

Consider the following example. The parameter $ireland is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $ireland
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was changed, but the annotation was not.

Loading history...
303
     * @param array $composerArgs The arguments to pass to composer
304
     * @param string $projectWithVersion The project:version to install
305
     * @param array $env Environment to set prior to exec
306
     * @param string $installLocation Location to install the project
307
     * @return CommandToExec
308
     */
309
    public function buildGlobalCommand($composerCommand, $execPath, $composerArgs, $projectWithVersion, $env, $installLocation)
310
    {
311
        $projectSpecificArgs = array("--working-dir=$installLocation", $composerCommand, $projectWithVersion);
312
        $arguments = array_merge($composerArgs, $projectSpecificArgs);
313
        return new CommandToExec($execPath, $arguments, $env, $installLocation);
314
    }
315
316
    /**
317
     * Identify an argument that could be a Composer version string.
318
     *
319
     * @param string $arg The argument to test
320
     * @return boolean
321
     */
322
    public function isComposerVersion($arg)
323
    {
324
        $specialVersionChars = array('^', '~', '<', '>');
325
        return is_numeric($arg[0]) || in_array($arg[0], $specialVersionChars);
326
    }
327
}
328