Procházet zdrojové kódy

added injection to middleware

develop
Robin Thoni před 8 roky
rodič
revize
c36af0947e

+ 106
- 0
src/Utils/Business/LuInjector.php Zobrazit soubor

@@ -0,0 +1,106 @@
1
+<?php
2
+/**
3
+ * Created by PhpStorm.
4
+ * User: robin
5
+ * Date: 7/1/16
6
+ * Time: 10:17 PM
7
+ */
8
+
9
+namespace Luticate\Utils\Business;
10
+
11
+
12
+use Luticate\Utils\Dbo\LuDbo;
13
+use Luticate\Utils\Dbo\LuDboConstraintException;
14
+use Luticate\Utils\Dbo\LuDboDeserializeException;
15
+
16
+class LuInjector
17
+{
18
+    public static function inject($obj, string $methodName, array $parameters)
19
+    {
20
+        if (is_string($obj)) {
21
+            $className = $obj;
22
+            $objInstance = new $className();
23
+        }
24
+        else {
25
+            $className = get_class($obj);
26
+            $objInstance = $obj;
27
+        }
28
+        $reflect = new \ReflectionMethod($className, $methodName);
29
+        $params = $reflect->getParameters();
30
+        $docs = new LuMethodDocParser($reflect->getDocComment());
31
+        $docs->parse();
32
+
33
+        $args = [];
34
+        foreach ($params as $param) {
35
+
36
+            try {
37
+                $value = null;
38
+                if (array_key_exists($param->getName(), $parameters)) {
39
+                    $value = static::getParam($param, $parameters[$param->getName()]);
40
+                }
41
+                else if ($param->isOptional()) {
42
+                    $value = $param->getDefaultValue();
43
+                }
44
+                else {
45
+                    throw new LuDboDeserializeException("Missing parameter '" . $param->getName() . "'", 400);
46
+                }
47
+
48
+                if (array_key_exists($param->getName(), $docs->getParams())) {
49
+                    $doc = $docs->getParams()[$param->getName()];
50
+                    if (is_null($value) && $doc->isNotNull()) {
51
+                        throw new LuDboConstraintException("Parameter '" . $param->getName() . "' can not be null", 400);
52
+                    }
53
+
54
+                    if (!is_null($value)) {
55
+                        $value->checkConstraints($doc->getConstraints());
56
+                    }
57
+                }
58
+                $args[$param->getName()] = $value;
59
+            }
60
+            catch (LuDboConstraintException $e)
61
+            {
62
+                $paramName = $param->getName();
63
+                throw new LuBusinessException("Invalid value for '${paramName}': " . $e->getMessage(), 400, $e);
64
+            }
65
+            catch (LuDboDeserializeException $e)
66
+            {
67
+                $paramName = $param->getName();
68
+                throw new LuBusinessException("Failed to deserialize '${paramName}': " . $e->getMessage(), 400, $e);
69
+            }
70
+        }
71
+
72
+        $result = call_user_func_array(array($objInstance, $methodName), $args);
73
+        return $result;
74
+    }
75
+
76
+    public static function getClassName(\ReflectionParameter $param) {
77
+        preg_match('/\[\s\<\w+?>\s([\w]+)/s', $param->__toString(), $matches);
78
+        return isset($matches[1]) ? $matches[1] : null;
79
+    }
80
+
81
+    public static function getParam(\ReflectionParameter $param, $value)
82
+    {
83
+        $typedValue = null;
84
+        $className = static::getClassName($param);
85
+        if (is_null($className)) {
86
+            $typedValue = $value;
87
+        }
88
+        else {
89
+            $class = $param->getClass();
90
+            $className = is_null($class) ? "string" : $class->getName();
91
+            try
92
+            {
93
+                $json = json_decode($value, true);
94
+                $typedValue = LuDbo::deserializeValue($json, $className);
95
+            }
96
+            catch (\Exception $e)
97
+            {
98
+                if ($e instanceof LuDboDeserializeException || $e instanceof LuDboConstraintException) {
99
+                    throw $e;
100
+                }
101
+                throw new LuBusinessException("Unable to parse JSON value for '" . $param->getName() . "'", 400, $e);
102
+            }
103
+        }
104
+        return $typedValue;
105
+    }
106
+}

+ 21
- 94
src/Utils/Controller/LuRoute.php Zobrazit soubor

@@ -4,6 +4,7 @@ namespace Luticate\Utils\Controller;
4 4
 
5 5
 use FastRoute\Dispatcher;
6 6
 use Luticate\Utils\Business\LuBusinessException;
7
+use Luticate\Utils\Business\LuInjector;
7 8
 use Luticate\Utils\Business\LuMethodDocParser;
8 9
 use Luticate\Utils\Dbo\LuDboConstraintException;
9 10
 use Luticate\Utils\Dbo\LuDboDeserializeException;
