Completed
Pull Request — 2.1 (#15718)
by Alex
17:00
created

Controller::confirm()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 2.0625

Importance

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