generated from MarwanAlsoltany/php-package
-
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathCallback.php
101 lines (90 loc) · 2.94 KB
/
Callback.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
<?php
/**
* @author Marwan Al-Soltany <MarwanAlsoltany@gmail.com>
* @copyright Marwan Al-Soltany 2022
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
declare(strict_types=1);
namespace MAKS\Mighty\Validation\Constraint;
use Attribute;
use MAKS\Mighty\Rule;
use MAKS\Mighty\Result;
use MAKS\Mighty\Validation\Strategy;
use MAKS\Mighty\Validation\Constraint;
use MAKS\Mighty\Validation\Constraint\ValidatesOne;
/**
* Validates any data using a callback function.
*
* @package Mighty\Validator
*/
#[Attribute(
Attribute::IS_REPEATABLE |
Attribute::TARGET_CLASS |
Attribute::TARGET_CLASS_CONSTANT |
Attribute::TARGET_PROPERTY |
Attribute::TARGET_METHOD
)]
class Callback extends Constraint implements ValidatesOne
{
/**
* Callback constructor.
*
* @param string|array<string,string> $callback
* @param string|null $message
* @param Strategy $strategy
*/
public function __construct(
private string|array $callback,
?string $message = null,
Strategy $strategy = Strategy::FailLazy,
) {
($validator = clone $this->getMasterValidator())
->setData([
'callback' => $callback,
])
->setValidations([
'callback' => $validator->validation()->required()->group(fn ($validation) => $validation->string()->xor()->array())->callable(),
])
->setLabels([
'callback' => 'Callback',
])
->setMessages([
'callback' => [
'callable' => '${@label} must be a callable in the form of string or array (constant expression)',
],
])
->check();
parent::__construct(validation: 'callback', messages: ['callback' => $message], strategy: $strategy);
}
/**
* {@inheritDoc}
*/
public function validate(mixed $value = null): Result
{
$name = '';
$data = [$name => $value];
$validations = [$name => $this->validation];
$messages = [$name => [$this->validation => $this->messages[$this->validation] ?? null]];
$labels = [$name => static::class];
/** @var callable $callback */
$callback = $this->callback;
$callback = $callback(...);
$result = $this
->getValidator()
->addRule(
(new Rule())
->setName('callback')
->setCallback($callback)
->setParameters(['@input'])
->setComparison(['@output', '&&', true])
->setMessage('${@label}: Callback validation failed.')
)
->setData($data)
->setValidations($validations)
->setMessages($messages)
->setLabels($labels)
->validate();
return $result[$name];
}
}