Completed
Push — master ( 5fb0d1...d464b6 )
by Greg
10s
created

Application::getDefaultOptionValues()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 10
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 10
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 7
nc 1
nop 1
1
<?php
2
3
namespace Consolidation\Cgr;
4
5
/**
6
 * Note that this command is deliberately written using only php-native
7
 * libraries, and no external dependencies whatsoever, so that it may
8
 * be installed via `composer global require` without causing any conflicts
9
 * with any other project.
10
 *
11
 * This technique is NOT recommended for other tools. Use Symfony Console
12
 * directly, or, better yet, use Robo (http://robo.li) as a framework.
13
 * See: http://robo.li/framework/
14
 */
15
class Application
16
{
17
    protected $outputFile = '';
18
19
    /**
20
     * Run the cgr tool, a safer alternative to `composer global require`.
21
     *
22
     * @param array $argv The global $argv array passed in by PHP
23
     * @param string $home The path to the user's home directory
24
     * @return integer
25
     */
26
    public function run($argv, $home)
27
    {
28
        $optionDefaultValues = $this->getDefaultOptionValues($home);
29
        $optionDefaultValues = $this->overlayEnvironmentValues($optionDefaultValues);
30
31
        list($argv, $options) = $this->parseOutOurOptions($argv, $optionDefaultValues);
32
33
        if (reset($argv) == 'help') {
34
            $this->help($argv);
35
            return 0;
36
        }
37
38
        $commandList = $this->separateProjectAndGetCommandList($argv, $home, $options);
39
        if (empty($commandList)) {
40
            return 1;
41
        }
42
        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...
43
    }
44
45
    public function help($argv)
0 ignored issues
show
Unused Code introduced by
The parameter $argv 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...
46
    {
47
        // Future: support 'help <command>'?
48
        print <<<EOT
49
The 'cgr' tool is a "safer" alternative to 'composer global require'.
50
Installing projects with cgr helps avoid dependency conflicts between
51
different tools.  Use 'cgr' wherever 'composer global require' is recommended.
52
53
Examples:
54
55
Install a project:
56
------------------
57
$ cgr drush/drush
58
59
Display the info of a project:
60
-----------------------------
61
$ cgr info drush/drush
62
63
Display the info of all projects installed via 'cgr':
64
----------------------------------------------------
65
$ cgr info
66
67
Update a project:
68
-----------------
69
$ cgr update drush/drush
70
71
Update all projects installed via 'cgr':
72
----------------------------------------
73
$ cgr update
74
75
Remove a project:
76
-----------------
77
$ cgr remove drush/drush
78
79
For more information, see: https://github.com/consolidation/cgr
80
81
82
EOT;
83
    }
84
85
    /**
86
     * Set up output redirection. Used by tests.
87
     */
88
    public function setOutputFile($outputFile)
89
    {
90
        $this->outputFile = $outputFile;
91
    }
92
93
    /**
94
     * Figure out everything we're going to do, but don't do any of it
95
     * yet, just return the command objects to run.
96
     */
97
    public function parseArgvAndGetCommandList($argv, $home)
98
    {
99
        $optionDefaultValues = $this->getDefaultOptionValues($home);
100
        $optionDefaultValues = $this->overlayEnvironmentValues($optionDefaultValues);
101
102
        list($argv, $options) = $this->parseOutOurOptions($argv, $optionDefaultValues);
103
        return $this->separateProjectAndGetCommandList($argv, $home, $options);
104
    }
105
106
    /**
107
     * Figure out everything we're going to do, but don't do any of it
108
     * yet, just return the command objects to run.
109
     */
110
    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...
111
    {
112
        list($command, $projects, $composerArgs) = $this->separateProjectsFromArgs($argv, $options);
113
114
        // If command was unknown, then exit with an error message
115
        if (empty($command)) {
116
            print "Unknown command: " . implode(' ', $composerArgs) . "\n";
117
            exit(1);
0 ignored issues
show
Coding Style Compatibility introduced by
The method separateProjectAndGetCommandList() contains an exit expression.

An exit expression should only be used in rare cases. For example, if you write a short command line script.

In most cases however, using an exit expression makes the code untestable and often causes incompatibilities with other libraries. Thus, unless you are absolutely sure it is required here, we recommend to refactor your code to avoid its usage.

Loading history...
118
        }
119
120
        $commandList = $this->getCommandsToExec($command, $composerArgs, $projects, $options);
121
        return $commandList;
122
    }
123
124
    /**
125
     * Run all of the commands in a list.  Abort early if any fail.
126
     *
127
     * @param array $commandList An array of CommandToExec
128
     * @return integer
129
     */
130
    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...
131
    {
132
        foreach ($commandList as $command) {
133
            $exitCode = $command->run($this->outputFile);
134
            if ($exitCode) {
135
                return $exitCode;
136
            }
137
        }
138
        return 0;
139
    }
140
141
    /**
142
     * Return an array containing a list of commands to execute.  Depending on
143
     * the composition of the aguments and projects parameters, this list will
144
     * contain either a single command string to call through to composer (if
145
     * cgr is being used as a composer alias), or it will contain a list of
146
     * appropriate replacement 'composer global require' commands that install
147
     * each project in its own installation directory, while installing each
148
     * projects' binaries in the global Composer bin directory,
149
     * ~/.composer/vendor/bin.
150
     *
151
     * @param array $composerArgs
152
     * @param array $projects
153
     * @param array $options
154
     * @return CommandToExec
155
     */
156
    public function getCommandsToExec($command, $composerArgs, $projects, $options)
157
    {
158
        $execPath = $options['composer-path'];
159
160
        // Call requireCommand, updateCommand, or removeCommand, as appropriate.
161
        $methodName = "{$command}Command";
162
        if (method_exists($this, $methodName)) {
163
            return $this->$methodName($execPath, $composerArgs, $projects, $options);
164
        } else {
165
            // If there is no specific implementation for the requested command, then call 'generalCommand'.
166
            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...
167
        }
168
    }
169
170
    /**
171
     * Return our list of default option values, with paths relative to
172
     * the provided home directory.
173
     * @param string $home The user's home directory
174
     * @return array
175
     */
176
    public function getDefaultOptionValues($home)
177
    {
178
        return array(
179
            'composer' => false,
180
            'composer-path' => 'composer',
181
            'base-dir' => "$home/.composer/global",
182
            'bin-dir' => "$home/.composer/vendor/bin",
183
            'stability' => false,
184
        );
185
    }
186
187
    /**
188
     * Replace option default values with the corresponding
189
     * environment variable value, if it is set.
190
     */
191
    protected function overlayEnvironmentValues($defaults)
192
    {
193
        foreach ($defaults as $key => $value) {
194
            $envKey = 'CGR_' . strtoupper(strtr($key, '-', '_'));
195
            $envValue = getenv($envKey);
196
            if ($envValue) {
197
                $defaults[$key] = $envValue;
198
            }
199
        }
200
201
        return $defaults;
202
    }
203
204
    /**
205
     * We use our own special-purpose argv parser. The options that apply
206
     * to this tool are identified by a simple associative array, where
207
     * the key is the option name, and the value is its default value.
208
     * The result of this function is an array of two items containing:
209
     *  - An array of the items in $argv not used to set an option value
210
     *  - An array of options containing the user-specified or default values
211
     *
212
     * @param array $argv The global $argv passed in by php
213
     * @param array $optionDefaultValues An associative array
214
     * @return array
215
     */
216
    public function parseOutOurOptions($argv, $optionDefaultValues)
217
    {
218
        $argv0 = array_shift($argv);
219
        $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...
220
        $passAlongArgvItems = array();
221
        $options = array();
222
        while (!empty($argv)) {
223
            $arg = array_shift($argv);
224
            if ((substr($arg, 0, 2) == '--') && array_key_exists(substr($arg, 2), $optionDefaultValues)) {
225
                $options[substr($arg, 2)] = array_shift($argv);
226
            } else {
227
                $passAlongArgvItems[] = $arg;
228
            }
229
        }
230
        return array($passAlongArgvItems, $options + $optionDefaultValues);
231
    }
232
233
    /**
234
     * After our options are removed by parseOutOurOptions, those items remaining
235
     * in $argv will be separated into a list of projects and versions, and
236
     * anything else that is not a project:version. Returns an array of two
237
     * items containing:
238
     *  - An associative array, where the key is the project name and the value
239
     *    is the version (or an empty string, if no version was specified)
240
     *  - The remaining $argv items not used to build the projects array.
241
     *
242
     * @param array $argv The $argv array from parseOutOurOptions()
243
     * @return array
244
     */
245
    public function separateProjectsFromArgs($argv, $options)
246
    {
247
        $cgrCommands = array('info', 'require', 'update', 'remove');
248
        $command = 'require';
249
        $composerArgs = array();
250
        $projects = array();
251
        $globalMode = !$options['composer'];
252
        foreach ($argv as $arg) {
253
            if ($arg[0] == '-') {
254
                // Any flags (first character is '-') will just be passed
255
                // through to to composer. Flags interpreted by cgr have
256
                // already been removed from $argv.
257
                $composerArgs[] = $arg;
258
            } elseif (strpos($arg, '/') !== false) {
259
                // Arguments containing a '/' name projects.  We will split
260
                // the project from its version, allowing the separator
261
                // character to be either a '=' or a ':', and then store the
262
                // result in the $projects array.
263
                $projectAndVersion = explode(':', strtr($arg, '=', ':'), 2) + array('', '');
264
                list($project, $version) = $projectAndVersion;
265
                $projects[$project] = $version;
266
            } elseif ($this->isComposerVersion($arg)) {
267
                // If an argument is a composer version, then we will alter
268
                // the last project we saw, attaching this version to it.
269
                // This allows us to handle 'a/b:1.0' and 'a/b 1.0' equivalently.
270
                $keys = array_keys($projects);
271
                $lastProject = array_pop($keys);
272
                unset($projects[$lastProject]);
273
                $projects[$lastProject] = $arg;
274
            } elseif ($arg == 'global') {
275
                // Make note if we see the 'global' command.
276
                $globalMode = true;
277
            } else {
278
                // If we see any command other than 'global [require|update|remove]',
279
                // then we will pass *all* of the arguments through to
280
                // composer unchanged. We return an empty projects array
281
                // to indicate that this should be a pass-through call
282
                // to composer, rather than one or more calls to
283
                // 'composer require' to install global projects.
284
                if ((!$globalMode) || (!in_array($arg, $cgrCommands))) {
285
                    return array('', array(), $argv);
286
                }
287
                // Remember which command we saw
288
                $command = $arg;
289
            }
290
        }
291
        return array($command, $projects, $composerArgs);
292
    }
293
294
    /**
295
     * Provide a safer version of `composer global require`.  Each project
296
     * listed in $projects will be installed into its own project directory.
297
     * The binaries from each project will still be placed in the global
298
     * composer bin directory.
299
     *
300
     * @param string $execPath The path to composer
301
     * @param array $composerArgs Anything from the global $argv to be passed
302
     *   on to Composer
303
     * @param array $projects A list of projects to install, with the key
304
     *   specifying the project name, and the value specifying its version.
305
     * @param array $options User options from the command line; see
306
     *   $optionDefaultValues in the main() function.
307
     * @return array
308
     */
309
    public function requireCommand($execPath, $composerArgs, $projects, $options)
310
    {
311
        $stabilityCommands = array();
312
        if ($options['stability']) {
313
            $stabilityCommands = $this->configureProjectStability($execPath, $composerArgs, $projects, $options);
314
        }
315
        $requireCommands = $this->generalCommand('require', $execPath, $composerArgs, $projects, $options);
316
        return array_merge($stabilityCommands, $requireCommands);
317
    }
318
319
    /**
320
     * General command handler.
321
     *
322
     * @param string $composerCommand The composer command to run e.g. require
323
     * @param string $execPath The path to composer
324
     * @param array $composerArgs Anything from the global $argv to be passed
325
     *   on to Composer
326
     * @param array $projects A list of projects to install, with the key
327
     *   specifying the project name, and the value specifying its version.
328
     * @param array $options User options from the command line; see
329
     *   $optionDefaultValues in the main() function.
330
     * @return array
331
     */
332
    public function generalCommand($composerCommand, $execPath, $composerArgs, $projects, $options)
333
    {
334
        $globalBaseDir = $options['base-dir'];
335
        $binDir = $options['bin-dir'];
336
        $env = array("COMPOSER_BIN_DIR" => $binDir);
337
        $result = array();
338
        foreach ($projects as $project => $version) {
339
            $installLocation = "$globalBaseDir/$project";
340
            $projectWithVersion = $this->projectWithVersion($project, $version);
341
            $commandToExec = $this->buildGlobalCommand($composerCommand, $execPath, $composerArgs, $projectWithVersion, $env, $installLocation);
342
            $result[] = $commandToExec;
343
        }
344
        return $result;
345
    }
346
347
    /**
348
     * If --stability VALUE is provided, then run a `composer config minimum-stability VALUE`
349
     * command to configure composer.json appropriately.
350
     *
351
     * @param string $execPath The path to composer
352
     * @param array $composerArgs Anything from the global $argv to be passed
353
     *   on to Composer
354
     * @param array $projects A list of projects to install, with the key
355
     *   specifying the project name, and the value specifying its version.
356
     * @param array $options User options from the command line; see
357
     *   $optionDefaultValues in the main() function.
358
     * @return array
359
     */
360
    public function configureProjectStability($execPath, $composerArgs, $projects, $options)
361
    {
362
        $globalBaseDir = $options['base-dir'];
363
        $stability = $options['stability'];
364
        $result = array();
365
        $env = array();
366
367
        foreach ($projects as $project => $version) {
368
            $installLocation = "$globalBaseDir/$project";
369
            FileSystemUtils::mkdirParents($installLocation);
370
            if (!file_exists("$installLocation/composer.json")) {
371
                file_put_contents("$installLocation/composer.json", '{}');
372
            }
373
            $result[] = $this->buildConfigCommand($execPath, $composerArgs, 'minimum-stability', $stability, $env, $installLocation);
374
        }
375
376
        return $result;
377
    }
378
379
    /**
380
     * Run `composer info`. Not only do we want to display the information of
381
     * the "global" Composer project, we also want to get the infomation of
382
     * all the "isolated" projects installed via cgr in ~/.composer/global.
383
     *
384
     * @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...
385
     * @param array $composerArgs Anything from the global $argv to be passed
386
     *   on to Composer
387
     * @param array $projects A list of projects to update.
388
     * @param array $options User options from the command line; see
389
     *   $optionDefaultValues in the main() function.
390
     * @return array
391
     */
392 View Code Duplication
    public function infoCommand($execPath, $composerArgs, $projects, $options)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
393
    {
394
        // If 'projects' list is empty, make a list of everything currently installed
395
        if (empty($projects)) {
396
            $projects = FileSystemUtils::allInstalledProjectsInBaseDir($options['base-dir']);
397
            $projects = $this->flipProjectsArray($projects);
398
        }
399
        return $this->generalCommand('info', $execPath, $composerArgs, $projects, $options);
400
    }
401
402
403
    /**
404
     * Run `composer global update`. Not only do we want to update the
405
     * "global" Composer project, we also want to update all of the
406
     * "isolated" projects installed via cgr in ~/.composer/global.
407
     *
408
     * @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...
409
     * @param array $composerArgs Anything from the global $argv to be passed
410
     *   on to Composer
411
     * @param array $projects A list of projects to update.
412
     * @param array $options User options from the command line; see
413
     *   $optionDefaultValues in the main() function.
414
     * @return array
415
     */
416 View Code Duplication
    public function updateCommand($execPath, $composerArgs, $projects, $options)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
417
    {
418
        // If 'projects' list is empty, make a list of everything currently installed
419
        if (empty($projects)) {
420
            $projects = FileSystemUtils::allInstalledProjectsInBaseDir($options['base-dir']);
421
            $projects = $this->flipProjectsArray($projects);
422
        }
423
        return $this->generalCommand('update', $execPath, $composerArgs, $projects, $options);
424
    }
425
426
    /**
427
     * Convert from an array of projects to an array where the key is the
428
     * project name, and the value (version) is an empty string.
429
     *
430
     * @param string[] $projects
431
     * @return array
432
     */
433
    public function flipProjectsArray($projects)
434
    {
435
        return array_map(function () {
436
            return '';
437
        }, array_flip($projects));
438
    }
439
440
    /**
441
     * Return $project:$version, or just $project if there is no $version.
442
     *
443
     * @param string $project The project to install
444
     * @param string $version The version desired
445
     * @return string
446
     */
447
    public function projectWithVersion($project, $version)
448
    {
449
        if (empty($version)) {
450
            return $project;
451
        }
452
        return "$project:$version";
453
    }
454
455
    /**
456
     * Generate command string to call `composer COMMAND` to install one project.
457
     *
458
     * @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...
459
     * @param array $composerArgs The arguments to pass to composer
460
     * @param string $projectWithVersion The project:version to install
461
     * @param array $env Environment to set prior to exec
462
     * @param string $installLocation Location to install the project
463
     * @return CommandToExec
464
     */
465
    public function buildGlobalCommand($composerCommand, $execPath, $composerArgs, $projectWithVersion, $env, $installLocation)
466
    {
467
        $projectSpecificArgs = array("--working-dir=$installLocation", $composerCommand, $projectWithVersion);
468
        $arguments = array_merge($composerArgs, $projectSpecificArgs);
469
        return new CommandToExec($execPath, $arguments, $env, $installLocation);
470
    }
471
472
    /**
473
     * Generate command string to call `composer config KEY VALUE` to install one project.
474
     *
475
     * @param string $execPath The path to composer
476
     * @param array $composerArgs The arguments to pass to composer
477
     * @param string $key The config item to set
478
     * @param string $value The value to set the config item to
479
     * @param array $env Environment to set prior to exec
480
     * @param string $installLocation Location to install the project
481
     * @return CommandToExec
482
     */
483
    public function buildConfigCommand($execPath, $composerArgs, $key, $value, $env, $installLocation)
484
    {
485
        $projectSpecificArgs = array("--working-dir=$installLocation", 'config', $key, $value);
486
        $arguments = array_merge($composerArgs, $projectSpecificArgs);
487
        return new CommandToExec($execPath, $arguments, $env, $installLocation);
488
    }
489
490
    /**
491
     * Identify an argument that could be a Composer version string.
492
     *
493
     * @param string $arg The argument to test
494
     * @return boolean
495
     */
496
    public function isComposerVersion($arg)
497
    {
498
        // Allow for 'dev-master', et. al.
499
        if (substr($arg, 0, 4) == 'dev-') {
500
            return true;
501
        }
502
        $specialVersionChars = array('^', '~', '<', '>');
503
        return is_numeric($arg[0]) || in_array($arg[0], $specialVersionChars);
504
    }
505
}
506