Completed
Pull Request — master (#16)
by Greg
03:10
created

Application::getHelpArgValue()   C

Complexity

Conditions 9
Paths 12

Size

Total Lines 24
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

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