Completed
Pull Request — master (#671)
by Antonio
11:03
created

Runner::setClassLoader()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 5
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 3
nc 1
nop 1
1
<?php
2
namespace Robo;
3
4
use Composer\Autoload\ClassLoader;
5
use Symfony\Component\Console\Input\ArgvInput;
6
use Symfony\Component\Console\Input\StringInput;
7
use Robo\Contract\BuilderAwareInterface;
8
use Robo\Collection\CollectionBuilder;
9
use Robo\Common\IO;
10
use Robo\Exception\TaskExitException;
11
use League\Container\ContainerAwareInterface;
12
use League\Container\ContainerAwareTrait;
13
14
class Runner implements ContainerAwareInterface
15
{
16
    const ROBOCLASS = 'RoboFile';
17
    const ROBOFILE = 'RoboFile.php';
18
19
    use IO;
20
    use ContainerAwareTrait;
21
22
    /**
23
     * @var string
24
     */
25
    protected $roboClass;
26
27
    /**
28
     * @var string
29
     */
30
    protected $roboFile;
31
32
    /**
33
     * @var string working dir of Robo
34
     */
35
    protected $dir;
36
37
    /**
38
     * @var string[]
39
     */
40
    protected $errorConditions = [];
41
42
    /**
43
     * @var string GitHub Repo for SelfUpdate
44
     */
45
    protected $selfUpdateRepository = null;
46
47
    /**
48
     * @var \Composer\Autoload\ClassLoader
49
     */
50
    protected $classLoader = null;
51
52
    /**
53
     * @var string
54
     */
55
    protected $commandFileRelativeNamespace = 'Robo\Commands';
56
57
    /**
58
     * Class Constructor
59
     *
60
     * @param null|string $roboClass
61
     * @param null|string $roboFile
62
     */
63
    public function __construct($roboClass = null, $roboFile = null)
64
    {
65
        // set the const as class properties to allow overwriting in child classes
66
        $this->roboClass = $roboClass ? $roboClass : self::ROBOCLASS ;
67
        $this->roboFile  = $roboFile ? $roboFile : self::ROBOFILE;
68
        $this->dir = getcwd();
69
    }
70
71
    protected function errorCondtion($msg, $errorType)
72
    {
73
        $this->errorConditions[$msg] = $errorType;
74
    }
75
76
    /**
77
     * @param \Symfony\Component\Console\Output\OutputInterface $output
78
     *
79
     * @return bool
80
     */
81
    protected function loadRoboFile($output)
82
    {
83
        // If we have not been provided an output object, make a temporary one.
84
        if (!$output) {
85
            $output = new \Symfony\Component\Console\Output\ConsoleOutput();
0 ignored issues
show
Unused Code introduced by
$output is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
86
        }
87
88
        // If $this->roboClass is a single class that has not already
89
        // been loaded, then we will try to obtain it from $this->roboFile.
90
        // If $this->roboClass is an array, we presume all classes requested
91
        // are available via the autoloader.
92
        if (is_array($this->roboClass) || class_exists($this->roboClass)) {
93
            return true;
94
        }
95
        if (!file_exists($this->dir)) {
96
            $this->errorCondtion("Path `{$this->dir}` is invalid; please provide a valid absolute path to the Robofile to load.", 'red');
97
            return false;
98
        }
99
100
        $realDir = realpath($this->dir);
101
102
        $roboFilePath = $realDir . DIRECTORY_SEPARATOR . $this->roboFile;
103
        if (!file_exists($roboFilePath)) {
104
            $requestedRoboFilePath = $this->dir . DIRECTORY_SEPARATOR . $this->roboFile;
105
            $this->errorCondtion("Requested RoboFile `$requestedRoboFilePath` is invalid, please provide valid absolute path to load Robofile.", 'red');
106
            return false;
107
        }
108
        require_once $roboFilePath;
109
110
        if (!class_exists($this->roboClass)) {
111
            $this->errorCondtion("Class {$this->roboClass} was not loaded.", 'red');
112
            return false;
113
        }
114
        return true;
115
    }
116
117
    /**
118
     * @param array $argv
119
     * @param null|string $appName
120
     * @param null|string $appVersion
121
     * @param null|\Symfony\Component\Console\Output\OutputInterface $output
122
     *
123
     * @return int
124
     */
125
    public function execute($argv, $appName = null, $appVersion = null, $output = null)
126
    {
127
        $argv = $this->shebang($argv);
128
        $argv = $this->processRoboOptions($argv);
129
        $app = null;
130
        if ($appName && $appVersion) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $appName of type null|string is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
Bug Best Practice introduced by
The expression $appVersion of type null|string is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
131
            $app = Robo::createDefaultApplication($appName, $appVersion);
132
        }
133
        $commandFiles = $this->getRoboFileCommands($output);
0 ignored issues
show
Bug introduced by
It seems like $output defined by parameter $output on line 125 can be null; however, Robo\Runner::getRoboFileCommands() does not accept null, maybe add an additional type check?

It seems like you allow that null is being passed for a parameter, however the function which is called does not seem to accept null.

We recommend to add an additional type check (or disallow null for the parameter):

function notNullable(stdClass $x) { }

// Unsafe
function withoutCheck(stdClass $x = null) {
    notNullable($x);
}

// Safe - Alternative 1: Adding Additional Type-Check
function withCheck(stdClass $x = null) {
    if ($x instanceof stdClass) {
        notNullable($x);
    }
}

// Safe - Alternative 2: Changing Parameter
function withNonNullableParam(stdClass $x) {
    notNullable($x);
}
Loading history...
134
        return $this->run($argv, $output, $app, $commandFiles, $this->classLoader);
0 ignored issues
show
Documentation introduced by
$argv is of type array, but the function expects a null|object<Symfony\Comp...e\Input\InputInterface>.

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...
Documentation introduced by
$commandFiles is of type null|string, but the function expects a array<integer,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...
135
    }
136
137
    /**
138
     * @param null|\Symfony\Component\Console\Input\InputInterface $input
139
     * @param null|\Symfony\Component\Console\Output\OutputInterface $output
140
     * @param null|\Robo\Application $app
141
     * @param array[] $commandFiles
142
     * @param null|ClassLoader $classLoader
143
     *
144
     * @return int
145
     */
146
    public function run($input = null, $output = null, $app = null, $commandFiles = [], $classLoader = null)
147
    {
148
        // Create default input and output objects if they were not provided
149
        if (!$input) {
150
            $input = new StringInput('');
151
        }
152
        if (is_array($input)) {
153
            $input = new ArgvInput($input);
154
        }
155
        if (!$output) {
156
            $output = new \Symfony\Component\Console\Output\ConsoleOutput();
157
        }
158
        $this->setInput($input);
159
        $this->setOutput($output);
160
161
        // If we were not provided a container, then create one
162
        if (!$this->getContainer()) {
163
            $userConfig = 'robo.yml';
164
            $roboAppConfig = dirname(__DIR__) . '/robo.yml';
165
            $config = Robo::createConfiguration([$userConfig, $roboAppConfig]);
166
            $container = Robo::createDefaultContainer($input, $output, $app, $config, $classLoader);
167
            $this->setContainer($container);
168
            // Automatically register a shutdown function and
169
            // an error handler when we provide the container.
170
            $this->installRoboHandlers();
171
        }
172
173
        if (!$app) {
174
            $app = Robo::application();
175
        }
176
        if ($app instanceof \Robo\Application) {
177
            $app->addSelfUpdateCommand($this->getSelfUpdateRepository());
178
            if (!isset($commandFiles)) {
179
                $this->errorCondtion("Robo is not initialized here. Please run `robo init` to create a new RoboFile.", 'yellow');
180
                $app->addInitRoboFileCommand($this->roboFile, $this->roboClass);
181
                $commandFiles = [];
182
            }
183
        }
184
185
        $commandClasses = $this->discoverCommandClasses($this->commandFileRelativeNamespace);
186
        $commandFiles = array_merge((array)$commandFiles, $commandClasses);
187
188
        $this->registerCommandClasses($app, $commandFiles);
189
190
        try {
191
            $statusCode = $app->run($input, $output);
192
        } catch (TaskExitException $e) {
193
            $statusCode = $e->getCode() ?: 1;
194
        }
195
196
        // If there were any error conditions in bootstrapping Robo,
197
        // print them only if the requested command did not complete
198
        // successfully.
199
        if ($statusCode) {
200
            foreach ($this->errorConditions as $msg => $color) {
201
                $this->yell($msg, 40, $color);
202
            }
203
        }
204
        return $statusCode;
205
    }
206
207
    /**
208
     * @param \Symfony\Component\Console\Output\OutputInterface $output
209
     *
210
     * @return null|string
211
     */
212
    protected function getRoboFileCommands($output)
213
    {
214
        if (!$this->loadRoboFile($output)) {
215
            return;
216
        }
217
        return $this->roboClass;
218
    }
219
220
    /**
221
     * @param \Robo\Application $app
222
     * @param array $commandClasses
223
     */
224
    public function registerCommandClasses($app, $commandClasses)
225
    {
226
        foreach ((array)$commandClasses as $commandClass) {
227
            $this->registerCommandClass($app, $commandClass);
228
        }
229
    }
230
231
    /**
232
     * @param $relativeNamespace
233
     *
234
     * @return array|string[]
235
     */
236
    protected function discoverCommandClasses($relativeNamespace)
237
    {
238
        /** @var \Robo\ClassDiscovery\RelativeNamespaceDiscovery $discovery */
239
        $discovery = Robo::service('relativeNamespaceDiscovery');
240
        $discovery->setRelativeNamespace($relativeNamespace);
241
        return $discovery->getClasses();
242
    }
243
244
    /**
245
     * @param \Robo\Application $app
246
     * @param string|BuilderAwareInterface|ContainerAwareInterface $commandClass
247
     *
248
     * @return mixed|void
249
     */
250
    public function registerCommandClass($app, $commandClass)
251
    {
252
        $container = Robo::getContainer();
253
        $roboCommandFileInstance = $this->instantiateCommandClass($commandClass);
254
        if (!$roboCommandFileInstance) {
255
            return;
256
        }
257
258
        // Register commands for all of the public methods in the RoboFile.
259
        $commandFactory = $container->get('commandFactory');
260
        $commandList = $commandFactory->createCommandsFromClass($roboCommandFileInstance);
261
        foreach ($commandList as $command) {
262
            $app->add($command);
263
        }
264
        return $roboCommandFileInstance;
265
    }
266
267
    /**
268
     * @param string|BuilderAwareInterface|ContainerAwareInterface  $commandClass
269
     *
270
     * @return null|object
271
     */
272
    protected function instantiateCommandClass($commandClass)
273
    {
274
        $container = Robo::getContainer();
275
276
        // Register the RoboFile with the container and then immediately
277
        // fetch it; this ensures that all of the inflectors will run.
278
        // If the command class is already an instantiated object, then
279
        // just use it exactly as it was provided to us.
280
        if (is_string($commandClass)) {
281
            if (!class_exists($commandClass)) {
282
                return;
283
            }
284
            $reflectionClass = new \ReflectionClass($commandClass);
285
            if ($reflectionClass->isAbstract()) {
286
                return;
287
            }
288
289
            $commandFileName = "{$commandClass}Commands";
290
            $container->share($commandFileName, $commandClass);
291
            $commandClass = $container->get($commandFileName);
292
        }
293
        // If the command class is a Builder Aware Interface, then
294
        // ensure that it has a builder.  Every command class needs
295
        // its own collection builder, as they have references to each other.
296
        if ($commandClass instanceof BuilderAwareInterface) {
297
            $builder = CollectionBuilder::create($container, $commandClass);
298
            $commandClass->setBuilder($builder);
299
        }
300
        if ($commandClass instanceof ContainerAwareInterface) {
301
            $commandClass->setContainer($container);
302
        }
303
        return $commandClass;
304
    }
305
306
    public function installRoboHandlers()
307
    {
308
        register_shutdown_function(array($this, 'shutdown'));
309
        set_error_handler(array($this, 'handleError'));
310
    }
311
312
    /**
313
     * Process a shebang script, if one was used to launch this Runner.
314
     *
315
     * @param array $args
316
     *
317
     * @return array $args with shebang script removed
318
     */
319
    protected function shebang($args)
320
    {
321
        // Option 1: Shebang line names Robo, but includes no parameters.
322
        // #!/bin/env robo
323
        // The robo class may contain multiple commands; the user may
324
        // select which one to run, or even get a list of commands or
325
        // run 'help' on any of the available commands as usual.
326 View Code Duplication
        if ((count($args) > 1) && $this->isShebangFile($args[1])) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
327
            return array_merge([$args[0]], array_slice($args, 2));
328
        }
329
        // Option 2: Shebang line stipulates which command to run.
330
        // #!/bin/env robo mycommand
331
        // The robo class must contain a public method named 'mycommand'.
332
        // This command will be executed every time.  Arguments and options
333
        // may be provided on the commandline as usual.
334 View Code Duplication
        if ((count($args) > 2) && $this->isShebangFile($args[2])) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
335
            return array_merge([$args[0]], explode(' ', $args[1]), array_slice($args, 3));
336
        }
