Validator   A
last analyzed

Complexity

Total Complexity 6

Size/Duplication

Total Lines 66
Duplicated Lines 0 %

Test Coverage

Coverage 66.67%

Importance

Changes 0
Metric Value
eloc 9
dl 0
loc 66
ccs 8
cts 12
cp 0.6667
rs 10
c 0
b 0
f 0
wmc 6

5 Methods

Rating   Name   Duplication   Size   Complexity  
A assert() 0 3 1
A validate() 0 3 1
A getValidator() 0 3 1
A getValidatorForm() 0 6 2
A addValidator() 0 3 1
1
<?php
2
3
/**
4
 * Bluz Framework Component
5
 *
6
 * @copyright Bluz PHP Team
7
 * @link      https://github.com/bluzphp/framework
8
 */
9
10
declare(strict_types=1);
11
12
namespace Bluz\Validator\Traits;
13
14
use Bluz\Validator\Exception\ValidatorException;
15
use Bluz\Validator\ValidatorChain;
16
use Bluz\Validator\ValidatorForm;
17
18
/**
19
 * Validator trait
20
 *
21
 * Example of usage
22
 * <code>
23
 *    use Bluz\Validator\Traits\Validator;
24
 *    use Bluz\Validator\Validator as v;
25
 *
26
 *    class Row extends Db\Row {
27
 *        use Validator;
28
 *        function beforeSave()
29
 *        {
30
 *             $this->addValidator(
31
 *                 'login',
32
 *                 v::required()->latin()->length(3, 255)
33
 *             );
34
 *        }
35
 *    }
36
 * </code>
37
 *
38
 * @package  Bluz\Validator\Traits
39
 * @author   Anton Shevchuk
40
 */
41
trait Validator
42
{
43
    /**
44
     * @var ValidatorForm instance
45
     */
46
    private $validatorForm;
47
48
    /**
49
     * Get ValidatorBuilder
50
     *
51
     * @return ValidatorForm
52
     */
53 2
    private function getValidatorForm(): ValidatorForm
54
    {
55 2
        if (!$this->validatorForm) {
56 2
            $this->validatorForm = new ValidatorForm();
57
        }
58 2
        return $this->validatorForm;
59
    }
60
61
    /**
62
     * Add ValidatorChain
63
     *
64
     * @param string $name
65
     *
66
     * @return ValidatorChain
67
     */
68 2
    public function addValidator(string $name): ValidatorChain
69
    {
70 2
        return $this->getValidatorForm()->add($name);
71
    }
72
73
    /**
74
     * Get ValidatorChain
75
     *
76
     * @param string $name
77
     *
78
     * @return ValidatorChain
79
     */
80
    public function getValidator(string $name): ValidatorChain
81
    {
82
        return $this->getValidatorForm()->get($name);
83
    }
84
85
    /**
86
     * Validate input data
87
     *
88
     * @param  array $input
89
     *
90
     * @return bool
91
     */
92
    public function validate($input): bool
93
    {
94
        return $this->getValidatorForm()->validate($input);
95
    }
96
97
    /**
98
     * Assert input data
99
     *
100
     * @param  array $input
101
     *
102
     * @throws ValidatorException
103
     */
104 2
    public function assert($input): void
105
    {
106 2
        $this->getValidatorForm()->assert($input);
107 2
    }
108
}
109