Completed
Push — fix-wrong-response-code-in-err... ( 60af75...b69ef7 )
by Alexander
79:57 queued 39:19
created

Controller::getActionArgsHelp()   C

Complexity

Conditions 7
Paths 20

Size

Total Lines 40
Code Lines 29

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 26
CRAP Score 7.0178

Importance

Changes 0
Metric Value
dl 0
loc 40
ccs 26
cts 28
cp 0.9286
rs 6.7272
c 0
b 0
f 0
cc 7
eloc 29
nc 20
nop 1
crap 7.0178
1
<?php
2
/**
3
 * @link http://www.yiiframework.com/
4
 * @copyright Copyright (c) 2008 Yii Software LLC
5
 * @license http://www.yiiframework.com/license/
6
 */
7
8
namespace yii\console;
9
10
use Yii;
11
use yii\base\Action;
12
use yii\base\InlineAction;
13
use yii\base\InvalidRouteException;
14
use yii\helpers\Console;
15
16
/**
17
 * Controller is the base class of console command classes.
18
 *
19
 * A console controller consists of one or several actions known as sub-commands.
20
 * Users call a console command by specifying the corresponding route which identifies a controller action.
21
 * The `yii` program is used when calling a console command, like the following:
22
 *
23
 * ```
24
 * yii <route> [--param1=value1 --param2 ...]
25
 * ```
26
 *
27
 * where `<route>` is a route to a controller action and the params will be populated as properties of a command.
28
 * See [[options()]] for details.
29
 *
30
 * @property string $help This property is read-only.
31
 * @property string $helpSummary This property is read-only.
32
 * @property array $passedOptionValues The properties corresponding to the passed options. This property is
33
 * read-only.
34
 * @property array $passedOptions The names of the options passed during execution. This property is
35
 * read-only.
36
 *
37
 * @author Qiang Xue <[email protected]>
38
 * @since 2.0
39
 */
