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