Test Setup Failed
Push — master ( 92050c...514983 )
by Php Easy Api
04:20
created

Client::validation()   A

Complexity

Conditions 4
Paths 2

Size

Total Lines 8
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
eloc 3
nc 2
nop 0
dl 0
loc 8
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace Resta\Client;
4
5
use Resta\Support\Utils;
6
use Resta\Contracts\HandleContracts;
7
use Resta\Support\ReflectionProcess;
8
use ReflectionException as ReflectionExceptionAlias;
9
10
/**
11
 * @property $this auto_capsule
12
 * @property $this http
13
 * @property $this autoObjectValidate
14
 * @property $this requestExcept
15
 * @property $this expected
16
 * @property  $this groups
17
 */
18
class Client extends ClientAbstract implements HandleContracts
19
{
20
    /**
21
     * @var array
22
     */
23
    protected $capsule = [];
24
25
    /**
26
     * @var null|string
27
     */
28
    protected $clientName;
29
30
    /**
31
     * @var array
32
     */
33
    protected $except = [];
34
35
    /**
36
     * @var null|string
37
     */
38
    protected $method;
39
40
    /**
41
     * @var ReflectionProcess
42
     */
43
    protected $reflection;
44
45
    /**
46
     * @var null|ClientHttpManager
47
     */
48
    protected $requestHttp;
49
50
    /**
51
     * @var null|array
52
     */
53
    protected $clientData;
54
55
    /**
56
     * @var array
57
     */
58
    protected $requestData = [];
59
60
    /**
61
     * @var array
62
     */
63
    protected $generatorList = [];
64
65
    /**
66
     * Request constructor.
67
     *
68
     * @param null|array $clientData
69
     *
70
     * @throws ReflectionExceptionAlias
71
     */
72
    public function __construct($clientData=null)
73
    {
74
        //reflection process
75
        $this->reflection = app()['reflection']($this);
76
77
        //set clientName for client
78
        $this->setClientName();
79
80
        //get http method via request http manager class
81
        $this->requestHttp = app()->resolve(ClientHttpManager::class,['client'=>$this]);
82
83
        //get request client data
84
        $this->clientData = ($clientData===null) ? $this->requestHttp->resolve() : $clientData;
85
86
        //handle request
87
        $this->handle();
88
    }
89
90
    /**
91
     * auto validate
92
     *
93
     * @param $validate
94
     */
95
    private function autoValidate($validate)
96
    {
97
        //we get the values ​​to auto-validate.
98
        foreach ($this->{$validate} as $object=>$datas){
99
100
            if(false===Utils::isNamespaceExists($object)){
101
                return;
102
            }
103
104
            // the auto-validate value must necessarily represent a class.
105
            // otherwise auto-validate is not used.
106
            $getObjectInstance = app()->resolve($object);
107
108
            // we get the index values,
109
            // which are called methods of the auto-validate value that represents the class.
110
            foreach ($datas as $dataKey=>$data){
111
112
                // if the methods of the auto-validate class resolved by the container resolve method apply,
113
                // the process of auto-validate automatic implementation will be completed.
114
                if(is_numeric($dataKey) && method_exists($getObjectInstance,$data) && isset($this->origin[$data])){
115
                    if(!is_array($this->origin[$data])){
116
                        $this->origin[$data] = array($this->origin[$data]);
117
                    }
118
                    foreach ($this->origin[$data] as $originData){
119
                        $getObjectInstance->{$data}($originData);
120
                    }
121
                }
122
            }
123
        }
124
    }
125
126
    /**
127
     * capsule inputs
128
     *
129
     * @return void|mixed
130
     */
131
    private function capsule()
132
    {
133
        //a process can be added to the capsule array using the method.
134
        if(method_exists($this,'capsuleMethod')){
135
            $this->capsule = array_merge($this->capsule,$this->capsuleMethod());
136
        }
137
138
        // expected method is executed.
139
        // this method is a must for http method values to be found in this property.
140
        if($this->checkProperties('capsule')){
141
142
            if(property_exists($this,'auto_capsule') && is_array($this->auto_capsule)){
0 ignored issues
show
introduced by
The condition is_array($this->auto_capsule) is always false.
Loading history...
143
                $this->capsule = array_merge($this->capsule,$this->auto_capsule);
144
            }
145
146
            foreach($this->inputs as $input=>$value){
147
148
                if($this->checkProperties('capsule') && !in_array($input,$this->capsule)){
149
                    exception('clientCapsule',['key'=>$input])
150
                        ->overflow('The '.$input.' value cannot be sent.');
151
                }
152
            }
153
        }
154
    }
155
156
    /**
157
     * check http method
158
     *
159
     * @return void|mixed
160
     */
161
    private function checkHttpMethod()
162
    {
163
        //get http method
164
        $method = $this->requestHttp->getMethod();
0 ignored issues
show
Bug introduced by
The method getMethod() does not exist on null. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

164
        /** @scrutinizer ignore-call */ $method = $this->requestHttp->getMethod();

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
165
166
        // Determines which HTTP method
167
        // the request object will be exposed to.
168
        if($this->checkProperties('http')){
169
170
            // if the current http method does not exist
171
            // in the http object, the exception will be thrown.
172
            if(!in_array($method,$this->http)){
0 ignored issues
show
Bug introduced by
$this->http of type Resta\Client\Client is incompatible with the type array expected by parameter $haystack of in_array(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

172
            if(!in_array($method,/** @scrutinizer ignore-type */ $this->http)){
Loading history...
173
174
                //exception batMethodCall
175
                exception()->badMethodCall(
176
                    'Invalid http method process for '.basename($this).'.That is accepted http methods ['.implode(",",$this->http).'] ');
0 ignored issues
show
Bug introduced by
$this of type Resta\Client\Client is incompatible with the type string expected by parameter $path of basename(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

176
                    'Invalid http method process for '.basename(/** @scrutinizer ignore-type */ $this).'.That is accepted http methods ['.implode(",",$this->http).'] ');
Loading history...
Bug introduced by
$this->http of type Resta\Client\Client is incompatible with the type array expected by parameter $pieces of implode(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

176
                    'Invalid http method process for '.basename($this).'.That is accepted http methods ['.implode(",",/** @scrutinizer ignore-type */ $this->http).'] ');
Loading history...
177
            }
178
        }
179
    }
180
181
    /**
182
     * check properties
183
     *
184
     * @param $properties
185
     * @return bool
186
     */
187
    private function checkProperties($properties)
188
    {
189
        // from the properties of the object properties to
190
        // the existing variables, control the array and at least one element.
191
        return (property_exists($this,$properties)
192
            && is_array($this->{$properties}) && count($this->{$properties})) ? true : false;
193
    }
194
195
    /**
196
     * register container for request
197
     *
198
     * @return mixed|void
199
     */
200
    private function containerRegister()
201
    {
202
        // we are saving the expected values ​​for the request in container.
203
        // this record can be returned in exception information.
204
        app()->register('requestExpected',$this->expected);
205
    }
206
207
    /**
208
     * get request except
209
     *
210
     * @param $except
211
     * @return $this
212
     */
213
    public function except($except)
214
    {
215
        // the except parameter is a callable value.
216
        if(is_callable($except)){
217
            $call = call_user_func_array($except,[$this]);
218
            $except = $call;
219
        }
220
221
        // except with the except exceptions property
222
        // and then assigning them to the inputs property.
223
        $this->except = array_merge($this->except,$except);
224
        $this->inputs = array_diff_key($this->inputs,array_flip($this->except));
225
226
        return $this;
227
    }
228
229
    /**
230
     * expected inputs
231
     *
232
     * @return void|mixed
233
     */
234
    private function expectedInputs()
235
    {
236
        // expected method is executed.
237
        // this method is a must for http method values to be found in this property.
238
        if($this->checkProperties('expected')){
239
240
            // if the expected values are not found in the inputs array,
241
            // the exception will be thrown.
242
            foreach ($this->expected as $expected){
243
244
                $expectedValues = [];
245
246
                // mandatory expected data for each key can be separated by | operator.
247
                // this is evaluated as "or".
248
                foreach($expectedData = explode("|",$expected) as $inputs){
249
250
                    // we should do key control for group format.
251
                    // this process will allow us to perform key control for 2D array correctly.
252
                    $this->groupsProcess($inputs);
253
254
                    if(!isset($this->inputs[$inputs])){
255
                        $expectedValues[$inputs] = $inputs;
256
                    }
257
                }
258
259
                // if the expectedData and expectedValues ​​
260
                // array are numerically equal to the expected key, the exception is thrown.
261
                if(count($expectedData)===count($expectedValues)){
262
                    exception('clientExpected',['key'=>$expected])
263
                        ->unexpectedValue('You absolutely have to send the value '.implode(" or ",$expectedValues).' for request object');
264
                }
265
            }
266
        }
267
    }
268
269
    /**
270
     * generator manager
271
     *
272
     * @throws ReflectionExceptionAlias
273
     */
274
    private function generatorManager()
275
    {
276
        // check the presence of the generator object
277
        // and operate the generator over this object.
278
        if($this->checkProperties('auto_generators')){
279
            $generators = $this->getAutoGenerators();
280
        }
281
282
        // check the presence of the generator object
283
        // and operate the generator over this object.
284
        if($this->checkProperties('generators')){
285
            $generators = array_merge(isset($generators) ? $generators: [],$this->getGenerators());
0 ignored issues
show
Bug introduced by
It seems like $this->getGenerators() can also be of type Resta\Client\ClientAbstract; however, parameter $array2 of array_merge() does only seem to accept array|null, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

285
            $generators = array_merge(isset($generators) ? $generators: [],/** @scrutinizer ignore-type */ $this->getGenerators());
Loading history...
286
        }
287
288
        if(isset($generators)){
289
            $this->generatorMethod($generators);
290
        }
291
    }
292
293
    /**
294
     * generator method
295
     *
296
     * @param $generators
297
     *
298
     * @throws ReflectionExceptionAlias
299
     */
300
    private function generatorMethod($generators)
301
    {
302
        //generator array object
303
        foreach ($generators as $generator){
304
305
            //generator method name
306
            $generatorMethodName = $generator.'Generator';
307
308
            // if the generator method is present,
309
            // the fake value is assigned.
310
            if(method_exists($this,$generatorMethodName)){
311
312
                //fake registration
313
                if(!isset($this->inputs[$generator])){
314
315
                    $generatorMethodNameResult = $this->{$generatorMethodName}();
316
317
                    if(!is_null($generatorMethodNameResult)){
318
                        $this->{$generator} = $this->{$generatorMethodName}();
319
                        $this->inputs[$generator] = $this->{$generatorMethodName}();
320
                        $this->generatorList[] = $generator;
321
                    }
322
                }
323
                else {
324
325
                    if($this->checkProperties('auto_generators_dont_overwrite')
326
                        && in_array($generator,$this->getAutoGeneratorsDontOverwrite())){
0 ignored issues
show
Bug introduced by
It seems like $this->getAutoGeneratorsDontOverwrite() can also be of type Resta\Client\ClientAbstract; however, parameter $haystack of in_array() does only seem to accept array, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

326
                        && in_array($generator,/** @scrutinizer ignore-type */ $this->getAutoGeneratorsDontOverwrite())){
Loading history...
327
                        $this->{$generator} = $this->{$generatorMethodName}();
328
                        $this->inputs[$generator] = $this->{$generatorMethodName}();
329
                        $this->generatorList[] = $generator;
330
                    }
331
332
                    if($this->checkProperties('generators_dont_overwrite')
333
                        && in_array($generator,$this->getGeneratorsDontOverwrite())){
334
                        $this->{$generator} = $this->{$generatorMethodName}();
335
                        $this->inputs[$generator] = $this->{$generatorMethodName}();
336
                        $this->generatorList[] = $generator;
337
                    }
338
339
                }
340
341
                $this->registerRequestInputs($generator);
342
            }
343
        }
344
    }
345
346
    /**
347
     * get client name for request
348
     *
349
     * @return string
350
     */
351
    public function getClientName()
352
    {
353
        return $this->clientName;
354
    }
355
356
    /**
357
     * we should do key control for group format.
358
     * this process will allow us to perform key control for 2D array correctly.
359
     *
360
     * @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...
361
     * @param null $callback
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $callback is correct as it would always require null to be passed?
Loading history...
362
     */
363
    public function groupsProcess($key=null,$callback=null)
364
    {
365
        if(property_exists($this,'groups') && is_array($this->groups)){
0 ignored issues
show
introduced by
The condition is_array($this->groups) is always false.
Loading history...
366
367
            $clientObjects = $this->getClientObjects();
368
369
            foreach ($this->groups as $group){
370
                if(isset($clientObjects['origin'][$group][$key])){
371
                    $this->{$key} = $clientObjects['origin'][$group][$key];
372
                    $this->inputs[$key] = $this->{$key};
373
374
                    if(is_callable($callback)){
375
                        call_user_func_array($callback,[$key]);
376
                    }
377
                }
378
            }
379
        }
380
    }
381
382
    /**
383
     * request handle
384
     *
385
     * @return mixed|void
386
     *
387
     * @throws ReflectionExceptionAlias
388
     */
389
    public function handle()
390
    {
391
        //set container for request
392
        $this->containerRegister();
393
394
        //we record the values ​​
395
        //that coming with the post.
396
        $this->initClient();
397
398
        // this method determines
399
        // how the request object will be requested,
400
        $this->checkHttpMethod();
401
402
        // get capsule as mandatory values
403
        $this->capsule();
404
405
        // if a fake method is defined and it is not in
406
        // the context of any key method when access is granted,
407
        // it can be filled with fake method.
408
        $this->generatorManager();
409
410
        // contrary to capsule method,
411
        // expected values must be in the key being sent.
412
        $this->expectedInputs();
413
414
        // it passes all keys that are sent through
415
        // a validation method on the user side.
416
        $this->validation();
417
418
        // we update the input values ​​after
419
        // we receive and check the saved objects.
420
        $this->setClientObjects();
421
422
        // the values ​​specified in request except property
423
        // are subtracted from all input values.
424
        $this->requestExcept();
425
    }
426
427
    /**
428
     * get init client
429
     *
430
     * @return void
431
     */
432
    private function initClient()
433
    {
434
        // we use the http method to write
435
        // the values to the inputs and origin properties.
436
        foreach($this->clientData as $key=>$value){
437
438
            //inputs and origin properties
439
            $this->inputs[$key] = $value;
440
            $this->origin[$key] = $value;
441
        }
442
    }
443
444
    /**
445
     * the values ​​specified in request except property
446
     * are subtracted from all input values.
447
     *
448
     * @return mixed|void
449
     */
450
    private function requestExcept()
451
    {
452
        if(property_exists($this,'requestExcept') && is_array($this->requestExcept)){
0 ignored issues
show
introduced by
The condition is_array($this->requestExcept) is always false.
Loading history...
453
            foreach ($this->requestExcept as $item){
454
                if(isset($this->inputs[$item])){
455
                    unset($this->inputs[$item]);
456
                }
457
            }
458
        }
459
    }
460
461
    /**
462
     * set client name for client resolver
463
     *
464
     * @param null|string $clientName
465
     * @return void|mixed
466
     */
467
    public function setClientName($clientName=null)
468
    {
469
        if(!is_null($clientName) && is_string($clientName)){
470
            return $this->clientName = $clientName;
471
        }
472
473
        if(!is_null(Utils::trace(0)) && isset(Utils::trace(0)['object'])){
474
            $backTrace = Utils::trace(0)['object'];
475
476
            if(property_exists($backTrace,'clientName')){
477
                $this->clientName = $backTrace->clientName;
478
            }
479
        }
480
    }
481
482
    /**
483
     * set client objects
484
     *
485
     * @throws ReflectionExceptionAlias
486
     */
487
    private function setClientObjects()
488
    {
489
        $clientObjects = $this->getClientObjects();
490
491
        // we update the input values ​​after
492
        // we receive and check the saved objects.
493
        foreach ($clientObjects as $key=>$value){
494
495
            // we should do key control for group format.
496
            // this process will allow us to perform key control for 2D array correctly.
497
            $this->groupsProcess($key,function($key){
498
                $this->registerRequestInputs($key);
499
                unset($this->inputs[$key]);
500
            });
501
502
            if(!in_array($key,$this->generatorList) && isset($clientObjects['origin'][$key])){
503
504
                $this->{$key} = $clientObjects['origin'][$key];
505
                $this->inputs[$key] = $this->{$key};
506
507
                // the request update to be performed using
508
                // the method name to be used with the http method.
509
                $this->registerRequestInputs($key);
510
            }
511
        }
512
513
    }
514
515
    /**
516
     * register request inputs
517
     *
518
     * @param $key
519
     *
520
     * @throws ReflectionExceptionAlias
521
     */
522
    private function registerRequestInputs($key)
523
    {
524
        // the method name to be used with
525
        // the http method.
526
        $requestMethod = $this->requestHttp->getMethod().''.ucfirst($key);
527
528
        // the request update to be performed using
529
        // the method name to be used with the http method.
530
        $this->setRequestInputs($requestMethod,$key);
531
532
        // the request update to be performed using
533
        // the method name to be used without the http method.
534
        $this->setRequestInputs($key,$key);
535
    }
536
537
    /**
538
     * set request inputs
539
     *
540
     * @param $method
541
     * @param $key
542
     *
543
     * @throws ReflectionExceptionAlias
544
     */
545
    private function setRequestInputs($method,$key)
546
    {
547
        if(!in_array($key,$this->generatorList) && method_exists($this,$method) && $this->reflection->reflectionMethodParams($method)->isProtected){
548
549
            //check annotations for method
550
            $annotation = app()->resolve(ClientAnnotationManager::class,['request'=>$this]);
551
            $annotation->annotation($method,$key);
552
553
            if(isset($this->inputs[$key]) && is_array($this->inputs[$key])){
554
555
                $inputKeys = $this->inputs[$key];
556
557
                $this->inputs[$key] = [];
558
                foreach ($inputKeys as $input){
559
560
                    $this->{$key}               = $input;
561
                    $keyMethod                  = $this->{$method}();
562
                    $this->inputs[$key][]       = $keyMethod;
563
                }
564
            }
565
            else{
566
                if(isset($this->inputs[$key])){
567
                    $keyMethod = $this->{$method}();
568
                    $this->inputs[$key] = $keyMethod;
569
                }
570
571
            }
572
        }
573
    }
574
575
    /**
576
     * validation for request
577
     *
578
     * @return void
579
     */
580
    private function validation()
581
    {
582
        // the auto object validate property is the property
583
        // where all of your request values ​​are automatically validated.
584
        /** @noinspection PhpParamsInspection */
585
        if(property_exists($this,'autoObjectValidate')
586
            && is_array($this->autoObjectValidate) && count($this->autoObjectValidate)){
0 ignored issues
show
introduced by
The condition is_array($this->autoObjectValidate) is always false.
Loading history...
587
            $this->autoValidate('autoObjectValidate');
588
        }
589
    }
590
}