337
        return $args;
338
    }
339
340
    /**
341
     * Determine if the specified argument is a path to a shebang script.
342
     * If so, load it.
343
     *
344
     * @param string $filepath file to check
345
     *
346
     * @return bool Returns TRUE if shebang script was processed
347
     */
348
    protected function isShebangFile($filepath)
349
    {
350
        if (!is_file($filepath)) {
351
            return false;
352
        }
353
        $fp = fopen($filepath, "r");
354
        if ($fp === false) {
355
            return false;
356
        }
357
        $line = fgets($fp);
358
        $result = $this->isShebangLine($line);
359
        if ($result) {
360
            while ($line = fgets($fp)) {
361
                $line = trim($line);
362
                if ($line == '<?php') {
363
                    $script = stream_get_contents($fp);
364
                    if (preg_match('#^class *([^ ]+)#m', $script, $matches)) {
365
                        $this->roboClass = $matches[1];
366
                        eval($script);
0 ignored issues
show
Coding Style introduced by
It is generally not recommended to use eval unless absolutely required.

On one hand, eval might be exploited by malicious users if they somehow manage to inject dynamic content. On the other hand, with the emergence of faster PHP runtimes like the HHVM, eval prevents some optimization that they perform.

Loading history...
367
                        $result = true;
368
                    }
369
                }
370
            }
371
        }
372
        fclose($fp);
373
374
        return $result;
375
    }
