Passed
Push — main ( 954523...045e26 )
by Breno
01:54
created

AbstractRule::translatedMessage()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
c 0
b 0
f 0
nc 1
nop 0
dl 0
loc 3
rs 10
1
<?php
2
declare(strict_types=1);
3
4
namespace BrenoRoosevelt\Validation;
5
6
use BrenoRoosevelt\Validation\Exception\ValidateOrFailTrait;
7
use BrenoRoosevelt\Validation\Translation\Translator;
8
9
abstract class AbstractRule implements Rule, BelongsToField, Stoppable
10
{
11
    const MESSAGE = 'Contraint violation (%s)';
12
13
    use ValidateOrFailTrait, BelongsToFieldTrait, StoppableTrait;
14
15
    public function __construct(
16
        protected ?string $message = null,
17
        int $stopOnFailure = StopSign::DONT_STOP
18
    ) {
19
        $this->stopOnFailure = $stopOnFailure;
20
    }
21
22
    public function message(): string
23
    {
24
        return $this->message ?? $this->translatedMessage();
25
    }
26
27
    public function translatedMessage(): ?string
28
    {
29
        return Translator::translate(static::MESSAGE, $this->className());
30
    }
31
32
    /** @inheritDoc */
33
    public function validate(mixed $input, array $context = []): Result
34
    {
35
        return
36
            $this->isValid($input, $context) ?
37
                ErrorReporting::success() :
38
                (new ErrorReporting)->addError($this->message(), $this->getField(), $this);
39
    }
40
41
    protected function className(): string
42
    {
43
        return array_reverse(explode('\\', get_class($this)))[0];
44
    }
45
46
    abstract public function isValid(mixed $input, array $context = []): bool;
47
}
48