1 | <?php |
||
10 | final class Framework |
||
11 | { |
||
12 | private $projectNamespace = '\Project'; |
||
13 | private $controllerPackage = '\Controller'; |
||
14 | private $controllerActionSuffix = 'Action'; |
||
15 | |||
16 | /** |
||
17 | * Dispatch the request |
||
18 | * @throws \Exception |
||
19 | * @return mixed |
||
20 | */ |
||
21 | 10 | public function dispatch() |
|
22 | { |
||
23 | 10 | list($controllerName, $action) = $this->getControllerAndAction(); |
|
24 | 10 | $controller = $this->projectNamespace . $this->controllerPackage . '\\' . ucfirst($controllerName); |
|
25 | 10 | if (!class_exists($controller)) { |
|
26 | 3 | throw new \Exception('controller ' . $controllerName . ' not found'); |
|
27 | }; |
||
28 | 7 | $controller = new $controller; |
|
29 | 7 | $finalAction = $this->getVerbFromRequest() . ucfirst($action) . $this->controllerActionSuffix; |
|
30 | 7 | if (is_callable(array($controller, $finalAction))) { |
|
31 | 1 | return $controller->$finalAction(); |
|
32 | } |
||
33 | 6 | $finalAction = $action . $this->controllerActionSuffix; |
|
34 | 6 | if (!is_callable(array($controller, $finalAction))) { |
|
35 | 1 | throw new \Exception('action ' . $finalAction . ' not found in controller ' . $controllerName); |
|
36 | } |
||
37 | 5 | return $controller->$finalAction(); |
|
38 | } |
||
39 | |||
40 | /** |
||
41 | * Return HTTP Method for request |
||
42 | * @return string |
||
43 | */ |
||
44 | 7 | private function getVerbFromRequest() |
|
48 | |||
49 | /** |
||
50 | * Returns Request uri without query string |
||
51 | * @return string |
||
52 | */ |
||
53 | 10 | private function getQuery() : string |
|
59 | |||
60 | /** |
||
61 | * Determine controller and action from Request Uri |
||
62 | * @return array |
||
63 | */ |
||
64 | 10 | private function getControllerAndAction() : array |
|
71 | |||
72 | /** |
||
73 | * Redefine personal namespace |
||
74 | * @param string $namespace |
||
75 | * @return Framework |
||
76 | */ |
||
77 | 4 | public function setNamespace(string $namespace = '\Project') : Framework |
|
82 | |||
83 | /** |
||
84 | * Redefine controller subpackage |
||
85 | * @param string $controllerPackage |
||
86 | * @return Framework |
||
87 | */ |
||
88 | 5 | public function setControllerPackage(string $controllerPackage = '\Controller') : Framework |
|
95 | |||
96 | /** |
||
97 | * Redefine controller action suffix |
||
98 | * @param string $suffix |
||
99 | * @return Framework |
||
100 | */ |
||
101 | 3 | public function setControllerActionSuffix(string $suffix = 'Action') : Framework |
|
106 | } |
||
107 |