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 Respect\Validation\Exceptions\ValidationException; |
17
|
|
|
use Respect\Validation\Validatable; |
18
|
|
|
use function call_user_func; |
19
|
|
|
use function restore_error_handler; |
20
|
|
|
use function set_error_handler; |
21
|
|
|
|
22
|
|
|
/** |
23
|
|
|
* Validates the return of a callable for a given input. |
24
|
|
|
* |
25
|
|
|
* @author Alexandre Gomes Gaigalas <[email protected]> |
26
|
|
|
* @author Emmerson Siqueira <[email protected]> |
27
|
|
|
* @author Henrique Moody <[email protected]> |
28
|
|
|
*/ |
29
|
|
|
final class Call extends AbstractRule |
30
|
|
|
{ |
31
|
|
|
/** |
32
|
|
|
* @var callable |
33
|
|
|
*/ |
34
|
|
|
private $callable; |
35
|
|
|
|
36
|
|
|
/** |
37
|
|
|
* @var Validatable |
38
|
|
|
*/ |
39
|
|
|
private $rule; |
40
|
|
|
|
41
|
|
|
/** |
42
|
|
|
* Initializes the rule with the callable to be executed after the input is passed. |
43
|
|
|
* |
44
|
|
|
* @param callable $callable |
45
|
|
|
* @param Validatable $rule |
46
|
|
|
*/ |
47
|
11 |
|
public function __construct(callable $callable, Validatable $rule) |
48
|
|
|
{ |
49
|
11 |
|
$this->callable = $callable; |
50
|
11 |
|
$this->rule = $rule; |
51
|
11 |
|
} |
52
|
|
|
|
53
|
|
|
/** |
54
|
|
|
* {@inheritdoc} |
55
|
|
|
*/ |
56
|
6 |
|
public function assert($input): void |
57
|
|
|
{ |
58
|
6 |
|
$this->setErrorHandler($input); |
59
|
|
|
|
60
|
6 |
|
$this->rule->assert(call_user_func($this->callable, $input)); |
61
|
|
|
|
62
|
1 |
|
restore_error_handler(); |
63
|
1 |
|
} |
64
|
|
|
|
65
|
|
|
/** |
66
|
|
|
* {@inheritdoc} |
67
|
|
|
*/ |
68
|
6 |
|
public function check($input): void |
69
|
|
|
{ |
70
|
6 |
|
$this->setErrorHandler($input); |
71
|
|
|
|
72
|
6 |
|
$this->rule->check(call_user_func($this->callable, $input)); |
73
|
|
|
|
74
|
3 |
|
restore_error_handler(); |
75
|
3 |
|
} |
76
|
|
|
|
77
|
|
|
/** |
78
|
|
|
* {@inheritdoc} |
79
|
|
|
*/ |
80
|
4 |
|
public function validate($input): bool |
81
|
|
|
{ |
82
|
|
|
try { |
83
|
4 |
|
$this->check($input); |
84
|
2 |
|
} catch (ValidationException $exception) { |
85
|
2 |
|
return false; |
86
|
|
|
} |
87
|
|
|
|
88
|
2 |
|
return true; |
89
|
|
|
} |
90
|
|
|
|
91
|
|
|
private function setErrorHandler($input): void |
92
|
|
|
{ |
93
|
11 |
|
set_error_handler(function () use ($input): void { |
94
|
4 |
|
throw $this->reportError($input); |
95
|
11 |
|
}); |
96
|
11 |
|
} |
97
|
|
|
} |
98
|
|
|
|