1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
/** |
4
|
|
|
* This file is part of slick/web_stack package |
5
|
|
|
* |
6
|
|
|
* For the full copyright and license information, please view the LICENSE |
7
|
|
|
* file that was distributed with this source code. |
8
|
|
|
*/ |
9
|
|
|
|
10
|
|
|
namespace Slick\WebStack\Dispatcher; |
11
|
|
|
|
12
|
|
|
use Aura\Router\Route; |
13
|
|
|
|
14
|
|
|
/** |
15
|
|
|
* ControllerDispatchInflector |
16
|
|
|
* |
17
|
|
|
* @package Slick\WebStack\Dispatcher |
18
|
|
|
*/ |
19
|
|
|
class ControllerDispatchInflector implements ControllerDispatchInflectorInterface |
20
|
|
|
{ |
21
|
|
|
/** |
22
|
|
|
* Returns the controller class name from provided route |
23
|
|
|
* |
24
|
|
|
* @param Route $route |
25
|
|
|
* |
26
|
|
|
* @return ControllerDispatch |
27
|
|
|
*/ |
28
|
|
|
public function inflect(Route $route) |
29
|
|
|
{ |
30
|
|
|
$arguments = $this->extractAttributes($route); |
31
|
|
|
return $this->createDispatch($arguments); |
32
|
|
|
} |
33
|
|
|
|
34
|
|
|
/** |
35
|
|
|
* Get arguments form route attributes |
36
|
|
|
* |
37
|
|
|
* @param Route $route |
38
|
|
|
* @return array |
39
|
|
|
*/ |
40
|
|
|
private function extractAttributes(Route $route) |
41
|
|
|
{ |
42
|
|
|
$arguments = [ |
43
|
|
|
'namespace' => null, |
44
|
|
|
'controller' => null, |
45
|
|
|
'action' => null, |
46
|
|
|
'args' => [] |
47
|
|
|
]; |
48
|
|
|
foreach (array_keys($arguments) as $name) { |
49
|
|
|
$arguments[$name] = array_key_exists($name, $route->attributes) |
50
|
|
|
? $route->attributes[$name] |
51
|
|
|
: $arguments[$name]; |
52
|
|
|
} |
53
|
|
|
return $arguments; |
54
|
|
|
} |
55
|
|
|
|
56
|
|
|
/** |
57
|
|
|
* Create a controller dispatch with provided arguments |
58
|
|
|
* |
59
|
|
|
* @param array $arguments |
60
|
|
|
* |
61
|
|
|
* @return ControllerDispatch|Object |
62
|
|
|
*/ |
63
|
|
|
private function createDispatch(array $arguments) |
64
|
|
|
{ |
65
|
|
|
$arguments['controller'] = $this->filterName($arguments['controller']); |
66
|
|
|
$data = [ |
67
|
|
|
'className' => ltrim( |
68
|
|
|
"{$arguments['namespace']}"."\\"."{$arguments['controller']}", |
69
|
|
|
"\\" |
70
|
|
|
), |
71
|
|
|
'method' => lcfirst($this->filterName($arguments['action'])), |
72
|
|
|
'arguments' => $arguments['args'] |
73
|
|
|
]; |
74
|
|
|
$reflection = new \ReflectionClass(ControllerDispatch::class); |
75
|
|
|
return $reflection->newInstanceArgs($data); |
76
|
|
|
} |
77
|
|
|
|
78
|
|
|
/** |
79
|
|
|
* Filters the controller class name |
80
|
|
|
* |
81
|
|
|
* @param string $name |
82
|
|
|
* |
83
|
|
|
* @return string |
84
|
|
|
*/ |
85
|
|
|
private function filterName($name) |
86
|
|
|
{ |
87
|
|
|
$name = str_replace(['-', '_'], ' ', $name); |
88
|
|
|
$words = explode(' ', $name); |
89
|
|
|
$filtered = ''; |
90
|
|
|
foreach ($words as $word) { |
91
|
|
|
$filtered .= ucfirst($word); |
92
|
|
|
} |
93
|
|
|
return $filtered; |
94
|
|
|
} |
95
|
|
|
} |
96
|
|
|
|