376
377
    /**
378
     * Test to see if the provided line is a robo 'shebang' line.
379
     *
380
     * @param string $line
381
     *
382
     * @return bool
383
     */
384
    protected function isShebangLine($line)
385
    {
386
        return ((substr($line, 0, 2) == '#!') && (strstr($line, 'robo') !== false));
387
    }
388
389
    /**
390
     * Check for Robo-specific arguments such as --load-from, process them,
391
     * and remove them from the array.  We have to process --load-from before
392
     * we set up Symfony Console.
393
     *
394
     * @param array $argv
395
     *
396
     * @return array
397
     */
398
    protected function processRoboOptions($argv)
399
    {
400
        // loading from other directory
401
        $pos = $this->arraySearchBeginsWith('--load-from', $argv) ?: array_search('-f', $argv);
402
        if ($pos === false) {
403
            return $argv;
404
        }
405
406
        $passThru = array_search('--', $argv);
407
        if (($passThru !== false) && ($passThru < $pos)) {
408
            return $argv;
409
        }
410
411
        if (substr($argv[$pos], 0, 12) == '--load-from=') {
412
            $this->dir = substr($argv[$pos], 12);
413
        } elseif (isset($argv[$pos +1])) {
414
            $this->dir = $argv[$pos +1];
415
            unset($argv[$pos +1]);
416
        }
417
        unset($argv[$pos]);
418
        // Make adjustments if '--load-from' points at a file.
419
        if (is_file($this->dir) || (substr($this->dir, -4) == '.php')) {
420
            $this->roboFile = basename($this->dir);
421
            $this->dir = dirname($this->dir);
422
            $className = basename($this->roboFile, '.php');
423
            if ($className != $this->roboFile) {
424
                $this->roboClass = $className;
425
            }
426
        }
427
        // Convert directory to a real path, but only if the
428
        // path exists. We do not want to lose the original
429
        // directory if the user supplied a bad value.
430
        $realDir = realpath($this->dir);
431
        if ($realDir) {
432
            chdir($realDir);
433
            $this->dir = $realDir;
434
        }
435
436
        return $argv;
437
    }
