Passed
Push — main ( 5dcab6...f5f51a )
by Breno
02:01
created

AbstractRule::validate()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

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