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

AbstractRule   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 38
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 11
c 1
b 0
f 0
dl 0
loc 38
rs 10
wmc 6

5 Methods

Rating   Name   Duplication   Size   Complexity  
A message() 0 3 1
A __construct() 0 5 1
A validate() 0 6 2
A className() 0 3 1
A translatedMessage() 0 3 1
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