Completed
Push — master ( a4c193...4ecd26 )
by Anton
10s
created

Validator   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 55
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1

Test Coverage

Coverage 81.82%

Importance

Changes 0
Metric Value
dl 0
loc 55
ccs 9
cts 11
cp 0.8182
rs 10
c 0
b 0
f 0
wmc 5
lcom 1
cbo 1

4 Methods

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