GitHub Access Token became invalid

It seems like the GitHub access token used for retrieving details about this repository from GitHub became invalid. This might prevent certain types of inspections from being run (in particular, everything related to pull requests).
Please ask an admin of your repository to re-new the access token on this website.
Completed
Push — master ( 7c9800...6d277d )
by Robert
25:06
created

Controller::parseDocCommentSummary()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 2.032

Importance

Changes 0
Metric Value
dl 0
loc 8
ccs 4
cts 5
cp 0.8
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 5
nc 2
nop 1
crap 2.032
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 57
    public function runAction($id, $params = [])
91
    {
92 57
        if (!empty($params)) {
93
            // populate options here so that they are available in beforeAction().
94 48
            $options = $this->options($id === '' ? $this->defaultAction : $id);
95 48
            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 48
            foreach ($params as $name => $value) {
107 48
                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 48
                } elseif (!is_int($name)) {
120
                    throw new Exception(Yii::t('yii', 'Unknown option: --{name}', ['name' => $name]));
121
                }
122 48
            }
123 48
        }
124 57
        if ($this->help) {
125 2
            $route = $this->getUniqueId() . '/' . $id;
126 2
            return Yii::$app->runAction('help', [$route]);
127
        }
128 57
        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 63
    public function bindActionParams($action, $params)
