Test Failed
Push — master ( afae9d...56ac77 )
by Php Easy Api
04:28
created

MiddlewareProvider::specificMiddlewareCondition()   A

Complexity

Conditions 5
Paths 4

Size

Total Lines 26
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 5
eloc 7
nc 4
nop 1
dl 0
loc 26
rs 9.6111
c 0
b 0
f 0
1
<?php
2
3
namespace Resta\Middleware;
4
5
use Resta\Router\Route;
6
use Resta\Support\Utils;
7
use Resta\Contracts\HandleContracts;
8
use Resta\Foundation\ApplicationProvider;
9
use Resta\Support\AppData\ServiceMiddlewareManager;
10
use Resta\Contracts\ServiceMiddlewareManagerContracts;
11
12
class MiddlewareProvider extends ApplicationProvider implements HandleContracts
13
{
14
    /**
15
     * @var array $odds
16
     */
17
    protected $odds = [];
18
19
    /**
20
     * @var array $show
21
     */
22
    protected $show = [];
23
24
    /**
25
     * @var array $middleware
26
     */
27
    protected $middleware = [];
28
29
    /**
30
     * @var $serviceMiddleware
0 ignored issues
show
Documentation Bug introduced by
The doc comment $serviceMiddleware at position 0 could not be parsed: Unknown type name '$serviceMiddleware' at position 0 in $serviceMiddleware.
Loading history...
31
     */
32
    protected $serviceMiddleware;
33
34
    /**
35
     * after middleware
36
     *
37
     * @return void|mixed
38
     */
39
    public function after()
40
    {
41
        //middleware handle process
42
        $this->handleMiddlewareProcess('after');
43
    }
44
45
    /**
46
     * check namespace and specificCondition
47
     *
48
     * @return bool
49
     */
50
    private function checkNamespaceAndSpecificCondition()
51
    {
52
        return Utils::isNamespaceExists($this->middleware['namespace'])
53
            && $this->specificMiddlewareCondition($this->middleware['key']);
54
    }
55
56
    /**
57
     * get resolve service middleware
58
     *
59
     * @return mixed
60
     */
61
    public function getResolveServiceMiddleware()
62
    {
63
        if(!is_null($this->serviceMiddleware)){
64
            return $this->app->resolve($this->serviceMiddleware);
65
        }
66
67
        return $this->app['middlewareClass'];
68
    }
69
70
    /**
71
     * get assigned service middleware
72
     *
73
     * @return mixed
74
     */
75
    public function getServiceMiddleware()
76
    {
77
        return $this->serviceMiddleware;
78
    }
79
80
    /**
81
     * get show data for middleware
82
     *
83
     * @return array
84
     */
85
    public function getShow()
86
    {
87
        return $this->show;
88
    }
89
90
    /**
91
     * application middleware handle
92
     *
93
     * @return void
94
     */
95
    public function handle()
96
    {
97
        //set define for middleware
98
        define('middleware',true);
99
100
        //middleware handle process
101
        $this->handleMiddlewareProcess();
102
    }
103
104
    /**
105
     * handle middleware process
106
     *
107
     * @param string $method
108
     * @return void|mixed
109
     */
110
    public function handleMiddlewareProcess($method='handle')
111
    {
112
        // the app instance is a global application example,
113
        // and a hash is loaded as this hash.
114
        $this->setMiddleware();
115
116
        // the middleware class must be subject to
117
        // the ServiceMiddlewareManagerContracts interface rule to be implemented.
118
        if(!$this->getResolveServiceMiddleware() instanceof ServiceMiddlewareManagerContracts){
119
            exception()->badMethodCall('Service middleware does not have ServiceMiddlewareManagerContracts');
120
        }
121
122
        //When your application is requested, the middleware classes are running before all bootstrapper executables.
123
        //Thus, if you make http request your application, you can verify with an intermediate middleware layer
124
        //and throw an exception.
125
        $resolveServiceMiddleware = $this->getResolveServiceMiddleware()->{$method}();
126
        return $this->serviceMiddleware($resolveServiceMiddleware);
0 ignored issues
show
Bug introduced by
Are you sure the usage of $this->serviceMiddleware...solveServiceMiddleware) targeting Resta\Middleware\Middlew...er::serviceMiddleware() seems to always return null.

This check looks for function or method calls that always return null and whose return value is used.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
if ($a->getObject()) {

The method getObject() can return nothing but null, so it makes no sense to use the return value.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
127
    }
128
129
    /**
130
     * middleware key odds
131
     *
132
     * @param $key null
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $$key is correct as it would always require null to be passed?
Loading history...
133
     * @return array
134
     */
135
    public function middlewareKeyOdds($key=null)
136
    {
137
        $route = Route::getRouteResolve();
138
139
        $endpoint = (isset($route['namespace']))
140
            ? $route['namespace']
141
            : (defined('endpoint')) ? endpoint : null;
142
143
        $method = (isset($route['method']))
144
            ? $route['method'] :
145
            ($this->app->has('routeParameters')) ? implode("/",$this->app['routeParameters']) : '';
146
147
        $http = (isset($route['http']))
148
            ? $route['http'] :
149
            ($this->app->has('httpMethod')) ? $this->app['httpMethod'] : null ;
150
151
        // identifying constants for the middleware layer.
152
        // with the property of the user, the user is free to determine the constants that the middleware layer wants.
153
        $method     = $this->odds['method'] ?? $method;
154
        $endpoint   = $this->odds['endpoint'] ?? $endpoint;
155
        $http       = $this->odds['http'] ?? $http;
156
157
        //method can only return fixed.
158
        if(!is_null($key)){
159
            if(isset($$key)) return $$key;
160
        }
161
162
        //middleware key odds
163
        return [
164
            strtolower($endpoint),
165
            strtolower($endpoint).'@'.strtolower($http),
166
            strtolower($endpoint).'@'.strtolower($http).'@'.strtolower($method),
167
            strtolower($endpoint).'@'.strtolower($method),
168
            strtolower($endpoint).'@'.strtolower($method).'@'.strtolower($http)
169
        ];
170
    }
171
172
    /**
173
     * service middleware
174
     *
175
     * @param array $middleware
176
     */
177
    public function serviceMiddleware($middleware=array())
178
    {
179
        $this->show = [];
180
181
        //It will be run individually according to the rules of
182
        //the middleware classes specified for the service middleware middleware.
183
        foreach($middleware as $middleVal=>$middleKey){
184
185
            // if the keys in the array in the service middleware class represent a class,
186
            // this value is checked, if it does not represent the class,
187
            // it is detected as a short name and is searched in the middleware directory.
188
            if(Utils::isNamespaceExists($middleVal)){
189
                $middlewareNamespace = $middleVal;
190
            }
191
            else{
192
                $middlewareNamespace = app()->namespace()->middleware().'\\'.ucfirst($middleVal);
193
            }
194
195
            //middleware and exclude class instances
196
            $excludeClass = $this->app['excludeClass'];
197
            $middlewareClass = $this->getResolveServiceMiddleware();
198
199
            //middleware definitions.
200
            $this->middleware['namespace']          = $middlewareNamespace;
201
            $this->middleware['key']                = $middleKey;
202
            $this->middleware['class']              = $middlewareClass;
203
            $this->middleware['middlewareName']     = $middleVal;
204
            $this->middleware['odds']               = $this->middlewareKeyOdds();
205
206
            //middleware class for service middleware
207
            //it will be handled according to the following rule.
208
            //The exclude class will return a callback and allocate the result as bool to the exclude variable.
209
            //If the exclude variable is true then the middleware will be run.
210
            $excludeClass->exclude($this->middleware,function($exclude) use ($middleVal){
211
212
                if($exclude){
213
214
                    //the condition of a specific statement to be handled
215
                    if($this->checkNamespaceAndSpecificCondition()){
216
                        $this->pointer($middleVal);
217
218
                        //directly registered to the middleware name show property.
219
                        $this->show[] = class_basename($this->middleware['namespace']);
220
221
                        // the middleware namespace must have handletraitcontract interface property.
222
                        // otherwise, middleware will not work.
223
                        if(false === $this->app->runningInConsole()
224
                            && $this->app->resolve($this->middleware['namespace']) instanceof HandleContracts){
225
                            $this->app->resolve($this->middleware['namespace'])->handle();
226
                        }
227
                    }
228
                }
229
230
            });
231
        }
232
    }
233
234
    /**
235
     * sey middleware key odds
236
     *
237
     * @param null $key
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $key is correct as it would always require null to be passed?
Loading history...
238
     * @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...
239
     */
240
    public function setKeyOdds($key=null,$value=null)
241
    {
242
        //user-defined middleware constants.
243
        if(!is_null($key) && !is_null($value)){
0 ignored issues
show
introduced by
The condition is_null($key) is always true.
Loading history...
244
            $this->odds[$key] = $value;
245
        }
246
    }
247
248
    /**
249
     * register to container for middleware
250
     *
251
     * @return void
252
     */
253
    private function setMiddleware()
254
    {
255
        //get service middleware namespace
256
        $serviceMiddleware = $this->serviceMiddleware ?? app()->namespace()->serviceMiddleware();
257
258
        // if the service middleware does not represent a class,
259
        // then in this case core support is assigned as a class service middleware.
260
        if(Utils::isNamespaceExists($serviceMiddleware)===false){
261
            $serviceMiddleware = ServiceMiddlewareManager::class;
262
        }
263
264
        //We are logging the kernel for the middleware class and the exclude class
265
        $this->app->register('middlewareClass',$this->app->resolve($serviceMiddleware));
266
        $this->app->register('excludeClass',$this->app->resolve(ExcludeMiddleware::class));
267
    }
268
269
    /**
270
     * set service middleware
271
     *
272
     * @param null $serviceMiddleware
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $serviceMiddleware is correct as it would always require null to be passed?
Loading history...
273
     */
274
    public function setserviceMiddleware($serviceMiddleware=null)
275
    {
276
        if(!is_null($serviceMiddleware)){
0 ignored issues
show
introduced by
The condition is_null($serviceMiddleware) is always true.
Loading history...
277
            $this->serviceMiddleware = $serviceMiddleware;
278
        }
279
    }
280
281
    /**
282
     * specific middleware condition
283
     *
284
     * @param $key
285
     * @return bool
286
     */
287
    private function specificMiddlewareCondition($key)
288
    {
289
        //If the all option is present,
290
        //it is automatically injected into all services for the middleware application.
291
        if($key==="all") return true;
292
293
        //service middleware key
294
        //if it is array,check odds
295
        if(is_array($key)){
296
297
            //get middleware odd keys
298
            $odds = $this->middlewareKeyOdds();
299
300
            //If the user definition specified in the middleware key is an array,
301
            //then the middleware is conditioned and the services are individually checked according to
302
            //the degree of conformity with the middlewareOdds method and
303
            //the middleware is executed under the specified condition.
304
            foreach($key as $item){
305
                if(in_array($item,$odds)){
306
                    return true;
307
                }
308
            }
309
        }
310
311
        //return false
312
        return false;
313
    }
314
315
    /**
316
     * register to container for middleware pointer
317
     *
318
     * @param $middleValue
319
     * @return void
320
     */
321
    private function pointer($middleValue)
322
    {
323
        if(isset($this->app['pointer']['middlewareList'])){
324
325
            $middlewareList = $this->app['pointer']['middlewareList'];
326
327
            if(is_array($middlewareList)){
328
                $middlewareList = array_merge($middlewareList,[$middleValue]);
329
                $this->app->register('pointer','middlewareList',$middlewareList);
330
            }
331
        }
332
        else{
333
            $this->app->register('pointer','middlewareList',[$middleValue]);
334
        }
335
    }
336
}