Test Setup Failed
Push — master ( 864b82...1de887 )
by Php Easy Api
04:11
created

Route::setRoute()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 17
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 12
nc 1
nop 3
dl 0
loc 17
rs 9.8666
c 0
b 0
f 0
1
<?php
2
3
namespace Resta\Router;
4
5
use Resta\Foundation\PathManager\StaticPathList;
6
use Resta\Support\Arr;
7
use Resta\Support\Utils;
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 $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
    private 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
     * matching url method
64
     *
65
     * @param $patterns
66
     * @param $urlMethod
67
     * @return array
68
     */
69
    private static function matchingUrlMethod($patterns,$urlMethod)
70
    {
71
        if(isset($urlMethod[0])){
72
73
            $list = [];
74
75
            foreach ($patterns as $key=>$pattern){
76
                if(isset($pattern[0])){
77
                    if($pattern[0] !== $urlMethod[0] && !self::isMatchVaribleRegexPattern($pattern[0])){
78
                        $list[$key] = [];
79
                    }
80
                }
81
82
                if(!isset($list[$key])){
83
                    $list[$key] = $pattern;
84
                }
85
86
                if(isset($pattern[0]) && $pattern[0]==$urlMethod[0]){
87
88
                    if(isset($list[$key-1],$list[$key-1][0]) && $list[$key-1][0]!==$urlMethod[0]){
89
                        unset($list[$key-1]);
90
                    }
91
92
                    $list[$key] = $pattern;
93
                }
94
            }
95
96
            $patterns = $list;
97
        }
98
99
        return $patterns;
100
    }
101
102
    /**
103
     * get route getPatternResolve
104
     *
105
     * @return array|int|string
106
     */
107
    private static function getPatternResolve()
108
    {
109
        $routes = self::getRoutes();
110
111
        if(!isset($routes['pattern'])){
112
            return [];
113
        }
114
115
        $patterns = $routes['pattern'];
116
        $urlRoute = array_filter(route(),'strlen');
117
118
        $patternList = [];
119
120
        foreach($routes['data'] as $patternKey=>$routeData){
121
            if($routeData['http']==httpMethod()){
122
                $patternList[$patternKey]=$patterns[$patternKey];
123
            }
124
        }
125
126
        $patternList = self::matchingUrlMethod($patternList,$urlRoute);
127
128
        foreach ($patternList as $key=>$pattern){
129
130
            $pattern = array_filter($pattern,'strlen');
131
            $diff = Arr::arrayDiffKey($pattern,$urlRoute);
132
133
            if($diff){
134
135
                $matches = true;
136
137
                foreach ($pattern as $patternKey=>$patternValue){
138
                    if(!self::isMatchVaribleRegexPattern($patternValue)){
139
                        if($patternValue!==$urlRoute[$patternKey]){
140
                            $matches = false;
141
                        }
142
                    }
143
                }
144
145
                if($matches){
146
147
                    $isArrayEqual = self::checkArrayEqual($patternList,$urlRoute);
148
149
                    if($isArrayEqual===null){
150
                        return $key;
151
                    }
152
                    return $isArrayEqual;
153
                }
154
            }
155
156
            if(count($pattern)-1 == count(route())){
157
                if(preg_match('@\{[a-z]+\?\}@is',end($pattern))){
158
                    return $key;
159
                }
160
            }
161
        }
162
    }
163
164
    /**
165
     * get route getRouteResolve
166
     *
167
     * @return array
168
     */
169
    public static function getRouteResolve()
170
    {
171
        // get routes data and the resolving pattern
172
        // Both are interrelated.
173
        $routes         = self::getRoutes();
174
        $patternResolve = self::getPatternResolve();
175
176
        //if routes data is available in pattern resolve.
177
        if(isset($routes['data'][$patternResolve])){
178
179
            // if the incoming http value is
180
            // the same as the real request method, the data is processed.
181
            if($routes['data'][$patternResolve]['http'] == strtolower(httpMethod)){
182
183
                // we are set the solved pattern to a variable.
184
                $resolve = $routes['data'][$patternResolve];
185
186
                return [
187
                    'class'         => $resolve['class'],
188
                    'method'        => $resolve['method'],
189
                    'controller'    => $resolve['controller'],
190
                    'namespace'     => $resolve['namespace'],
191
                ];
192
            }
193
        }
194
        return [];
195
    }
196
197
    /**
198
     * route handle for route application
199
     *
200
     * @return void|mixed
201
     */
202
    public function handle()
203
    {
204
        // we will record the path data for the route.
205
        // We set the routeMapper variables and the route path.
206
        self::setPath(function(){
207
208
            // we are sending
209
            // the controller and routes.php path.
210
            return [
211
                'controllerPath'    => path()->controller(),
212
                'routePath'         => path()->route(),
213
            ];
214
        });
215
216
        // in the paths data,
217
        // we run the route mapper values ​​and the route files one by one.
218
        foreach (self::$paths as $mapper=>$controller){
219
            core()->fileSystem->callFile($mapper);
220
        }
221
    }
222
223
    /**
224
     * get route setPath method
225
     *
226
     * @param $path
227
     */
228
    public static function setPath(callable $callback)
229
    {
230
        $routeDefinitor = call_user_func($callback);
231
232
        if(isset($routeDefinitor['controllerPath']) && isset($routeDefinitor['routePath'])){
233
234
            //the route paths to be saved to the mappers static property.
235
            static::$mappers['routePaths'][] = $routeDefinitor['routePath'];
236
            static::$mappers['controllerNamespaces'][] = Utils::getNamespace($routeDefinitor['controllerPath']);
237
238
            // if there is endpoint,
239
            // then only that endpoint is transferred into the path
240
            if(defined('endpoint')){
241
242
                $routeName      = endpoint.'Route.php';
243
                $routeMapper    = $routeDefinitor['routePath'].''.DIRECTORY_SEPARATOR.''.$routeName;
244
245
                if(file_exists($routeMapper) && !isset(static::$paths[$routeMapper])){
246
                    static::$paths[$routeMapper] = $routeDefinitor['controllerPath'];
247
                }
248
            }
249
            else{
250
251
                // if there is no endpoint,
252
                // all files in the path of the route are transferred to path.
253
                $allFilesInThatRoutePath = Utils::glob($routeDefinitor['routePath']);
254
255
                foreach ($allFilesInThatRoutePath as $item){
256
                    static::$paths[$item] = $routeDefinitor['controllerPath'];
257
                }
258
            }
259
        }
260
    }
261
262
    /**
263
     * get route setRoute method
264
     *
265
     * @param $params
266
     * @param $function
267
     * @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...
268
     */
269
    public static function setRoute($params,$function,$controller=null)
270
    {
271
        [$pattern,$route]   = $params;
272
        [$class,$method]    = explode("@",$route);
273
274
        $patternList = array_values(
275
            array_filter(explode("/",$pattern),'strlen')
276
        );
277
278
        static::$routes['pattern'][] = $patternList;
279
        static::$routes['data'][] = [
280
            'method'        => $method,
281
            'class'         => $class,
282
            'http'          => $function,
283
            'controller'    => $controller,
284
            'namespace'     => static::$namespace,
285
            'endpoint'      => strtolower(str_replace(StaticPathList::$controllerBundleName,'',static::$namespace))
286
        ];
287
    }
288
289
    /**
290
     * is matc variable regex pattern
291
     *
292
     * @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...
293
     * @return bool
294
     */
295
    public static function isMatchVaribleRegexPattern($value=null)
296
    {
297
        if(preg_match('@\{(.*?)\}@is',$value)){
298
            return true;
299
        }
300
301
        return false;
302
    }
303
}