142
    {
143 63
        if ($action instanceof InlineAction) {
144 63
            $method = new \ReflectionMethod($this, $action->actionMethod);
145 63
        } else {
146
            $method = new \ReflectionMethod($action, 'run');
147
        }
148
149 63
        $args = array_values($params);
150
151 63
        $missing = [];
152 63
        foreach ($method->getParameters() as $i => $param) {
153 61
            if ($param->isArray() && isset($args[$i])) {
154 1
                $args[$i] = preg_split('/\s*,\s*/', $args[$i]);
155 1
            }
156 61
            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 63
        }
164
165 63
        if (!empty($missing)) {
166 1
            throw new Exception(Yii::t('yii', 'Missing required arguments: {params}', ['params' => implode(', ', $missing)]));
167
        }
168
169 63
        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 51
    public function options($actionID)
336
    {
337
        // $actionId might be used in subclasses to provide options specific to action id
338 51
        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 20
    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 20
        $properties = [];
369 20
        foreach ($this->options($this->action->id) as $property) {
370 20
            $properties[$property] = $this->$property;
371 20
        }
372 20
        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 18
    public function getPassedOptionValues()
391
    {
392 18
        $properties = [];
393 18
        foreach ($this->_passedOptions as $property) {
394
            $properties[$property] = $this->$property;
395 18
        }
396 18
        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
            $name = $reflection->getName();
471 4
            $tag = isset($params[$i]) ? $params[$i] : '';
472 4
            if (preg_match('/^(\S+)\s+(\$\w+\s+)?(.*)/s', $tag, $matches)) {
473 4
                $type = $matches[1];
474 4
                $comment = $matches[3];
475 4
            } else {
476
                $type = null;
477
                $comment = $tag;
478
            }
479 4
            if ($reflection->isDefaultValueAvailable()) {
480 2
                $args[$name] = [
481 2
                    'required' => false,
482 2
                    'type' => $type,
483 2
                    'default' => $reflection->getDefaultValue(),
484 2
                    'comment' => $comment,
485
                ];
486 2
            } else {
487 2
                $args[$name] = [
488 2
                    'required' => true,
489 2
                    'type' => $type,
490 2
                    'default' => null,
491 2
                    'comment' => $comment,
492
                ];
493
            }
494 4
        }
495 4
        return $args;
496
    }
497
498
    /**
499
     * Returns the help information for the options for the action.
500
     * The returned value should be an array. The keys are the option names, and the values are
501
     * the corresponding help information. Each value must be an array of the following structure:
502
     *
503
     * - type: string, the PHP type of this argument.
504
     * - default: string, the default value of this argument
505
     * - comment: string, the comment of this argument
506
     *
507
     * The default implementation will return the help information extracted from the doc-comment of
508
     * the properties corresponding to the action options.
509
     *
510
     * @param Action $action
511
     * @return array the help information of the action options
512
     */
513 3
    public function getActionOptionsHelp($action)
514
    {
515 3
        $optionNames = $this->options($action->id);
516 3
        if (empty($optionNames)) {
517
            return [];
518
        }
519
520 3
        $class = new \ReflectionClass($this);
521 3
        $options = [];
522 3
        foreach ($class->getProperties() as $property) {
523 3
            $name = $property->getName();
524 3
            if (!in_array($name, $optionNames, true)) {
525 3
                continue;
526
            }
527 3
            $defaultValue = $property->getValue($this);
528 3
            $tags = $this->parseDocCommentTags($property);
529 3
            if (isset($tags['var']) || isset($tags['property'])) {
530 3
                $doc = isset($tags['var']) ? $tags['var'] : $tags['property'];
531 3
                if (is_array($doc)) {
532
                    $doc = reset($doc);
533
                }
534 3
                if (preg_match('/^(\S+)(.*)/s', $doc, $matches)) {
535 3
                    $type = $matches[1];
536 3
                    $comment = $matches[2];
537 3
                } else {
538
                    $type = null;
539
                    $comment = $doc;
540
                }
541 3
                $options[$name] = [
542 3
                    'type' => $type,
543 3
                    'default' => $defaultValue,
544 3
                    'comment' => $comment,
545
                ];
546 3
            } else {
547
                $options[$name] = [
548
                    'type' => null,
549
                    'default' => $defaultValue,
550
                    'comment' => '',
551
                ];
552
            }
553 3
        }
554 3
        return $options;
555
    }
556
557
    private $_reflections = [];
558
559
    /**
560
     * @param Action $action
561
     * @return \ReflectionMethod
562
     */
563 5
    protected function getActionMethodReflection($action)
564
    {
565 5
        if (!isset($this->_reflections[$action->id])) {
566 5
            if ($action instanceof InlineAction) {
567 5
                $this->_reflections[$action->id] = new \ReflectionMethod($this, $action->actionMethod);
568 5
            } else {
569
                $this->_reflections[$action->id] = new \ReflectionMethod($action, 'run');
570
            }
571 5
        }
572 5
        return $this->_reflections[$action->id];
573
    }
574
575
    /**
576
     * Parses the comment block into tags.
577
     * @param \Reflector $reflection the comment block
578
     * @return array the parsed tags
579
     */
580 4
    protected function parseDocCommentTags($reflection)
581
    {
582 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...
583 4
        $comment = "@description \n" . strtr(trim(preg_replace('/^\s*\**( |\t)?/m', '', trim($comment, '/'))), "\r", '');
584 4
        $parts = preg_split('/^\s*@/m', $comment, -1, PREG_SPLIT_NO_EMPTY);
585 4
        $tags = [];
586 4
        foreach ($parts as $part) {
587 4
            if (preg_match('/^(\w+)(.*)/ms', trim($part), $matches)) {
588 4
                $name = $matches[1];
589 4
                if (!isset($tags[$name])) {
590 4
                    $tags[$name] = trim($matches[2]);
591 4
                } elseif (is_array($tags[$name])) {
592
                    $tags[$name][] = trim($matches[2]);
593
                } else {
594
                    $tags[$name] = [$tags[$name], trim($matches[2])];
595
                }
596 4
            }
597 4
        }
598 4
        return $tags;
599
    }
600
601
    /**
602
     * Returns the first line of docblock.
603
     *
604
     * @param \Reflector $reflection
605
     * @return string
606
     */
607 2
    protected function parseDocCommentSummary($reflection)
608
    {
609 2
        $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...
610 2
        if (isset($docLines[1])) {
611 2
            return trim($docLines[1], "\t *");
612
        }
613
        return '';
614
    }
615
616
    /**
617
     * Returns full description from the docblock.
618
     *
619
     * @param \Reflector $reflection
620
     * @return string
621
     */
622 2
    protected function parseDocCommentDetail($reflection)
623
    {
624 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...
625 2
        if (preg_match('/^\s*@\w+/m', $comment, $matches, PREG_OFFSET_CAPTURE)) {
626 2
            $comment = trim(substr($comment, 0, $matches[0][1]));
627 2
        }
628 2
        if ($comment !== '') {
629 2
            return rtrim(Console::renderColoredString(Console::markdownToAnsi($comment)));
630
        }
631
        return '';
632
    }
633
}
634