1 | <?php |
||
5 | class RuleDescriptionParser |
||
6 | { |
||
7 | private $rule; |
||
8 | |||
9 | private $parameters = []; |
||
10 | |||
11 | const DEFAULT_LOCALE = 'en'; |
||
12 | |||
13 | /** |
||
14 | * @param null $rule |
||
15 | */ |
||
16 | public function __construct($rule = null) |
||
20 | |||
21 | /** |
||
22 | * @return array|string |
||
23 | */ |
||
24 | public function getDescription() |
||
28 | |||
29 | /** |
||
30 | * @param string|array $parameters |
||
31 | * |
||
32 | * @return $this |
||
33 | */ |
||
34 | public function with($parameters) |
||
42 | |||
43 | /** |
||
44 | * @return bool |
||
45 | */ |
||
46 | protected function ruleDescriptionExist() |
||
47 | { |
||
48 | return trans()->hasForLocale($this->rule) || trans()->hasForLocale($this->rule, self::DEFAULT_LOCALE); |
||
|
|||
49 | } |
||
50 | |||
51 | /** |
||
52 | * @return string |
||
53 | */ |
||
54 | protected function makeDescription() |
||
55 | { |
||
56 | $description = trans()->hasForLocale($this->rule) ? |
||
57 | trans()->get($this->rule) : |
||
58 | trans()->get($this->rule, [], self::DEFAULT_LOCALE); |
||
59 | |||
60 | return $this->replaceAttributes($description); |
||
61 | } |
||
62 | |||
63 | /** |
||
64 | * @param string $description$ |
||
65 | * |
||
66 | * @return string |
||
67 | */ |
||
68 | protected function replaceAttributes($description) |
||
76 | |||
77 | /** |
||
78 | * @param null $rule |
||
79 | * |
||
80 | * @return static |
||
81 | */ |
||
82 | public static function parse($rule = null) |
||
86 | } |
||
87 |
Let’s take a look at an example:
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
Change the type-hint for the parameter:
Add an additional type-check:
Add the method to the interface: