Completed
Pull Request — master (#3)
by Greg
04:07
created

Application::separateProjectAndGetCommandList()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
c 2
b 0
f 0
dl 0
loc 6
rs 9.4285
cc 1
eloc 4
nc 1
nop 3
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
        return $this->$methodName($execPath, $composerArgs, $projects, $options);
102
    }
103
104
    /**
105
     * Return our list of default option values, with paths relative to
106
     * the provided home directory.
107
     * @param string $home The user's home directory
108
     * @return array
109
     */
110
    public function getDefaultOptionValues($home)
111
    {
112
        return array(
113
            'composer' => false,
114
            'composer-path' => 'composer',
115
            'base-dir' => "$home/.composer/global",
116
            'bin-dir' => "$home/.composer/vendor/bin",
117
        );
118
    }
119
120
    /**
121
     * Replace option default values with the corresponding
122
     * environment variable value, if it is set.
123
     */
124
    protected function overlayEnvironmentValues($defaults)
125
    {
126
        foreach ($defaults as $key => $value) {
127
            $envKey = 'CGR_' . strtoupper(strtr($key, '-', '_'));
128
            $envValue = getenv($envKey);
129
            if ($envValue) {
130
                $defaults[$key] = $envValue;
131
            }
132
        }
133
134
        return $defaults;
135
    }
136
137
    /**
138
     * We use our own special-purpose argv parser. The options that apply
139
     * to this tool are identified by a simple associative array, where
140
     * the key is the option name, and the value is its default value.
141
     * The result of this function is an array of two items containing:
142
     *  - An array of the items in $argv not used to set an option value
143
     *  - An array of options containing the user-specified or default values
144
     *
145
     * @param array $argv The global $argv passed in by php
146
     * @param array $optionDefaultValues An associative array
147
     * @return array
148
     */
149
    public function parseOutOurOptions($argv, $optionDefaultValues)
150
    {
151
        $argv0 = array_shift($argv);
152
        $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...
153
        $passAlongArgvItems = array();
154
        $options = array();
155
        while (!empty($argv)) {
156
            $arg = array_shift($argv);
157
            if ((substr($arg, 0, 2) == '--') && array_key_exists(substr($arg, 2), $optionDefaultValues)) {
158
                $options[substr($arg, 2)] = array_shift($argv);
159
            } else {
160
                $passAlongArgvItems[] = $arg;
161
            }
162
        }
163
        return array($passAlongArgvItems, $options + $optionDefaultValues);
164
    }
165
166
    /**
167
     * After our options are removed by parseOutOurOptions, those items remaining
168
     * in $argv will be separated into a list of projects and versions, and
169
     * anything else that is not a project:version. Returns an array of two
170
     * items containing:
171
     *  - An associative array, where the key is the project name and the value
172
     *    is the version (or an empty string, if no version was specified)
173
     *  - The remaining $argv items not used to build the projects array.
174
     *
175
     * @param array $argv The $argv array from parseOutOurOptions()
176
     * @return array
177
     */
178
    public function separateProjectsFromArgs($argv, $options)
179
    {
180
        $cgrCommands = array('require', 'update', 'remove');
181
        $command = 'require';
182
        $composerArgs = array();
183
        $projects = array();
184
        $globalMode = !$options['composer'];
185
        foreach ($argv as $arg) {
186
            if ($arg[0] == '-') {
187
                // Any flags (first character is '-') will just be passed
188
                // through to to composer. Flags interpreted by cgr have
189
                // already been removed from $argv.
190
                $composerArgs[] = $arg;
191
            } elseif (strpos($arg, '/') !== false) {
192
                // Arguments containing a '/' name projects.  We will split
193
                // the project from its version, allowing the separator
194
                // character to be either a '=' or a ':', and then store the
195
                // result in the $projects array.
196
                $projectAndVersion = explode(':', strtr($arg, '=', ':'), 2) + array('', '');
197
                list($project, $version) = $projectAndVersion;
198
                $projects[$project] = $version;
199
            } elseif ($this->isComposerVersion($arg)) {
200
                // If an argument is a composer version, then we will alter
201
                // the last project we saw, attaching this version to it.
202
                // This allows us to handle 'a/b:1.0' and 'a/b 1.0' equivalently.
203
                $keys = array_keys($projects);
204
                $lastProject = array_pop($keys);
205
                unset($projects[$lastProject]);
206
                $projects[$lastProject] = $arg;
207
            } elseif ($arg == 'global') {
208
                // Make note if we see the 'global' command.
209
                $globalMode = true;
210
            } else {
211
                // If we see any command other than 'global [require|update|remove]',
212
                // then we will pass *all* of the arguments through to
213
                // composer unchanged. We return an empty projects array
214
                // to indicate that this should be a pass-through call
215
                // to composer, rather than one or more calls to
216
                // 'composer require' to install global projects.
217
                if ((!$globalMode) || (!in_array($arg, $cgrCommands))) {
218
                    return array('', array(), $argv);
219
                }
220
                // Remember which command we saw
221
                $command = $arg;
222
            }
223
        }
224
        return array($command, $projects, $composerArgs);
225
    }
