1
|
|
|
<?php |
2
|
|
|
namespace PTS\Routing\Point; |
3
|
|
|
|
4
|
|
|
use PTS\Routing\Route; |
5
|
|
|
|
6
|
|
|
class ControllerPoint extends AbstractPoint |
7
|
|
|
{ |
8
|
|
|
protected $controller; |
9
|
|
|
protected $action; |
10
|
|
|
|
11
|
|
|
/** |
12
|
|
|
* @param Route $route |
13
|
|
|
* @param array $args |
14
|
|
|
* |
15
|
|
|
* @return mixed |
16
|
|
|
*/ |
17
|
|
|
public function __invoke(Route $route, array $args = []) |
18
|
|
|
{ |
19
|
|
|
$endPoint = $this->getPoint($route); |
20
|
|
|
return call_user_func_array($endPoint, $args); |
21
|
|
|
} |
22
|
|
|
|
23
|
|
|
/** |
24
|
|
|
* @param Route $route |
25
|
|
|
* @return callable |
26
|
|
|
*/ |
27
|
|
|
protected function getPoint(Route $route) |
28
|
|
|
{ |
29
|
|
|
$matches = $route->getMatches(); |
30
|
|
|
$controller = $this->getControllerClass(); |
31
|
|
|
$this->checkController($controller); |
32
|
|
|
|
33
|
|
|
$controller = new $controller(); |
34
|
|
|
|
35
|
|
|
$action = $this->getAction($matches); |
36
|
|
|
$this->checkAction($controller, $action); |
37
|
|
|
|
38
|
|
|
return [$controller, $action]; |
39
|
|
|
} |
40
|
|
|
|
41
|
|
|
/** |
42
|
|
|
* @return string |
43
|
|
|
*/ |
44
|
|
|
protected function getControllerClass() : string |
45
|
|
|
{ |
46
|
|
|
return $this->controller; |
47
|
|
|
} |
48
|
|
|
|
49
|
|
|
/** |
50
|
|
|
* @param $controller |
51
|
|
|
* @throws \BadMethodCallException |
52
|
|
|
*/ |
53
|
|
|
protected function checkController($controller) |
54
|
|
|
{ |
55
|
|
|
if (!class_exists($controller)) { |
56
|
|
|
throw new \BadMethodCallException('Controller not found'); |
57
|
|
|
} |
58
|
|
|
} |
59
|
|
|
|
60
|
|
|
/** |
61
|
|
|
* @param $controller |
62
|
|
|
* @param string $action |
63
|
|
|
* @throws \BadMethodCallException |
64
|
|
|
*/ |
65
|
|
|
protected function checkAction($controller, $action) |
66
|
|
|
{ |
67
|
|
|
if (!method_exists($controller, $action)) { |
68
|
|
|
throw new \BadMethodCallException('Action not found'); |
69
|
|
|
} |
70
|
|
|
} |
71
|
|
|
|
72
|
|
|
/** |
73
|
|
|
* @param array $matches |
74
|
|
|
* @return string |
75
|
|
|
*/ |
76
|
|
|
protected function getAction(array $matches = []) : string |
77
|
|
|
{ |
78
|
|
|
return $matches['_action'] ?? $this->action ?? 'index'; |
79
|
|
|
} |
80
|
|
|
|
81
|
|
|
} |
82
|
|
|
|