Test Setup Failed
Push — master ( 514983...6e6ad2 )
by Php Easy Api
04:08
created

Client::autoValidate()   B

Complexity

Conditions 9
Paths 8

Size

Total Lines 25
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 9
eloc 10
nc 8
nop 1
dl 0
loc 25
rs 8.0555
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
            if(is_array($this->groups)){
0 ignored issues
show
introduced by
The condition is_array($this->groups) is always false.
Loading history...
147
                $this->capsule = array_merge($this->capsule,$this->groups);
148
149
                foreach ($this->capsule as $item) {
150
                    $groupProcess = $this->groupsProcess($item,true);
151
                    if(is_array($groupProcess)){
152
                        $this->inputs = array_merge($this->inputs,$groupProcess);
153
                    }
154
                }
155
            }
156
157
            foreach($this->inputs as $input=>$value){
158
159
                if($this->checkProperties('capsule') && !in_array($input,$this->capsule)){
160
                    exception('clientCapsule',['key'=>$input])
161
                        ->overflow('The '.$input.' value cannot be sent.');
162
                }
163
            }
164
        }
165
    }
166
167
    /**
168
     * check http method
169
     *
170
     * @return void|mixed
171
     */
172
    private function checkHttpMethod()
173
    {
174
        //get http method
175
        $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

175
        /** @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...
176
177
        // Determines which HTTP method
178
        // the request object will be exposed to.
179
        if($this->checkProperties('http')){
180
181
            // if the current http method does not exist
182
            // in the http object, the exception will be thrown.
183
            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

183
            if(!in_array($method,/** @scrutinizer ignore-type */ $this->http)){
Loading history...
184
185
                //exception batMethodCall
186
                exception()->badMethodCall(
187
                    'Invalid http method process for '.basename($this).'.That is accepted http methods ['.implode(",",$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 $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

187
                    'Invalid http method process for '.basename($this).'.That is accepted http methods ['.implode(",",/** @scrutinizer ignore-type */ $this->http).'] ');
Loading history...
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

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

296
            $generators = array_merge(isset($generators) ? $generators: [],/** @scrutinizer ignore-type */ $this->getGenerators());
Loading history...
297
        }
298
299
        if(isset($generators)){
300
            $this->generatorMethod($generators);
301
        }
302
    }
303
304
    /**
305
     * generator method
306
     *
307
     * @param $generators
308
     *
309
     * @throws ReflectionExceptionAlias
310
     */
311
    private function generatorMethod($generators)
312
    {
313
        //generator array object
314
        foreach ($generators as $generator){
315
316
            //generator method name
317
            $generatorMethodName = $generator.'Generator';
318
319
            // if the generator method is present,
320
            // the fake value is assigned.
321
            if(method_exists($this,$generatorMethodName)){
322
323
                //fake registration
324
                if(!isset($this->inputs[$generator])){
325
326
                    $generatorMethodNameResult = $this->{$generatorMethodName}();
327
328
                    if(!is_null($generatorMethodNameResult)){
329
                        $this->{$generator} = $this->{$generatorMethodName}();
330
                        $this->inputs[$generator] = $this->{$generatorMethodName}();
331
                        $this->generatorList[] = $generator;
332
                    }
333
                }
334
                else {
335
336
                    if($this->checkProperties('auto_generators_dont_overwrite')
337
                        && 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

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