1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Mpociot\ApiDoc\Parsers; |
4
|
|
|
|
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) |
17
|
|
|
{ |
18
|
|
|
$this->rule = "apidoc::rules.{$rule}"; |
19
|
|
|
} |
20
|
|
|
|
21
|
|
|
/** |
22
|
|
|
* @return array|string |
23
|
|
|
*/ |
24
|
|
|
public function getDescription() |
25
|
|
|
{ |
26
|
|
|
return $this->ruleDescriptionExist() ? $this->makeDescription() : []; |
27
|
|
|
} |
28
|
|
|
|
29
|
|
|
/** |
30
|
|
|
* @param string|array $parameters |
31
|
|
|
* |
32
|
|
|
* @return $this |
33
|
|
|
*/ |
34
|
|
|
public function with($parameters) |
35
|
|
|
{ |
36
|
|
|
is_array($parameters) ? |
37
|
|
|
$this->parameters += $parameters : |
38
|
|
|
$this->parameters[] = $parameters; |
39
|
|
|
|
40
|
|
|
return $this; |
41
|
|
|
} |
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) |
69
|
|
|
{ |
70
|
|
|
foreach ($this->parameters as $parameter) { |
71
|
|
|
$description = preg_replace('/:attribute/', $parameter, $description, 1); |
72
|
|
|
} |
73
|
|
|
|
74
|
|
|
return $description; |
75
|
|
|
} |
76
|
|
|
|
77
|
|
|
/** |
78
|
|
|
* @param null $rule |
79
|
|
|
* |
80
|
|
|
* @return static |
81
|
|
|
*/ |
82
|
|
|
public static function parse($rule = null) |
83
|
|
|
{ |
84
|
|
|
return new static($rule); |
85
|
|
|
} |
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: