|
1
|
|
|
<?php |
|
2
|
|
|
declare(strict_types=1); |
|
3
|
|
|
|
|
4
|
|
|
namespace BrenoRoosevelt\Validation; |
|
5
|
|
|
|
|
6
|
|
|
use BrenoRoosevelt\Validation\Contracts\Fieldable; |
|
7
|
|
|
use BrenoRoosevelt\Validation\Contracts\Prioritable; |
|
8
|
|
|
use BrenoRoosevelt\Validation\Contracts\Result; |
|
9
|
|
|
use BrenoRoosevelt\Validation\Contracts\Rule; |
|
10
|
|
|
use BrenoRoosevelt\Validation\Contracts\Stoppable; |
|
11
|
|
|
use BrenoRoosevelt\Validation\Exception\ValidateOrFail; |
|
12
|
|
|
use BrenoRoosevelt\Validation\Translation\Translator; |
|
13
|
|
|
|
|
14
|
|
|
abstract class AbstractRule implements Rule, Fieldable, Stoppable, Prioritable |
|
15
|
|
|
{ |
|
16
|
|
|
const MESSAGE = 'Constraint violation (%s)'; |
|
17
|
|
|
|
|
18
|
|
|
use ValidateOrFail, BelongsToField, StopOnFailure, Priority; |
|
19
|
|
|
|
|
20
|
|
|
public function __construct( |
|
21
|
|
|
protected ?string $message = null, |
|
22
|
|
|
?int $stopOnFailure = null, |
|
23
|
|
|
?int $priority = null |
|
24
|
|
|
) { |
|
25
|
|
|
$this->setStopSign($stopOnFailure ?? StopSign::DONT_STOP); |
|
26
|
|
|
$this->setPriority($priority ?? Prioritable::LOWEST_PRIORITY); |
|
27
|
|
|
$this->setField(null); |
|
28
|
|
|
} |
|
29
|
|
|
|
|
30
|
|
|
public function message(): string |
|
31
|
|
|
{ |
|
32
|
|
|
return $this->message ?? $this->translatedMessage(); |
|
33
|
|
|
} |
|
34
|
|
|
|
|
35
|
|
|
private function hasOwnMessage(): bool |
|
36
|
|
|
{ |
|
37
|
|
|
return static::MESSAGE !== self::MESSAGE; |
|
38
|
|
|
} |
|
39
|
|
|
|
|
40
|
|
|
public function translatedMessage(): ?string |
|
41
|
|
|
{ |
|
42
|
|
|
return |
|
43
|
|
|
$this->hasOwnMessage() ? |
|
44
|
|
|
Translator::translate(static::MESSAGE) : |
|
45
|
|
|
Translator::translate(static::MESSAGE, $this->className()); |
|
46
|
|
|
} |
|
47
|
|
|
|
|
48
|
|
|
/** @inheritDoc */ |
|
49
|
|
|
public function validate(mixed $input, array $context = []): Result |
|
50
|
|
|
{ |
|
51
|
|
|
return |
|
52
|
|
|
$this->isValid($input, $context) ? |
|
53
|
|
|
ErrorReporting::success() : |
|
54
|
|
|
(new ErrorReporting)->addError($this->message(), $this->getField(), $this); |
|
55
|
|
|
} |
|
56
|
|
|
|
|
57
|
|
|
protected function className(): string |
|
58
|
|
|
{ |
|
59
|
|
|
return array_reverse(explode('\\', get_class($this)))[0]; |
|
60
|
|
|
} |
|
61
|
|
|
|
|
62
|
|
|
abstract public function isValid(mixed $input, array $context = []): bool; |
|
63
|
|
|
} |
|
64
|
|
|
|