@@ -83,86 +84,42 @@ class LuRoute {
83 84
          * @var $middlewareDbo LuMiddlewareDbo
84 85
          */
85 86
         foreach (array_merge($this->_middlewares, $route->getMiddlewares()) as $middlewareDbo) {
86
-            $middlewareName = $middlewareDbo->getMiddleware();
87 87
             /**
88 88
              * @var $middleware LuAbstractMiddleware
89 89
              */
90
+            $middlewareName = $middlewareDbo->getMiddleware();
90 91
             $middleware = new $middlewareName();
91
-            $parameters["_middleware"] = $middlewareDbo->getParameters();
92
-            foreach ($route->getParameters() as $key => $value) {
93
-                $parameters["_middleware"][$key] = $value;
92
+
93
+            $args = array_merge($middlewareDbo->getParameters(), $route->getParameters());
94
+            $args["_route"] = $route;
95
+            $args["_parameters"] = $parameters;
96
+            $args["_all"] = $args;
97
+
98
+            if (is_callable([$middleware, "onBefore"])) {
99
+                $parameters = LuInjector::inject($middleware, "onBefore", $args);
94 100
             }
95
-            $parameters = $middleware->onBefore($route, $parameters);
101
+
96 102
             $middlewares[] = [
97 103
                 'middleware' => $middleware,
98 104
                 'dbo' => $middlewareDbo
99 105
             ];
100 106
         }
101
-        unset($parameters["_middleware"]);
102
-
103
-        $reflect = new \ReflectionMethod($route->getController(), $route->getAction());
104
-        $params = $reflect->getParameters();
105
-        $docs = new LuMethodDocParser($reflect->getDocComment());
106
-        $docs->parse();
107
-
108
-        $args = array();
109
-        foreach ($params as $param) {
110
-
111
-            try {
112
-                if ($param->isOptional()) {
113
-                    $value = null;
114
-                    if (array_key_exists($param->getName(), $parameters)) {
115
-                        $value = $this->getParam($param, $parameters[$param->getName()]);
116
-                    }
117
-                    else {
118
-                        $value = $param->getDefaultValue();
119
-                    }
120
-                }
121
-                else {
122
-                    if (array_key_exists($param->getName(), $parameters)) {
123
-                        $value = $this->getParam($param, $parameters[$param->getName()]);
124
-                    }
125
-                    else {
126
-                        throw new LuDboDeserializeException("Missing parameter '" . $param->getName() . "'", 400);
127
-                    }
128
-                }
129 107
 
130
-                if (array_key_exists($param->getName(), $docs->getParams())) {
131
-                    $doc = $docs->getParams()[$param->getName()];
132
-                    if (is_null($value) && $doc->isNotNull()) {
133
-                        throw new LuDboConstraintException("Parameter '" . $param->getName() . "' can not be null", 400);
134
-                    }
135
-
136
-                    if (!is_null($value)) {
137
-                        $value->checkConstraints($doc->getConstraints());
138
-                    }
139
-                }
140
-                $args[$param->getName()] = $value;
141
-            }
142
-            catch (LuDboConstraintException $e)
143
-            {
144
-                $paramName = $param->getName();
145
-                throw new LuBusinessException("Invalid value for '${paramName}': " . $e->getMessage(), 400, $e);
146
-            }
147
-            catch (LuDboDeserializeException $e)
148
-            {
149
-                $paramName = $param->getName();
150
-                throw new LuBusinessException("Failed to deserialize '${paramName}': " . $e->getMessage(), 400, $e);
151
-            }
152
-        }
153
-
154
-        $controller = $route->getController();
155
-        $controllerInstance = new $controller();
156
-        $result = call_user_func_array(array($controllerInstance, $route->getAction()), $args);
108
+        $result = LuInjector::inject($route->getController(), $route->getAction(), $parameters);
157 109
 
158 110
         foreach ($middlewares as $middlewareArray) {
159 111
             $middleware = $middlewareArray['middleware'];
160 112
             $middlewareDbo = $middlewareArray['dbo'];
161
-            $parameters["_middleware"] = $middlewareDbo->getParameters();
162
-            foreach ($route->getParameters() as $key => $value) {
163
-                $parameters["_middleware"][$key] = $value;
113
+
114
+            $args = array_merge($middlewareDbo->getParameters(), $route->getParameters());
115
+            $args["_route"] = $route;
116
+            $args["_parameters"] = $parameters;
117
+            $args["_result"] = $result;
118
+            $args["_all"] = $args;
119
+
120
+            if (is_callable([$middleware, "onAfter"])) {
121
+                $result = LuInjector::inject($middleware, "onAfter", $args);
164 122
             }
165
-            $result = $middleware->onAfter($route, $parameters, $result);
166 123
         }
167 124
 
168 125
         return $result;
@@ -186,36 +143,6 @@ class LuRoute {
186 143
         }
187 144
     }
188 145
     
189
-    private function getClassName(\ReflectionParameter $param) {
190
-        preg_match('/\[\s\<\w+?>\s([\w]+)/s', $param->__toString(), $matches);
191
-        return isset($matches[1]) ? $matches[1] : null;
192
-    }
193
-
194
-    private function getParam(\ReflectionParameter $param, $value)
195
-    {
196
-        $typedValue = null;
197
-        $className = $this->getClassName($param);
198
-        if (is_null($className)) {
199
-            $typedValue = $value;
200
-        }
201
-        else {
202
-            $class = $param->getClass();
203
-            try
204
-            {
205
-                $json = json_decode($value, true);
206
-                $typedValue = call_user_func_array(array($class->getName(), "jsonDeserialize"), array($json));
207
-            }
208
-            catch (\Exception $e)
209
-            {
210
-                if ($e instanceof LuDboDeserializeException || $e instanceof LuDboConstraintException) {
211
-                    throw $e;
212
-                }
213
-                throw new LuBusinessException("Unable to parse JSON value for '" . $param->getName() . "'", 400, $e);
214
-            }
215
-        }
216
-        return $typedValue;
217
-    }
218
-    
219 146
     public function addRoute2(LuRouteDbo $route) {
220 147
         $controller = $route->getController();
221 148
         if (strpos($controller, "\\") === false) {

+ 4
- 5
src/Utils/Middleware/LuAbstractMiddleware.php Zobrazit soubor

@@ -10,14 +10,13 @@ namespace Luticate\Utils\Middleware;
10 10
 
11 11
 use Luticate\Utils\Dbo\LuRouteDbo;
12 12
 
13
-abstract class LuAbstractMiddleware
13
+interface LuAbstractMiddleware
14 14
 {
15 15
     /**
16
-     * @param LuRouteDbo $route The route being executed
17
-     * @param $parameters array The request parameters
16
+     * @param $parameters array The injected parameters
18 17
      * @return mixed The requests parameters
19 18
      */
20
-    public abstract function onBefore(LuRouteDbo $route, $parameters);
19
+//    public function onBefore(...$parameters);
21 20
 
22 21
     /**
23 22
      * @param LuRouteDbo $route The route being executed
@@ -25,5 +24,5 @@ abstract class LuAbstractMiddleware
25 24
      * @param $result mixed The request result
26 25
      * @return mixed The request result
27 26
      */
28
-    public abstract function onAfter(LuRouteDbo $route, $parameters, $result);
27
+//    public function onAfter(LuRouteDbo $route, $parameters, $result);
29 28
 }

+ 9
- 25
tests/LuRouteTest.php Zobrazit soubor

@@ -60,47 +60,31 @@ class BasicTestController
60 60
     }
61 61
 }
62 62
 
63
-class BeforeMiddleware extends LuAbstractMiddleware {
63
+class BeforeMiddleware implements LuAbstractMiddleware {
64 64
 
65
-    public function onBefore(LuRouteDbo $route, $parameters)
65
+    public function onBefore($_parameters)
66 66
     {
67
-        $parameters["_user"] = "\"my user\"";
68
-        return $parameters;
69
-    }
70
-
71
-    public function onAfter(LuRouteDbo $route, $parameters, $result)
72
-    {
73
-        return $result;
67
+        $_parameters["_user"] = "\"my user\"";
68
+        return $_parameters;
74 69
     }
75 70
 }
76 71
 
77
-class AfterMiddleware extends LuAbstractMiddleware {
72
+class AfterMiddleware implements LuAbstractMiddleware {
78 73
 
79
-    public function onBefore(LuRouteDbo $route, $parameters)
80
-    {
81
-        return $parameters;
82
-    }
83
-
84
-    public function onAfter(LuRouteDbo $route, $parameters, $result)
74
+    public function onAfter()
85 75
     {
86 76
         return "AfterMiddleware";
87 77
     }
88 78
 }
89 79
 
90
-class AuthenticationMiddleware extends LuAbstractMiddleware {
80
+class AuthenticationMiddleware implements LuAbstractMiddleware {
91 81
 
92
-    public function onBefore(LuRouteDbo $route, $parameters)
82
+    public function onBefore($_parameters, $permissions = [])
93 83
     {
94
-        $permissions = $parameters['_middleware']['permissions'] ?? [];
95 84
         if ($permissions[0] != "ALLOWED") {
96 85
             throw new LuBusinessException("Unauthorized", 401);
97 86
         }
98
-        return $parameters;
99
-    }
100
-
101
-    public function onAfter(LuRouteDbo $route, $parameters, $result)
102
-    {
103
-        return $result;
87
+        return $_parameters;
104 88
     }
105 89
 }
106 90
 

Načítá se…
Zrušit
Uložit