Test Setup Failed
Push — master ( 5e2325...9a9998 )
by Php Easy Api
05:53
created

Route   A

Complexity

Total Complexity 37

Size/Duplication

Total Lines 343
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 109
dl 0
loc 343
rs 9.44
c 0
b 0
f 0
wmc 37

12 Methods

Rating   Name   Duplication   Size   Complexity  
A checkArrayEqual() 0 14 3
A getRouteControllerClass() 0 9 2
A updateRouteParameters() 0 20 4
A getRouteControllerNamespace() 0 9 2
A getRouteControllerMethod() 0 9 2
A getRouteResolve() 0 30 3
A setRoute() 0 17 1
A handle() 0 18 2
A isMatchVaribleRegexPattern() 0 5 2
B getRouteMappings() 0 52 6
B setPath() 0 29 8
A isOptionalVaribleRegexPattern() 0 5 2
1
<?php
2
3
namespace Resta\Router;
4
5
use Resta\Support\Str;
6
use Resta\Support\Utils;
7
use Resta\Foundation\PathManager\StaticPathList;
8
9
class Route extends RouteHttpManager
10
{
11
    // get route acccessible property
12
    use RouteAccessiblePropertyTrait;
13
14
    /**
15
     * @var array $endpoints
16
     */
17
    protected static $endpoints = [];
18
19
    /**
20
     * @var array $routes
21
     */
22
    protected static $routes = [];
23
24
    /**
25
     * @var array $paths
26
     */
27
    protected static $paths = [];
28
29
    /**
30
     * @var array $mappers
31
     */
32
    protected static $mappers = [];
33
34
    /**
35
     * @var null|string $namespace
36
     */
37
    protected static $namespace;
38
39
    /**
40
     * get route checkArrayEqual
41
     *
42
     * @param $patterns
43
     * @param $urlRoute
44
     * @return int|string
45
     */
46
    public static function checkArrayEqual($patterns,$urlRoute)
47
    {
48
        // calculates the equality difference between
49
        // the route pattern and the urlRoute value.
50
        foreach ($patterns as $key=>$pattern){
51
52
            if(Utils::isArrayEqual($pattern,$urlRoute)){
53
                return $key;
54
            }
55
        }
56
57
        // if the difference is not equal,
58
        // null is returned.
59
        return null;
60
    }
61
62
    /**
63
     * get route controller class
64
     *
65
     * @return string
66
     */
67
    public static function getRouteControllerClass()
68
    {
69
        $route = self::getRouteResolve();
70
71
        if(isset($route['class'])){
72
            return $route['class'];
73
        }
74
75
        return null;
76
    }
77
78
    /**
79
     * get route controller class
80
     *
81
     * @return string
82
     */
83
    public static function getRouteControllerMethod()
84
    {
85
        $route = self::getRouteResolve();
86
87
        if(isset($route['method'])){
88
            return $route['method'];
89
        }
90
91
        return null;
92
    }
93
94
    /**
95
     * get route controller namespace
96
     *
97
     * @return string
98
     */
99
    public static function getRouteControllerNamespace()
100
    {
101
        $route = self::getRouteResolve();
102
103
        if(isset($route['controller'],$route['namespace'])){
104
            return $route['controller'].'/'.$route['namespace'];
105
        }
106
107
        return null;
108
    }
109
110
    /**
111
     * get route getRouteResolve
112
     *
113
     * @return array
114
     */
115
    public static function getRouteResolve()
116
    {
117
        // get routes data and the resolving pattern
118
        // Both are interrelated.
119
        $routes = self::getRoutes();
120
        $patternResolve = app()->resolve(RouteMatching::class,['route'=>new self()])->getPatternResolve();
121
122
        // we set the route variables for the route assistant.
123
        self::updateRouteParameters($patternResolve);
124
125
        //if routes data is available in pattern resolve.
126
        if(isset($routes['data'][$patternResolve])){
127
128
            // if the incoming http value is
129
            // the same as the real request method, the data is processed.
130
            if($routes['data'][$patternResolve]['http'] == strtolower(httpMethod)){
131
132
                // we are set the solved pattern to a variable.
133
                $resolve = $routes['data'][$patternResolve];
134
135
                return [
136
                    'class'         => $resolve['class'],
137
                    'method'        => $resolve['method'],
138
                    'controller'    => $resolve['controller'],
139
                    'namespace'     => $resolve['namespace'],
140
                ];
141
            }
142
        }
143
144
        return [];
145
    }
146
147
    /**
148
     * update route parameters
149
     *
150
     * @param $patternResolvedKey
151
     * @return mixed|void
152
     */
153
    private static function updateRouteParameters($patternResolvedKey)
154
    {
155
        $list = [];
156
157
        if(isset(static::$routes['pattern'][$patternResolvedKey])){
158
159
            $routeParameters = static::$routes['pattern'][$patternResolvedKey];
160
            $route = route();
161
162
            foreach($routeParameters as $key=>$param){
163
164
                $param = Str::replaceWordArray(['{','}','?'],'',$param);
165
166
                if(isset($route[$key])){
167
                    $list[$param] = $route[$key];
168
                }
169
            }
170
        }
171
172
        app()->register('routeParams',$list);
173
    }
174
175
    /**
176
     * route handle for route application
177
     *
178
     * @param bool $endpoint
179
     */
180
    public function handle($endpoint=true)
181
    {
182
        // we will record the path data for the route.
183
        // We set the routeMapper variables and the route path.
184
        self::setPath(function(){
185
186
            // we are sending
187
            // the controller and routes.php path.
188
            return [
189
                'controllerPath'    => path()->controller(),
190
                'routePath'         => path()->route(),
191
            ];
192
        },$endpoint);
193
194
        // in the paths data,
195
        // we run the route mapper values ​​and the route files one by one.
196
        foreach (self::$paths as $mapper=>$controller){
197
            core()->fileSystem->callFile($mapper);
198
        }
199
    }
200
201
    /**
202
     * get route set path
203
     *
204
     * @param callable $callback
205
     * @param bool $endpoint
206
     */
207
    public static function setPath(callable $callback,$endpoint=true)
208
    {
209
        $routeDefinitor = call_user_func($callback);
210
211
        if(isset($routeDefinitor['controllerPath']) && isset($routeDefinitor['routePath'])){
212
213
            //the route paths to be saved to the mappers static property.
214
            static::$mappers['routePaths'][] = $routeDefinitor['routePath'];
215
            static::$mappers['controllerNamespaces'][] = Utils::getNamespace($routeDefinitor['controllerPath']);
216
217
            // if there is endpoint,
218
            // then only that endpoint is transferred into the path
219
            if(defined('endpoint') && $endpoint){
220
221
                $routeName      = endpoint.'Route.php';
222
                $routeMapper    = $routeDefinitor['routePath'].''.DIRECTORY_SEPARATOR.''.$routeName;
223
224
                if(file_exists($routeMapper) && !isset(static::$paths[$routeMapper])){
225
                    static::$paths[$routeMapper] = $routeDefinitor['controllerPath'];
226
                }
227
            }
228
            else{
229
230
                // if there is no endpoint,
231
                // all files in the path of the route are transferred to path.
232
                $allFilesInThatRoutePath = Utils::glob($routeDefinitor['routePath']);
233
234
                foreach ($allFilesInThatRoutePath as $item){
235
                    static::$paths[$item] = $routeDefinitor['controllerPath'];
236
                }
237
            }
238
        }
239
    }
240
241
    /**
242
     * get route setRoute method
243
     *
244
     * @param $params
245
     * @param $function
246
     * @param null $controller
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $controller is correct as it would always require null to be passed?
Loading history...
247
     */
248
    public static function setRoute($params,$function,$controller=null)
249
    {
250
        [$pattern,$route]   = $params;
251
        [$class,$method]    = explode("@",$route);
252
253
        $patternList = array_values(
254
            array_filter(explode("/",$pattern),'strlen')
255
        );
256
257
        static::$routes['pattern'][] = $patternList;
258
        static::$routes['data'][] = [
259
            'method'        => $method,
260
            'class'         => $class,
261
            'http'          => $function,
262
            'controller'    => $controller,
263
            'namespace'     => static::$namespace,
264
            'endpoint'      => strtolower(str_replace(StaticPathList::$controllerBundleName,'',static::$namespace))
265
        ];
266
    }
267
268
    /**
269
     * is route variable regex pattern
270
     *
271
     * @param null $value
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $value is correct as it would always require null to be passed?
Loading history...
272
     * @return bool
273
     */
274
    public static function isMatchVaribleRegexPattern($value=null)
275
    {
276
        // determines if the variable that can be used
277
        // in the route file meets the regex rule.
278
        return (preg_match('@\{(.*?)\}@is',$value)) ? true : false;
279
    }
280
281
282
    /**
283
     * is optional route variable regex pattern
284
     *
285
     * @param null $value
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $value is correct as it would always require null to be passed?
Loading history...
286
     * @return bool
287
     */
288
    public static function isOptionalVaribleRegexPattern($value=null)
289
    {
290
        // determines if the variable that can be used
291
        // in the route file meets the regex rule.
292
        return preg_match('@\{[a-z]+\?\}@is',$value) ? true : false;
293
    }
294
295
    /**
296
     * get route mappings
297
     *
298
     * @return array
299
     */
300
    public static function getRouteMappings()
301
    {
302
        (new self())->handle(false);
303
304
        $mappings = [];
305
        
306
        $routes = self::getRoutes();
307
        $routeData = isset($routes['data']) ? $routes['data'] : [];
308
        $routePattern = isset($routes['pattern']) ? $routes['pattern'] : [];
309
310
        $counter = 0;
0 ignored issues
show
Unused Code introduced by
The assignment to $counter is dead and can be removed.
Loading history...
311
312
        $application = app();
313
314
        $application->loadIfNotExistBoot(['middleware']);
315
        $middlewareProvider = $application['middleware'];
316
317
        foreach($routeData as $key=>$data) {
318
319
            $middlewareProvider->setKeyOdds('endpoint', $data['endpoint']);
320
            $middlewareProvider->setKeyOdds('method', $data['method']);
321
            $middlewareProvider->setKeyOdds('http', $data['http']);
322
323
            $middlewareProvider->handleMiddlewareProcess();
324
            $beforeMiddleware = $middlewareProvider->getShow();
325
326
            $middlewareProvider->handleMiddlewareProcess('after');
327
            $afterMiddleware = $middlewareProvider->getShow();
328
329
            $endpoint = $data['endpoint'];
330
            $controllerNamespace = Utils::getNamespace($data['controller'] . '/' . $data['namespace'] . '/' . $data['class']);
331
332
            $methodDocument = app()['reflection']($controllerNamespace)->reflectionMethodParams($data['method'])->document;
333
334
            $methodDefinition = '';
335
336
            if (preg_match('@#define:(.*?)\n@is', $methodDocument, $definition)) {
337
                if (isset($definition[1])) {
338
                    $methodDefinition = rtrim($definition[1]);
339
                }
340
            }
341
342
            $mappings[$key]['endpoint'] = $endpoint . '/' . implode("/", $routePattern[$key]);
343
            $mappings[$key]['http'] = $data['http'];
344
            $mappings[$key]['definition'] = $methodDefinition;
345
            $mappings[$key]['before'] = implode(",",$beforeMiddleware);
346
            $mappings[$key]['after'] = implode(",",$afterMiddleware);
347
            $mappings[$key]['doc'] = 'not available';
348
349
        }
350
        
351
        return $mappings;
352
    }
353
354
355
}