Completed
Push — 2.0 ( 60f4f1...be6014 )
by Kirill
04:10
created

HasValidation::getValidator()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 13
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 6
nc 1
nop 2
dl 0
loc 13
rs 9.4285
c 0
b 0
f 0
1
<?php
2
/**
3
 * This file is part of laravel.su package.
4
 * For the full copyright and license information, please view the LICENSE
5
 * file that was distributed with this source code.
6
 */
7
declare(strict_types=1);
8
9
namespace App\GraphQL\Kernel;
10
11
use Illuminate\Validation\Factory;
12
use Folklore\GraphQL\Support\Field;
13
use Illuminate\Contracts\Validation\Validator;
14
15
/**
16
 * Class HasValidation
17
 * @package App\GraphQL\Kernel
18
 * @mixin Field
19
 */
20
trait HasValidation
21
{
22
    /**
23
     * @param $args
24
     * @param $rules
25
     * @return Validator
26
     */
27
    protected function getValidator($args, $rules): Validator
28
    {
29
        /** @var Factory $factory */
30
        $factory = app(Factory::class);
31
32
        $validator = $factory->make($args, $rules, $this->messages());
33
34
        $validator->after(function($validator) use($args) {
35
            $this->afterValidation($validator, $args);
36
        });
37
38
        return $validator;
39
    }
40
41
    /**
42
     * @param Validator|\Illuminate\Validation\Validator $validator
43
     * @param array $args
44
     */
45
    private function afterValidation(Validator $validator, array $args): void
46
    {
47
        $validatorErrors = $this->validate($validator, $args);
48
49
        if ($validatorErrors instanceof \Traversable) {
50
            foreach ($validatorErrors as $key => $message) {
51
                $validator->errors()->add($key, $message);
52
            }
53
        }
54
    }
55
56
    /**
57
     * @param Validator $validator
58
     * @param array $args
59
     * @return \Generator|null
60
     */
61
    public function validate(Validator $validator, array $args = []): ?\Generator
0 ignored issues
show
Unused Code introduced by
The parameter $validator is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Unused Code introduced by
The parameter $args is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
62
    {
63
        return null;
64
    }
65
66
    /**
67
     * @return array
68
     */
69
    public function messages(): array
70
    {
71
        return [];
72
    }
73
}