1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace TS\PHPValidator; |
4
|
|
|
|
5
|
|
|
use phpDocumentor\Reflection\Types\Null_; |
6
|
|
|
use Twig\Extension\AbstractExtension; |
7
|
|
|
use Twig\TwigFunction; |
8
|
|
|
|
9
|
|
|
/** |
10
|
|
|
* Class ValidatorTwig |
11
|
|
|
* @package TS\PHPValidator |
12
|
|
|
* Requires package "twig/twig": "^3.1" |
13
|
|
|
*/ |
14
|
|
|
class ValidatorTwig extends AbstractExtension |
15
|
|
|
{ |
16
|
|
|
/** |
17
|
|
|
* @var Validator Instance |
18
|
|
|
*/ |
19
|
|
|
protected $validator; |
20
|
|
|
|
21
|
|
|
/** |
22
|
|
|
* ValidatorTwig constructor. |
23
|
|
|
* @param Validator $validator |
24
|
|
|
*/ |
25
|
|
|
public function __construct(Validator $validator) |
26
|
|
|
{ |
27
|
|
|
$this->validator = $validator; |
28
|
|
|
} |
29
|
|
|
|
30
|
|
|
/** |
31
|
|
|
* Return Twig Functions |
32
|
|
|
* @return array|TwigFunction[] |
33
|
|
|
*/ |
34
|
|
|
public function getFunctions() |
35
|
|
|
{ |
36
|
|
|
return [ |
37
|
|
|
new TwigFunction('has_errors', [$this, 'hasErrors']), |
38
|
|
|
new TwigFunction('has_error', [$this, 'hasError']), |
39
|
|
|
new TwigFunction('get_errors', [$this, 'getErrors']), |
40
|
|
|
new TwigFunction('get_error', [$this, 'getError']), |
41
|
|
|
new TwigFunction('get_value', [$this, 'getValue']), |
42
|
|
|
|
43
|
|
|
]; |
44
|
|
|
} |
45
|
|
|
|
46
|
|
|
/** |
47
|
|
|
* Check whether there is any errors |
48
|
|
|
* @return bool |
49
|
|
|
*/ |
50
|
|
|
public function hasErrors(): bool |
51
|
|
|
{ |
52
|
|
|
return $this->validator->failed(); |
53
|
|
|
} |
54
|
|
|
|
55
|
|
|
/** |
56
|
|
|
* Check whether a field has error |
57
|
|
|
* @param $key |
58
|
|
|
* @return bool |
59
|
|
|
*/ |
60
|
|
|
public function hasError($key): bool |
61
|
|
|
{ |
62
|
|
|
return isset($this->validator->getErrors()[$key]); |
63
|
|
|
} |
64
|
|
|
|
65
|
|
|
/** |
66
|
|
|
* Get all error messages |
67
|
|
|
*/ |
68
|
|
|
public function getErrors() |
69
|
|
|
{ |
70
|
|
|
return $this->validator->getErrors(); |
71
|
|
|
} |
72
|
|
|
|
73
|
|
|
/** |
74
|
|
|
* Get error by field name |
75
|
|
|
* @param $key |
76
|
|
|
* @return false|mixed |
77
|
|
|
*/ |
78
|
|
|
public function getError($key, $toString = true) |
79
|
|
|
{ |
80
|
|
|
return $toString ? implode(', ', $this->validator->getErrors()[$key]) : $this->validator->getErrors()[$key]; |
81
|
|
|
} |
82
|
|
|
|
83
|
|
|
/** |
84
|
|
|
* Get Specific value by key |
85
|
|
|
* @param $key |
86
|
|
|
* @param mixed|null $default |
87
|
|
|
*/ |
88
|
|
|
public function getValue($key, $default = null) |
89
|
|
|
{ |
90
|
|
|
return $this->validator->getValue($key, $default); |
91
|
|
|
} |
92
|
|
|
} |
93
|
|
|
|