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 | 9 | public function dispatch() |
|
22 | { |
||
23 | 9 | $verb = isset($_SERVER['REQUEST_METHOD']) ? strtolower($_SERVER['REQUEST_METHOD']) : 'get'; |
|
24 | 9 | list($controllerName, $action) = $this->getControllerAndAction(); |
|
25 | 9 | $controller = $this->projectNamespace . $this->controllerPackage . '\\' . ucfirst($controllerName); |
|
26 | 9 | if (!class_exists($controller)) { |
|
27 | 3 | throw new \Exception('controller ' . $controllerName . ' not found'); |
|
28 | }; |
||
29 | 6 | $controller = new $controller; |
|
30 | 6 | $finalAction = $verb . ucfirst($action) . $this->controllerActionSuffix; |
|
31 | 6 | if (is_callable(array($controller, $finalAction))) { |
|
32 | return $controller->$finalAction(); |
||
33 | } |
||
34 | 6 | $finalAction = $action . $this->controllerActionSuffix; |
|
35 | 6 | if (!is_callable(array($controller, $finalAction))) { |
|
36 | 1 | throw new \Exception('action ' . $finalAction . ' not found in controller ' . $controllerName); |
|
37 | } |
||
38 | 5 | return $controller->$finalAction(); |
|
39 | } |
||
40 | |||
41 | /** |
||
42 | * Determine controller and action from Request Uri |
||
43 | * @return array |
||
44 | */ |
||
45 | 9 | private function getControllerAndAction() : array |
|
46 | { |
||
47 | 9 | $requestUri = $_SERVER['REQUEST_URI']; |
|
48 | 9 | $appendUri = strpos($requestUri, '?'); |
|
49 | 9 | $query = substr($requestUri, 0, $appendUri === false ? strlen($requestUri) : $appendUri); |
|
50 | 9 | $parts = explode('/', preg_replace('~^' . Basepath::get() . '~', '', $query)); |
|
51 | 9 | $action = count($parts) >= 2 ? array_pop($parts) : 'index'; |
|
52 | 9 | $controllerName = isset($parts[0]) && $parts[0] ? implode($parts, '\\') : 'index'; |
|
53 | 9 | return [$controllerName, $action ?: 'index']; |
|
54 | } |
||
55 | |||
56 | /** |
||
57 | * Redefine personal namespace |
||
58 | * @param string $namespace |
||
59 | * @return Framework |
||
60 | */ |
||
61 | 3 | public function setNamespace(string $namespace = '\Project') : Framework |
|
66 | |||
67 | /** |
||
68 | * Redefine controller subpackage |
||
69 | * @param string $controllerPackage |
||
70 | * @return Framework |
||
71 | */ |
||
72 | 4 | public function setControllerPackage(string $controllerPackage = '\Controller') : Framework |
|
79 | |||
80 | /** |
||
81 | * Redefine controller action suffix |
||
82 | * @param string $suffix |
||
83 | * @return Framework |
||
84 | */ |
||
85 | 2 | public function setControllerActionSuffix(string $suffix = 'Action') : Framework |
|
90 | } |
||
91 |