Passed
Push — main ( 6de128...92895e )
by Breno
01:53
created

MaybeBelongsToField   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 31
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 13
c 0
b 0
f 0
dl 0
loc 31
rs 10
wmc 6

4 Methods

Rating   Name   Duplication   Size   Complexity  
A getField() 0 3 1
A newEmptyValidationResult() 0 6 2
A belongsToField() 0 3 1
A withField() 0 9 2
1
<?php
2
declare(strict_types=1);
3
4
namespace BrenoRoosevelt\Validation;
5
6
use BrenoRoosevelt\Validation\Rules\NotEmpty;
7
8
trait MaybeBelongsToField
9
{
10
    private ?string $field = null;
11
12
    public function getField(): ?string
13
    {
14
        return $this->field;
15
    }
16
17
    public function withField(?string $field): static
18
    {
19
        if ($field !== null) {
20
            (new NotEmpty('When provided, the field cannot be left blank'))->validateOrFail($field);
21
        }
22
23
        $instance = clone $this;
24
        $instance->field = $field;
25
        return $instance;
26
    }
27
28
    public function belongsToField(): bool
29
    {
30
        return $this->field !== null;
31
    }
32
33
    private function newEmptyValidationResult(): ValidationResult|ValidationResultByField
34
    {
35
        return
36
            $this->belongsToField() ?
37
                new ValidationResultByField($this->getField()) :
38
                ValidationResult::everythingIsOk();
39
    }
40
}
41