40
class Controller extends \yii\base\Controller
41
{
42
    const EXIT_CODE_NORMAL = 0;
43
    const EXIT_CODE_ERROR = 1;
44
45
    /**
46
     * @var bool whether to run the command interactively.
47
     */
48
    public $interactive = true;
49
    /**
50
     * @var bool whether to enable ANSI color in the output.
51
     * If not set, ANSI color will only be enabled for terminals that support it.
52
     */
53
    public $color;
54
    /**
55
     * @var bool whether to display help information about current command.
56
     * @since 2.0.10
57
     */
58
    public $help;
59
60
    /**
61
     * @var array the options passed during execution.
62
     */
63
    private $_passedOptions = [];
64
65
66
    /**
67
     * Returns a value indicating whether ANSI color is enabled.
68
     *
69
     * ANSI color is enabled only if [[color]] is set true or is not set
70
     * and the terminal supports ANSI color.
71
     *
72
     * @param resource $stream the stream to check.
73
     * @return bool Whether to enable ANSI style in output.
74
     */
75 4
    public function isColorEnabled($stream = \STDOUT)
76
    {
77 4
        return $this->color === null ? Console::streamSupportsAnsiColors($stream) : $this->color;
78
    }
79
80
    /**
81
     * Runs an action with the specified action ID and parameters.
82
     * If the action ID is empty, the method will use [[defaultAction]].
83
     * @param string $id the ID of the action to be executed.
84
     * @param array $params the parameters (name-value pairs) to be passed to the action.
85
     * @return int the status of the action execution. 0 means normal, other values mean abnormal.
86
     * @throws InvalidRouteException if the requested action ID cannot be resolved into an action successfully.
87
     * @throws Exception if there are unknown options or missing arguments
88
     * @see createAction
89
     */
90 70
    public function runAction($id, $params = [])
91
    {
92 70
        if (!empty($params)) {
93
            // populate options here so that they are available in beforeAction().
94 61
            $options = $this->options($id === '' ? $this->defaultAction : $id);
95 61
            if (isset($params['_aliases'])) {
96 1
                $optionAliases = $this->optionAliases();
97 1
                foreach ($params['_aliases'] as $name => $value) {
98 1
                    if (array_key_exists($name, $optionAliases)) {
99 1
                        $params[$optionAliases[$name]] = $value;
100 1
                    } else {
101
                        throw new Exception(Yii::t('yii', 'Unknown alias: -{name}', ['name' => $name]));
102
                    }
103 1
                }
104 1
                unset($params['_aliases']);
105 1
            }
106 61
            foreach ($params as $name => $value) {
107 61
                if (in_array($name, $options, true)) {
108 5
                    $default = $this->$name;
109 5
                    if (is_array($default)) {
110 5
                        $this->$name = preg_split('/\s*,\s*(?![^()]*\))/', $value);
111 5
                    } elseif ($default !== null) {
112 2
                        settype($value, gettype($default));
113 2
                        $this->$name = $value;
114 2
                    } else {
115 1
                        $this->$name = $value;
116
                    }
117 5
                    $this->_passedOptions[] = $name;
118 5
                    unset($params[$name]);
119 61
                } elseif (!is_int($name)) {
120
                    throw new Exception(Yii::t('yii', 'Unknown option: --{name}', ['name' => $name]));
121
                }
122 61
            }
123 61
        }
124 70
        if ($this->help) {
125 2
            $route = $this->getUniqueId() . '/' . $id;
126 2
            return Yii::$app->runAction('help', [$route]);
127
        }
128 70
        return parent::runAction($id, $params);
129
    }
130
131
    /**
132
     * Binds the parameters to the action.
133
     * This method is invoked by [[Action]] when it begins to run with the given parameters.
134
     * This method will first bind the parameters with the [[options()|options]]
135
     * available to the action. It then validates the given arguments.
136
     * @param Action $action the action to be bound with parameters
137
     * @param array $params the parameters to be bound to the action
138
     * @return array the valid parameters that the action can run with.
139
     * @throws Exception if there are unknown options or missing arguments
140
     */
141 76
    public function bindActionParams($action, $params)
142
    {
143 76
        if ($action instanceof InlineAction) {
144 76
            $method = new \ReflectionMethod($this, $action->actionMethod);
145 76
        } else {
146
            $method = new \ReflectionMethod($action, 'run');
147
        }
148
149 76
        $args = array_values($params);
150
151 76
        $missing = [];
152 76
        foreach ($method->getParameters() as $i => $param) {
153 74
            if ($param->isArray() && isset($args[$i])) {
154 1
                $args[$i] = preg_split('/\s*,\s*/', $args[$i]);
155 1
            }
156 74
            if (!isset($args[$i])) {
157 14
                if ($param->isDefaultValueAvailable()) {
158 14
                    $args[$i] = $param->getDefaultValue();
159 14
                } else {
160 1
                    $missing[] = $param->getName();
161
                }
162 14
            }
163 76
        }
164
165 76
        if (!empty($missing)) {
166 1
            throw new Exception(Yii::t('yii', 'Missing required arguments: {params}', ['params' => implode(', ', $missing)]));
167
        }
168
169 76
        return $args;
170
    }
171
172
    /**
173
     * Formats a string with ANSI codes
174
     *
175
     * You may pass additional parameters using the constants defined in [[\yii\helpers\Console]].
176
     *
177
     * Example:
178
     *
179
     * ```
180
     * echo $this->ansiFormat('This will be red and underlined.', Console::FG_RED, Console::UNDERLINE);
181
     * ```
182
     *
183
     * @param string $string the string to be formatted
184
     * @return string
185
     */
186 4
    public function ansiFormat($string)
187
    {
188 4
        if ($this->isColorEnabled()) {
189 4
            $args = func_get_args();
190 4
            array_shift($args);
191 4
            $string = Console::ansiFormat($string, $args);
192 4
        }
193 4
        return $string;
194
    }
195
196
    /**
197
     * Prints a string to STDOUT
198
     *
199
     * You may optionally format the string with ANSI codes by
200
     * passing additional parameters using the constants defined in [[\yii\helpers\Console]].
201
     *
202
     * Example:
203
     *
204
     * ```
205
     * $this->stdout('This will be red and underlined.', Console::FG_RED, Console::UNDERLINE);
206
     * ```
207
     *
208
     * @param string $string the string to print
209
     * @return int|bool Number of bytes printed or false on error
210
     */
211
    public function stdout($string)
212
    {
213
        if ($this->isColorEnabled()) {
214
            $args = func_get_args();
215
            array_shift($args);
216
            $string = Console::ansiFormat($string, $args);
217
        }
218
        return Console::stdout($string);
219
    }
220
221
    /**
222
     * Prints a string to STDERR
223
     *
224
     * You may optionally format the string with ANSI codes by
225
     * passing additional parameters using the constants defined in [[\yii\helpers\Console]].
226
     *
227
     * Example:
228
     *
229
     * ```
230
     * $this->stderr('This will be red and underlined.', Console::FG_RED, Console::UNDERLINE);
231
     * ```
232
     *
233
     * @param string $string the string to print
234
     * @return int|bool Number of bytes printed or false on error
235
     */
236
    public function stderr($string)
237
    {
238
        if ($this->isColorEnabled(\STDERR)) {
239
            $args = func_get_args();
240
            array_shift($args);
241
            $string = Console::ansiFormat($string, $args);
242
        }
243
        return fwrite(\STDERR, $string);
244
    }
245
246
    /**
247
     * Prompts the user for input and validates it
248
     *
249
     * @param string $text prompt string
250
     * @param array $options the options to validate the input:
251
     *
252
     *  - required: whether it is required or not
253
     *  - default: default value if no input is inserted by the user
254
     *  - pattern: regular expression pattern to validate user input
255
     *  - validator: a callable function to validate input. The function must accept two parameters:
256
     *      - $input: the user input to validate
257
     *      - $error: the error value passed by reference if validation failed.
258
     *
259
     * An example of how to use the prompt method with a validator function.
260
     *
261
     * ```php
262
     * $code = $this->prompt('Enter 4-Chars-Pin', ['required' => true, 'validator' => function($input, &$error) {
263
     *     if (strlen($input) !== 4) {
264
     *         $error = 'The Pin must be exactly 4 chars!';
265
     *         return false;
266
     *     }
267
     *     return true;
268
     * }]);
269
     * ```
270
     *
271
     * @return string the user input
272
     */
273
    public function prompt($text, $options = [])
274
    {
275
        if ($this->interactive) {
276
            return Console::prompt($text, $options);
277
        }
278
279
        return isset($options['default']) ? $options['default'] : '';
280
    }
281
282
    /**
283
     * Asks user to confirm by typing y or n.
284
     *
285
     * A typical usage looks like the following:
286
     *
287
     * ```php
288
     * if ($this->confirm("Are you sure?")) {
289
     *     echo "user typed yes\n";
290
     * } else {
291
     *     echo "user typed no\n";
292
     * }
293
     * ```
294
     *
295
     * @param string $message to echo out before waiting for user input
296
     * @param bool $default this value is returned if no selection is made.
297
     * @return bool whether user confirmed.
298
     * Will return true if [[interactive]] is false.
299
     */
300 34
    public function confirm($message, $default = false)
301
    {
302 34
        if ($this->interactive) {
303
            return Console::confirm($message, $default);
304
        }
305
306 34
        return true;
307
    }
308
309
    /**
310
     * Gives the user an option to choose from. Giving '?' as an input will show
311
     * a list of options to choose from and their explanations.
312
     *
313
     * @param string $prompt the prompt message
314
     * @param array $options Key-value array of options to choose from
315
     *
316
     * @return string An option character the user chose
317
     */
318
    public function select($prompt, $options = [])
319
    {
320
        return Console::select($prompt, $options);
321
    }
322
323
    /**
324
     * Returns the names of valid options for the action (id)
325
     * An option requires the existence of a public member variable whose
326
     * name is the option name.
327
     * Child classes may override this method to specify possible options.
328
     *
329
     * Note that the values setting via options are not available
330
     * until [[beforeAction()]] is being called.
331
     *
332
     * @param string $actionID the action id of the current request
333
     * @return string[] the names of the options valid for the action
334
     */
335 64
    public function options($actionID)
336
    {
337
        // $actionId might be used in subclasses to provide options specific to action id
338 64
        return ['color', 'interactive', 'help'];
339
    }
340
341
    /**
342
     * Returns option alias names.
343
     * Child classes may override this method to specify alias options.
344
     *
345
     * @return array the options alias names valid for the action
346
     * where the keys is alias name for option and value is option name.
347
     *
348
     * @since 2.0.8
349
     * @see options()
350
     */
351 2
    public function optionAliases()
352
    {
353
        return [
354
            'h' => 'help'
355 2
        ];
356
    }
357
358
    /**
359
     * Returns properties corresponding to the options for the action id
360
     * Child classes may override this method to specify possible properties.
361
     *
362
     * @param string $actionID the action id of the current request
363
     * @return array properties corresponding to the options for the action
364
     */
365 32
    public function getOptionValues($actionID)
0 ignored issues
show
Unused Code introduced by
The parameter $actionID 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...
366
    {
367
        // $actionId might be used in subclasses to provide properties specific to action id
368 32
        $properties = [];
369 32
        foreach ($this->options($this->action->id) as $property) {
370 32
            $properties[$property] = $this->$property;
371 32
        }
372 32
        return $properties;
373
    }
374
375
    /**
376
     * Returns the names of valid options passed during execution.
377
     *
378
     * @return array the names of the options passed during execution
379
     */
380
    public function getPassedOptions()
381
    {
382
        return $this->_passedOptions;
383
    }
384
385
    /**
386
     * Returns the properties corresponding to the passed options
387
     *
388
     * @return array the properties corresponding to the passed options
389
     */
390 29
    public function getPassedOptionValues()
391
    {
392 29
        $properties = [];
393 29
        foreach ($this->_passedOptions as $property) {
394
            $properties[$property] = $this->$property;
395 29
        }
396 29
        return $properties;
397
    }
398
399
    /**
400
     * Returns one-line short summary describing this controller.
401
     *
402
     * You may override this method to return customized summary.
403
     * The default implementation returns first line from the PHPDoc comment.
404
     *
405
     * @return string
406
     */
407 2
    public function getHelpSummary()
408
    {
409 2
        return $this->parseDocCommentSummary(new \ReflectionClass($this));
410
    }
411
412
    /**
413
     * Returns help information for this controller.
414
     *
415
     * You may override this method to return customized help.
416
     * The default implementation returns help information retrieved from the PHPDoc comment.
417
     * @return string
418
     */
419
    public function getHelp()
420
    {
421
        return $this->parseDocCommentDetail(new \ReflectionClass($this));
422
    }
423
424
    /**
425
     * Returns a one-line short summary describing the specified action.
426
     * @param Action $action action to get summary for
427
     * @return string a one-line short summary describing the specified action.
428
     */
429 1
    public function getActionHelpSummary($action)
430
    {
431 1
        return $this->parseDocCommentSummary($this->getActionMethodReflection($action));
432
    }
433
434
    /**
435
     * Returns the detailed help information for the specified action.
436
     * @param Action $action action to get help for
437
     * @return string the detailed help information for the specified action.
438
     */
439 2
    public function getActionHelp($action)
440
    {
441 2
        return $this->parseDocCommentDetail($this->getActionMethodReflection($action));
442
    }
443
444
    /**
445
     * Returns the help information for the anonymous arguments for the action.
446
     * The returned value should be an array. The keys are the argument names, and the values are
447
     * the corresponding help information. Each value must be an array of the following structure:
448
     *
449
     * - required: boolean, whether this argument is required.
450
     * - type: string, the PHP type of this argument.
451
     * - default: string, the default value of this argument
452
     * - comment: string, the comment of this argument
453
     *
454
     * The default implementation will return the help information extracted from the doc-comment of
455
     * the parameters corresponding to the action method.
456
     *
457
     * @param Action $action
458
     * @return array the help information of the action arguments
459
     */
460 4
    public function getActionArgsHelp($action)
461
    {
462 4
        $method = $this->getActionMethodReflection($action);
463 4
        $tags = $this->parseDocCommentTags($method);
464 4
        $params = isset($tags['param']) ? (array) $tags['param'] : [];
465
466 4
        $args = [];
467
468
        /** @var \ReflectionParameter $reflection */
469 4
        foreach ($method->getParameters() as $i => $reflection) {
470 4
            if ($reflection->getClass() !== null) {
471 4
                continue;
472 4
            }
473 4
            $name = $reflection->getName();
474 4
            $tag = isset($params[$i]) ? $params[$i] : '';
475 4
            if (preg_match('/^(\S+)\s+(\$\w+\s+)?(.*)/s', $tag, $matches)) {
476
                $type = $matches[1];
477
                $comment = $matches[3];
478
            } else {
479 4
                $type = null;
480 2
                $comment = $tag;
481 2
            }
482 2
            if ($reflection->isDefaultValueAvailable()) {
483 2
                $args[$name] = [
484 2
                    'required' => false,
485
                    'type' => $type,
486 2
                    'default' => $reflection->getDefaultValue(),
487 2
                    'comment' => $comment,
488 2
                ];
489 2
            } else {
490 2
                $args[$name] = [
491 2
                    'required' => true,
492
                    'type' => $type,
493
                    'default' => null,
494 4
                    'comment' => $comment,
495 4
                ];
496
            }
497
        }
498
        return $args;
499
    }
500
501
    /**
502
     * Returns the help information for the options for the action.
503
     * The returned value should be an array. The keys are the option names, and the values are
504
     * the corresponding help information. Each value must be an array of the following structure:
505
     *
506
     * - type: string, the PHP type of this argument.
507
     * - default: string, the default value of this argument
508
     * - comment: string, the comment of this argument
509
     *
510
     * The default implementation will return the help information extracted from the doc-comment of
511
     * the properties corresponding to the action options.
512
     *
513 3
     * @param Action $action
514
     * @return array the help information of the action options
515 3
     */
516 3
    public function getActionOptionsHelp($action)
517
    {
518
        $optionNames = $this->options($action->id);
519
        if (empty($optionNames)) {
520 3
            return [];
521 3
        }
522 3
523 3
        $class = new \ReflectionClass($this);
524 3
        $options = [];
525 3
        foreach ($class->getProperties() as $property) {
526
            $name = $property->getName();
527 3
            if (!in_array($name, $optionNames, true)) {
528 3
                continue;
529 3
            }
530 3
            $defaultValue = $property->getValue($this);
531 3
            $tags = $this->parseDocCommentTags($property);
532
            if (isset($tags['var']) || isset($tags['property'])) {
533
                $doc = isset($tags['var']) ? $tags['var'] : $tags['property'];
534 3
                if (is_array($doc)) {
535 3
                    $doc = reset($doc);
536 3
                }
537 3
                if (preg_match('/^(\S+)(.*)/s', $doc, $matches)) {
538
                    $type = $matches[1];
539
                    $comment = $matches[2];
540
                } else {
541 3
                    $type = null;
542 3
                    $comment = $doc;
543 3
                }
544 3
                $options[$name] = [
545
                    'type' => $type,
546 3
                    'default' => $defaultValue,
547
                    'comment' => $comment,
548
                ];
549
            } else {
550
                $options[$name] = [
551
                    'type' => null,
552
                    'default' => $defaultValue,
553 3
                    'comment' => '',
554 3
                ];
555
            }
556
        }
557
        return $options;
558
    }
559
560
    private $_reflections = [];
561
562
    /**
563 5
     * @param Action $action
564
     * @return \ReflectionMethod
565 5
     */
566 5
    protected function getActionMethodReflection($action)
567 5
    {
568 5
        if (!isset($this->_reflections[$action->id])) {
569
            if ($action instanceof InlineAction) {
570
                $this->_reflections[$action->id] = new \ReflectionMethod($this, $action->actionMethod);
571 5
            } else {
572 5
                $this->_reflections[$action->id] = new \ReflectionMethod($action, 'run');
573
            }
574
        }
575
        return $this->_reflections[$action->id];
576
    }
577
578
    /**
579
     * Parses the comment block into tags.
580 4
     * @param \Reflector $reflection the comment block
581
     * @return array the parsed tags
582 4
     */
583 4
    protected function parseDocCommentTags($reflection)
584 4
    {
585 4
        $comment = $reflection->getDocComment();
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Reflector as the method getDocComment() does only exist in the following implementations of said interface: ReflectionClass, ReflectionFunction, ReflectionFunctionAbstract, ReflectionMethod, ReflectionObject, ReflectionProperty.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
586 4
        $comment = "@description \n" . strtr(trim(preg_replace('/^\s*\**( |\t)?/m', '', trim($comment, '/'))), "\r", '');
587 4
        $parts = preg_split('/^\s*@/m', $comment, -1, PREG_SPLIT_NO_EMPTY);
588 4
        $tags = [];
589 4
        foreach ($parts as $part) {
590 4
            if (preg_match('/^(\w+)(.*)/ms', trim($part), $matches)) {
591 4
                $name = $matches[1];
592
                if (!isset($tags[$name])) {
593
                    $tags[$name] = trim($matches[2]);
594
                } elseif (is_array($tags[$name])) {
595
                    $tags[$name][] = trim($matches[2]);
596 4
                } else {
597 4
                    $tags[$name] = [$tags[$name], trim($matches[2])];
598 4
                }
599
            }
600
        }
601
        return $tags;
602
    }
603
604
    /**
605
     * Returns the first line of docblock.
606
     *
607 2
     * @param \Reflector $reflection
608
     * @return string
609 2
     */
610 2
    protected function parseDocCommentSummary($reflection)
611 2
    {
612
        $docLines = preg_split('~\R~u', $reflection->getDocComment());
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Reflector as the method getDocComment() does only exist in the following implementations of said interface: ReflectionClass, ReflectionFunction, ReflectionFunctionAbstract, ReflectionMethod, ReflectionObject, ReflectionProperty.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
613
        if (isset($docLines[1])) {
614
            return trim($docLines[1], "\t *");
615
        }
616
        return '';
617
    }
618
619
    /**
620
     * Returns full description from the docblock.
621
     *
622 2
     * @param \Reflector $reflection
623
     * @return string
624 2
     */
625 2
    protected function parseDocCommentDetail($reflection)
626 2
    {
627 2
        $comment = strtr(trim(preg_replace('/^\s*\**( |\t)?/m', '', trim($reflection->getDocComment(), '/'))), "\r", '');
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Reflector as the method getDocComment() does only exist in the following implementations of said interface: ReflectionClass, ReflectionFunction, ReflectionFunctionAbstract, ReflectionMethod, ReflectionObject, ReflectionProperty.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
628 2
        if (preg_match('/^\s*@\w+/m', $comment, $matches, PREG_OFFSET_CAPTURE)) {
629 2
            $comment = trim(substr($comment, 0, $matches[0][1]));
630
        }
631
        if ($comment !== '') {
632
            return rtrim(Console::renderColoredString(Console::markdownToAnsi($comment)));
633
        }
634
        return '';
635
    }
636
}
637