Completed
Push — master ( ba5969...442c68 )
by Greg
03:27
created

Application::buildConfigCommand()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 6
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 4
nc 1
nop 6
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
        if (empty($commandList)) {
24
            return 1;
25
        }
26
        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...
27
    }
28
29
    /**
30
     * Set up output redirection. Used by tests.
31
     */
32
    public function setOutputFile($outputFile)
33
    {
34
        $this->outputFile = $outputFile;
35
    }
36
37
    /**
38
     * Figure out everything we're going to do, but don't do any of it
39
     * yet, just return the command objects to run.
40
     */
41
    public function parseArgvAndGetCommandList($argv, $home)
42
    {
43
        $optionDefaultValues = $this->getDefaultOptionValues($home);
44
        $optionDefaultValues = $this->overlayEnvironmentValues($optionDefaultValues);
45
46
        list($argv, $options) = $this->parseOutOurOptions($argv, $optionDefaultValues);
47
        return $this->separateProjectAndGetCommandList($argv, $home, $options);
48
    }
49
50
    /**
51
     * Figure out everything we're going to do, but don't do any of it
52
     * yet, just return the command objects to run.
53
     */
54
    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...
55
    {
56
        list($command, $projects, $composerArgs) = $this->separateProjectsFromArgs($argv, $options);
57
        $commandList = $this->getCommandsToExec($command, $composerArgs, $projects, $options);
58
        return $commandList;
59
    }
60
61
    /**
62
     * Run all of the commands in a list.  Abort early if any fail.
63
     *
64
     * @param array $commandList An array of CommandToExec
65
     * @return integer
66
     */
67
    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...
68
    {
69
        foreach ($commandList as $command) {
70
            $exitCode = $command->run($this->outputFile);
71
            if ($exitCode) {
72
                return $exitCode;
73
            }
74
        }
75
        return 0;
76
    }
77
78
    /**
79
     * Return an array containing a list of commands to execute.  Depending on
80
     * the composition of the aguments and projects parameters, this list will
81
     * contain either a single command string to call through to composer (if
82
     * cgr is being used as a composer alias), or it will contain a list of
83
     * appropriate replacement 'composer global require' commands that install
84
     * each project in its own installation directory, while installing each
85
     * projects' binaries in the global Composer bin directory,
86
     * ~/.composer/vendor/bin.
87
     *
88
     * @param array $composerArgs
89
     * @param array $projects
90
     * @param array $options
91
     * @return CommandToExec
92
     */
93
    public function getCommandsToExec($command, $composerArgs, $projects, $options)
94
    {
95
        $execPath = $options['composer-path'];
96
        // If command was not 'global require', 'global update' or
97
        // 'global remove', then call through to the standard composer
98
        // with all of the original args.
99
        if (empty($command)) {
100
            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...
101
        }
102
        // Call requireCommand, updateCommand, or removeCommand, as appropriate.
103
        $methodName = "{$command}Command";
104
        if (method_exists($this, $methodName)) {
105
            return $this->$methodName($execPath, $composerArgs, $projects, $options);
106
        } else {
107
            // If there is no specific implementation for the requested command, then call 'generalCommand'.
108
            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...
109
        }
110
    }
111
112
    /**
113
     * Return our list of default option values, with paths relative to
114
     * the provided home directory.
115
     * @param string $home The user's home directory
116
     * @return array
117
     */
118
    public function getDefaultOptionValues($home)
119
    {
120
        return array(
121
            'composer' => false,
122
            'composer-path' => 'composer',
123
            'base-dir' => "$home/.composer/global",
124
            'bin-dir' => "$home/.composer/vendor/bin",
125
            'stability' => false,
126
        );
127
    }
128
129
    /**
130
     * Replace option default values with the corresponding
131
     * environment variable value, if it is set.
132
     */
133
    protected function overlayEnvironmentValues($defaults)
134
    {
135
        foreach ($defaults as $key => $value) {
136
            $envKey = 'CGR_' . strtoupper(strtr($key, '-', '_'));
137
            $envValue = getenv($envKey);
138
            if ($envValue) {
139
                $defaults[$key] = $envValue;
140
            }
141
        }
142
143
        return $defaults;
144
    }
145
146
    /**
147
     * We use our own special-purpose argv parser. The options that apply
148
     * to this tool are identified by a simple associative array, where
149
     * the key is the option name, and the value is its default value.
150
     * The result of this function is an array of two items containing:
151
     *  - An array of the items in $argv not used to set an option value
152
     *  - An array of options containing the user-specified or default values
153
     *
154
     * @param array $argv The global $argv passed in by php
155
     * @param array $optionDefaultValues An associative array
156
     * @return array
157
     */
158
    public function parseOutOurOptions($argv, $optionDefaultValues)
159
    {
160
        $argv0 = array_shift($argv);
161
        $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...
162
        $passAlongArgvItems = array();
163
        $options = array();
164
        while (!empty($argv)) {
165
            $arg = array_shift($argv);
166
            if ((substr($arg, 0, 2) == '--') && array_key_exists(substr($arg, 2), $optionDefaultValues)) {
167
                $options[substr($arg, 2)] = array_shift($argv);
168
            } else {
169
                $passAlongArgvItems[] = $arg;
170
            }
171
        }
172
        return array($passAlongArgvItems, $options + $optionDefaultValues);
173
    }
