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

AbstractRule   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 32
Duplicated Lines 0 %

Importance

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

4 Methods

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