226
227
    /**
228
     * Provide a safer version of `composer global require`.  Each project
229
     * listed in $projects will be installed into its own project directory.
230
     * The binaries from each project will still be placed in the global
231
     * composer bin directory.
232
     *
233
     * @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...
234
     * @param array $composerArgs Anything from the global $argv to be passed
235
     *   on to Composer
236
     * @param array $projects A list of projects to install, with the key
237
     *   specifying the project name, and the value specifying its version.
238
     * @param array $options User options from the command line; see
239
     *   $optionDefaultValues in the main() function.
240
     * @return array
241
     */
242
    public function requireCommand($execPath, $composerArgs, $projects, $options)
243
    {
244
        $globalBaseDir = $options['base-dir'];
245
        $binDir = $options['bin-dir'];
246
        $env = array("COMPOSER_BIN_DIR" => $binDir);
247
        $result = array();
248
        foreach ($projects as $project => $version) {
249
            $installLocation = "$globalBaseDir/$project";
250
            $projectWithVersion = $this->projectWithVersion($project, $version);
251
            $commandToExec = $this->buildGlobalRequireCommand($execPath, $composerArgs, $projectWithVersion, $env, $installLocation);
252
            $result[] = $commandToExec;
253
        }
254
        return $result;
255
    }
256
257
    /**
258
     * Run `composer global update`. Not only do we want to update the
259
     * "global" Composer project, we also want to update all of the
260
     * "isolated" projects installed via cgr in ~/.composer/global.
261
     *
262
     * @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...
263
     * @param array $composerArgs Anything from the global $argv to be passed
264
     *   on to Composer
265
     * @param array $projects A list of projects to update. Must be empty
266
     *   for now -- not supported yet (always updates all projects).
267
     * @param array $options User options from the command line; see
268
     *   $optionDefaultValues in the main() function.
269
     * @return array
270
     */
271
    public function updateCommand($execPath, $composerArgs, $projects, $options)
0 ignored issues
show
Unused Code introduced by
The parameter $execPath 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...
Unused Code introduced by
The parameter $composerArgs 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...
Unused Code introduced by
The parameter $projects 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...
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...
272
    {
273
        $result = array();
274
        return $result;
275
    }
276
277
    /**
278
     * Run `composer global remove`.  The project(s) specified may have been
279
     * installed via cgr, or may have been installed
280
     */
281
    public function removeCommand($execPath, $composerArgs, $projects, $options)
0 ignored issues
show
Unused Code introduced by
The parameter $execPath 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...
Unused Code introduced by
The parameter $composerArgs 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...
Unused Code introduced by
The parameter $projects 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...
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...
282
    {
283
        $result = array();
284
        return $result;
285
    }
286
287
    /**
288
     * Return $project:$version, or just $project if there is no $version.
289
     *
290
     * @param string $project The project to install
291
     * @param string $version The version desired
292
     * @return string
293
     */
294
    public function projectWithVersion($project, $version)
295
    {
296
        if (empty($version)) {
297
            return $project;
298
        }
299
        return "$project:$version";
300
    }
301
302
    /**
303
     * Generate command string to call `composer require` to install one project.
304
     *
305
     * @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...
306
     * @param array $composerArgs The arguments to pass to composer
307
     * @param string $projectWithVersion The project:version to install
308
     * @param array $env Environment to set prior to exec
309
     * @param string $installLocation Location to install the project
310
     * @return CommandToExec
311
     */
312
    public function buildGlobalRequireCommand($execPath, $composerArgs, $projectWithVersion, $env, $installLocation)
313
    {
314
        $projectSpecificArgs = array("--working-dir=$installLocation", 'require', $projectWithVersion);
315
        $arguments = array_merge($composerArgs, $projectSpecificArgs);
316
        return new CommandToExec($execPath, $arguments, $env, $installLocation);
317
    }
318
319
    /**
320
     * Identify an argument that could be a Composer version string.
321
     *
322
     * @param string $arg The argument to test
323
     * @return boolean
324
     */
325
    public function isComposerVersion($arg)
326
    {
327
        $specialVersionChars = array('^', '~', '<', '>');
328
        return is_numeric($arg[0]) || in_array($arg[0], $specialVersionChars);
329
    }
330
}
331