174
175
    /**
176
     * After our options are removed by parseOutOurOptions, those items remaining
177
     * in $argv will be separated into a list of projects and versions, and
178
     * anything else that is not a project:version. Returns an array of two
179
     * items containing:
180
     *  - An associative array, where the key is the project name and the value
181
     *    is the version (or an empty string, if no version was specified)
182
     *  - The remaining $argv items not used to build the projects array.
183
     *
184
     * @param array $argv The $argv array from parseOutOurOptions()
185
     * @return array
186
     */
187
    public function separateProjectsFromArgs($argv, $options)
188
    {
189
        $cgrCommands = array('require', 'update', 'remove');
190
        $command = 'require';
191
        $composerArgs = array();
192
        $projects = array();
193
        $globalMode = !$options['composer'];
194
        foreach ($argv as $arg) {
195
            if ($arg[0] == '-') {
196
                // Any flags (first character is '-') will just be passed
197
                // through to to composer. Flags interpreted by cgr have
198
                // already been removed from $argv.
199
                $composerArgs[] = $arg;
200
            } elseif (strpos($arg, '/') !== false) {
201
                // Arguments containing a '/' name projects.  We will split
202
                // the project from its version, allowing the separator
203
                // character to be either a '=' or a ':', and then store the
204
                // result in the $projects array.
205
                $projectAndVersion = explode(':', strtr($arg, '=', ':'), 2) + array('', '');
206
                list($project, $version) = $projectAndVersion;
207
                $projects[$project] = $version;
208
            } elseif ($this->isComposerVersion($arg)) {
209
                // If an argument is a composer version, then we will alter
210
                // the last project we saw, attaching this version to it.
211
                // This allows us to handle 'a/b:1.0' and 'a/b 1.0' equivalently.
212
                $keys = array_keys($projects);
213
                $lastProject = array_pop($keys);
214
                unset($projects[$lastProject]);
215
                $projects[$lastProject] = $arg;
216
            } elseif ($arg == 'global') {
217
                // Make note if we see the 'global' command.
218
                $globalMode = true;
219
            } else {
220
                // If we see any command other than 'global [require|update|remove]',
221
                // then we will pass *all* of the arguments through to
222
                // composer unchanged. We return an empty projects array
223
                // to indicate that this should be a pass-through call
224
                // to composer, rather than one or more calls to
225
                // 'composer require' to install global projects.
226
                if ((!$globalMode) || (!in_array($arg, $cgrCommands))) {
227
                    return array('', array(), $argv);
228
                }
229
                // Remember which command we saw
230
                $command = $arg;
231
            }
232
        }
233
        return array($command, $projects, $composerArgs);
234
    }
235
236
    /**
237
     * Provide a safer version of `composer global require`.  Each project
238
     * listed in $projects will be installed into its own project directory.
239
     * The binaries from each project will still be placed in the global
240
     * composer bin directory.
241
     *
242
     * @param string $execPath The path to composer
243
     * @param array $composerArgs Anything from the global $argv to be passed
244
     *   on to Composer
245
     * @param array $projects A list of projects to install, with the key
246
     *   specifying the project name, and the value specifying its version.
247
     * @param array $options User options from the command line; see
248
     *   $optionDefaultValues in the main() function.
249
     * @return array
250
     */
251
    public function requireCommand($execPath, $composerArgs, $projects, $options)
252
    {
253
        $stabilityCommands = array();
254
        if ($options['stability']) {
255
            $stabilityCommands = $this->configureProjectStability($execPath, $composerArgs, $projects, $options);
256
        }
257
        $requireCommands = $this->generalCommand('require', $execPath, $composerArgs, $projects, $options);
258
        return array_merge($stabilityCommands, $requireCommands);
259
    }
260
261
    /**
262
     * General command handler.
263
     *
264
     * @param string $composerCommand The composer command to run e.g. require
265
     * @param string $execPath The path to composer
266
     * @param array $composerArgs Anything from the global $argv to be passed
267
     *   on to Composer
268
     * @param array $projects A list of projects to install, with the key
269
     *   specifying the project name, and the value specifying its version.
270
     * @param array $options User options from the command line; see
271
     *   $optionDefaultValues in the main() function.
272
     * @return array
273
     */
274
    public function generalCommand($composerCommand, $execPath, $composerArgs, $projects, $options)
275
    {
276
        $globalBaseDir = $options['base-dir'];
277
        $binDir = $options['bin-dir'];
278
        $env = array("COMPOSER_BIN_DIR" => $binDir);
279
        $result = array();
280
        foreach ($projects as $project => $version) {
281
            $installLocation = "$globalBaseDir/$project";
282
            $projectWithVersion = $this->projectWithVersion($project, $version);
283
            $commandToExec = $this->buildGlobalCommand($composerCommand, $execPath, $composerArgs, $projectWithVersion, $env, $installLocation);
284
            $result[] = $commandToExec;
285
        }
286
        return $result;
287
    }
