@@ -20,22 +20,53 @@ final class Framework
20
20
*/
21
21
public function dispatch ()
22
22
{
23
- $ requestUri = $ _SERVER ['REQUEST_URI ' ];
24
- $ appendUri = strpos ($ requestUri , '? ' );
25
- $ query = substr ($ requestUri , 0 , $ appendUri === false ? strlen ($ requestUri ) : $ appendUri );
26
- $ parts = explode ('/ ' , preg_replace ('~^ ' . Basepath::get () . '~ ' , '' , $ query ));
27
- $ action = count ($ parts ) >= 2 ? array_pop ($ parts ) : 'index ' ;
28
- $ controllerName = isset ($ parts [0 ]) && $ parts [0 ] ? implode ($ parts , '\\' ) : 'index ' ;
23
+ list ($ controllerName , $ action ) = $ this ->getControllerAndAction ();
29
24
$ controller = $ this ->projectNamespace . $ this ->controllerPackage . '\\' . ucfirst ($ controllerName );
30
25
if (!class_exists ($ controller )) {
31
26
throw new \Exception ('controller ' . $ controllerName . ' not found ' );
32
27
};
33
28
$ controller = new $ controller ;
34
- $ action = ($ action ?: 'index ' ) . $ this ->controllerActionSuffix ;
35
- if (!is_callable (array ($ controller , $ action ))) {
36
- throw new \Exception ('action ' . $ action . ' not found in controller ' . $ controllerName );
29
+ $ finalAction = $ this ->getVerbFromRequest () . ucfirst ($ action ) . $ this ->controllerActionSuffix ;
30
+ if (is_callable (array ($ controller , $ finalAction ))) {
31
+ return $ controller ->$ finalAction ();
32
+ }
33
+ $ finalAction = $ action . $ this ->controllerActionSuffix ;
34
+ if (!is_callable (array ($ controller , $ finalAction ))) {
35
+ throw new \Exception ('action ' . $ finalAction . ' not found in controller ' . $ controllerName );
37
36
}
38
- return $ controller ->$ action ();
37
+ return $ controller ->$ finalAction ();
38
+ }
39
+
40
+ /**
41
+ * Return HTTP Method for request
42
+ * @return string
43
+ */
44
+ private function getVerbFromRequest ()
45
+ {
46
+ return isset ($ _SERVER ['REQUEST_METHOD ' ]) ? strtolower ($ _SERVER ['REQUEST_METHOD ' ]) : 'get ' ;
47
+ }
48
+
49
+ /**
50
+ * Returns Request uri without query string
51
+ * @return string
52
+ */
53
+ private function getQuery () : string
54
+ {
55
+ $ requestUri = $ _SERVER ['REQUEST_URI ' ];
56
+ $ appendUri = strpos ($ requestUri , '? ' );
57
+ return substr ($ requestUri , 0 , $ appendUri === false ? strlen ($ requestUri ) : $ appendUri );
58
+ }
59
+
60
+ /**
61
+ * Determine controller and action from Request Uri
62
+ * @return array
63
+ */
64
+ private function getControllerAndAction () : array
65
+ {
66
+ $ parts = explode ('/ ' , preg_replace ('~^ ' . Basepath::get () . '~ ' , '' , $ this ->getQuery ()));
67
+ $ action = count ($ parts ) >= 2 ? array_pop ($ parts ) : 'index ' ;
68
+ $ controllerName = isset ($ parts [0 ]) && $ parts [0 ] ? implode ($ parts , '\\' ) : 'index ' ;
69
+ return [$ controllerName , $ action ?: 'index ' ];
39
70
}
40
71
41
72
/**
0 commit comments