438
439
    /**
440
     * @param string $needle
441
     * @param string[] $haystack
442
     *
443
     * @return bool|int
444
     */
445
    protected function arraySearchBeginsWith($needle, $haystack)
446
    {
447
        for ($i = 0; $i < count($haystack); ++$i) {
0 ignored issues
show
Performance Best Practice introduced by
It seems like you are calling the size function count() as part of the test condition. You might want to compute the size beforehand, and not on each iteration.

If the size of the collection does not change during the iteration, it is generally a good practice to compute it beforehand, and not on each iteration:

for ($i=0; $i<count($array); $i++) { // calls count() on each iteration
}

// Better
for ($i=0, $c=count($array); $i<$c; $i++) { // calls count() just once
}
Loading history...
448
            if (substr($haystack[$i], 0, strlen($needle)) == $needle) {
449
                return $i;
450
            }
451
        }
452
        return false;
453
    }
454
455
    public function shutdown()
456
    {
457
        $error = error_get_last();
458
        if (!is_array($error)) {
459
            return;
460
        }
461
        $this->writeln(sprintf("<error>ERROR: %s \nin %s:%d\n</error>", $error['message'], $error['file'], $error['line']));
462
    }
463
464
    /**
465
     * This is just a proxy error handler that checks the current error_reporting level.
466
     * In case error_reporting is disabled the error is marked as handled, otherwise
467
     * the normal internal error handling resumes.
468
     *
469
     * @return bool
470
     */
471
    public function handleError()
472
    {
473
        if (error_reporting() === 0) {
474
            return true;
475
        }
476
        return false;
477
    }
478
479
    /**
480
     * @return string
481
     */
482
    public function getSelfUpdateRepository()
483
    {
484
        return $this->selfUpdateRepository;
485
    }
486
487
    /**
488
     * @param $selfUpdateRepository
489
     *
490
     * @return $this
491
     */
492
    public function setSelfUpdateRepository($selfUpdateRepository)
493
    {
494
        $this->selfUpdateRepository = $selfUpdateRepository;
495
        return $this;
496
    }
497
498
    /**
499
     * @param \Composer\Autoload\ClassLoader $classLoader
500
     *
501
     * @return $this
502
     */
503
    public function setClassLoader(ClassLoader $classLoader)
504
    {
505
        $this->classLoader = $classLoader;
506
        return $this;
507
    }
508
509
    /**
510
     * @param string $relativeNamespace
511
     *
512
     * @return $this
513
     */
514
    public function setCommandFileRelativeNamespace($relativeNamespace)
515
    {
516
        $this->commandFileRelativeNamespace = $relativeNamespace;
517
        return $this;
518
    }
519
}
520