288
289
    /**
290
     * If --stability VALUE is provided, then run a `composer config minimum-stability VALUE`
291
     * command to configure composer.json appropriately.
292
     *
293
     * @param string $execPath The path to composer
294
     * @param array $composerArgs Anything from the global $argv to be passed
295
     *   on to Composer
296
     * @param array $projects A list of projects to install, with the key
297
     *   specifying the project name, and the value specifying its version.
298
     * @param array $options User options from the command line; see
299
     *   $optionDefaultValues in the main() function.
300
     * @return array
301
     */
302
    public function configureProjectStability($execPath, $composerArgs, $projects, $options)
303
    {
304
        $globalBaseDir = $options['base-dir'];
305
        $stability = $options['stability'];
306
        $result = array();
307
        $env = array();
308
309
        foreach ($projects as $project => $version) {
310
            $installLocation = "$globalBaseDir/$project";
311
            FileSystemUtils::mkdirParents($installLocation);
312
            if (!file_exists("$installLocation/composer.json")) {
313
                file_put_contents("$installLocation/composer.json", '{}');
314
            }
315
            $result[] = $this->buildConfigCommand($execPath, $composerArgs, 'minimum-stability', $stability, $env, $installLocation);
316
        }
317
318
        return $result;
319
    }
320
321
    /**
322
     * Run `composer global update`. Not only do we want to update the
323
     * "global" Composer project, we also want to update all of the
324
     * "isolated" projects installed via cgr in ~/.composer/global.
325
     *
326
     * @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...
327
     * @param array $composerArgs Anything from the global $argv to be passed
328
     *   on to Composer
329
     * @param array $projects A list of projects to update.
330
     * @param array $options User options from the command line; see
331
     *   $optionDefaultValues in the main() function.
332
     * @return array
333
     */
334
    public function updateCommand($execPath, $composerArgs, $projects, $options)
335
    {
336
        // If 'projects' list is empty, make a list of everything currently installed
337
        if (empty($projects)) {
338
            $projects = FileSystemUtils::allInstalledProjectsInBaseDir($options['base-dir']);
339
            $projects = $this->flipProjectsArray($projects);
340
        }
341
        return $this->generalCommand('update', $execPath, $composerArgs, $projects, $options);
342
    }
343
344
    /**
345
     * Convert from an array of projects to an array where the key is the
346
     * project name, and the value (version) is an empty string.
347
     *
348
     * @param string[] $projects
349
     * @return array
350
     */
351
    public function flipProjectsArray($projects)
352
    {
353
        return array_map(function () {
354
            return '';
355
        }, array_flip($projects));
356
    }
357
358
    /**
359
     * Return $project:$version, or just $project if there is no $version.
360
     *
361
     * @param string $project The project to install
362
     * @param string $version The version desired
363
     * @return string
364
     */
365
    public function projectWithVersion($project, $version)
366
    {
367
        if (empty($version)) {
368
            return $project;
369
        }
370
        return "$project:$version";
371
    }
372
373
    /**
374
     * Generate command string to call `composer COMMAND` to install one project.
375
     *
376
     * @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...
377
     * @param array $composerArgs The arguments to pass to composer
378
     * @param string $projectWithVersion The project:version to install
379
     * @param array $env Environment to set prior to exec
380
     * @param string $installLocation Location to install the project
381
     * @return CommandToExec
382
     */
383
    public function buildGlobalCommand($composerCommand, $execPath, $composerArgs, $projectWithVersion, $env, $installLocation)
384
    {
385
        $projectSpecificArgs = array("--working-dir=$installLocation", $composerCommand, $projectWithVersion);
386
        $arguments = array_merge($composerArgs, $projectSpecificArgs);
387
        return new CommandToExec($execPath, $arguments, $env, $installLocation);
388
    }
389
390
    /**
391
     * Generate command string to call `composer config KEY VALUE` to install one project.
392
     *
393
     * @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...
394
     * @param array $composerArgs The arguments to pass to composer
395
     * @param string $key The config item to set
396
     * @param string $value The value to set the config item to
397
     * @param array $env Environment to set prior to exec
398
     * @param string $installLocation Location to install the project
399
     * @return CommandToExec
400
     */
401
    public function buildConfigCommand($execPath, $composerArgs, $key, $value, $env, $installLocation)
402
    {
403
        $projectSpecificArgs = array("--working-dir=$installLocation", 'config', $key, $value);
404
        $arguments = array_merge($composerArgs, $projectSpecificArgs);
405
        return new CommandToExec($execPath, $arguments, $env, $installLocation);
406
    }
407
408
    /**
409
     * Identify an argument that could be a Composer version string.
410
     *
411
     * @param string $arg The argument to test
412
     * @return boolean
413
     */
414
    public function isComposerVersion($arg)
415
    {
416
        $specialVersionChars = array('^', '~', '<', '>');
417
        return is_numeric($arg[0]) || in_array($arg[0], $specialVersionChars);
418
    }
419
}
420