1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
/* |
4
|
|
|
* This file is part of Respect/Validation. |
5
|
|
|
* |
6
|
|
|
* (c) Alexandre Gomes Gaigalas <[email protected]> |
7
|
|
|
* |
8
|
|
|
* For the full copyright and license information, please view the "LICENSE.md" |
9
|
|
|
* file that was distributed with this source code. |
10
|
|
|
*/ |
11
|
|
|
|
12
|
|
|
declare(strict_types=1); |
13
|
|
|
|
14
|
|
|
namespace Respect\Validation\Rules; |
15
|
|
|
|
16
|
|
|
use ReflectionClass; |
17
|
|
|
use Respect\Validation\Exceptions\ComponentException; |
18
|
|
|
use Respect\Validation\Exceptions\ZendException; |
19
|
|
|
|
20
|
|
|
/** |
21
|
|
|
* @author Alexandre Gomes Gaigalas <[email protected]> |
22
|
|
|
* @author Henrique Moody <[email protected]> |
23
|
|
|
* @author Hugo Hamon <[email protected]> |
24
|
|
|
*/ |
25
|
|
|
class Zend extends AbstractRule |
26
|
|
|
{ |
27
|
|
|
protected $messages = []; |
28
|
|
|
protected $zendValidator; |
29
|
|
|
|
30
|
9 |
|
public function __construct($validator, $params = []) |
31
|
|
|
{ |
32
|
9 |
|
if (is_object($validator)) { |
33
|
2 |
|
$this->zendValidator = $validator; |
34
|
2 |
|
return; |
35
|
|
|
} |
36
|
|
|
|
37
|
7 |
|
if (!is_string($validator)) { |
38
|
|
|
throw new ComponentException('Invalid Validator Construct'); |
39
|
|
|
} |
40
|
|
|
|
41
|
7 |
|
if (false === mb_stripos($validator, 'Zend')) { |
42
|
6 |
|
$validator = "Zend\\Validator\\{$validator}"; |
43
|
|
|
} else { |
44
|
1 |
|
$validator = "\\{$validator}"; |
45
|
|
|
} |
46
|
|
|
|
47
|
7 |
|
$zendMirror = new ReflectionClass($validator); |
48
|
|
|
|
49
|
7 |
|
if ($zendMirror->hasMethod('__construct')) { |
50
|
7 |
|
$this->zendValidator = $zendMirror->newInstanceArgs($params); |
51
|
|
|
} else { |
52
|
|
|
$this->zendValidator = $zendMirror->newInstance(); |
53
|
|
|
} |
54
|
7 |
|
} |
55
|
|
|
|
56
|
3 |
|
public function assert($input): void |
57
|
|
|
{ |
58
|
3 |
|
$validator = clone $this->zendValidator; |
59
|
|
|
|
60
|
3 |
|
if ($validator->isValid($input)) { |
61
|
1 |
|
return; |
62
|
|
|
} |
63
|
|
|
|
64
|
2 |
|
$exceptions = []; |
65
|
2 |
|
foreach ($validator->getMessages() as $m) { |
66
|
2 |
|
$exceptions[] = $this->reportError($m, get_object_vars($this)); |
67
|
|
|
} |
68
|
|
|
|
69
|
|
|
/** @var ZendException $zendException */ |
70
|
2 |
|
$zendException = $this->reportError($input); |
71
|
2 |
|
$zendException->addChildren($exceptions); |
72
|
|
|
|
73
|
2 |
|
throw $zendException; |
74
|
|
|
} |
75
|
|
|
|
76
|
3 |
|
public function validate($input): bool |
77
|
|
|
{ |
78
|
3 |
|
$validator = clone $this->zendValidator; |
79
|
|
|
|
80
|
3 |
|
return $validator->isValid($input); |
81
|
|
|
} |
82
|
|
|
} |
83
|
|
|
|