Passed
Push — main ( cd3a43...b0c9ae )
by Breno
01:54
created

MaybeBelongsToField::field()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 3
c 0
b 0
f 0
nc 1
nop 1
dl 0
loc 5
rs 10
1
<?php
2
declare(strict_types=1);
3
4
namespace BrenoRoosevelt\Validation;
5
6
use BrenoRoosevelt\Validation\Rules\NotEmptyString;
7
8
trait MaybeBelongsToField
9
{
10
    private ?string $field = null;
11
12
    public function getField(): ?string
13
    {
14
        return $this->field;
15
    }
16
17
    /**
18
     * @throws ValidationException
19
     */
20
    public function field(?string $field): static
21
    {
22
        $instance = clone $this;
23
        $instance->setField($field);
24
        return $instance;
25
    }
26
27
    /**
28
     * @throws ValidationException
29
     */
30
    private function setField(?string $field): void
31
    {
32
        (new NotEmptyString('When provided, the field cannot be left blank'))->validateOrFail($field);
33
        $this->field = $field;
34
    }
35
36
    public function belongsToField(): bool
37
    {
38
        return $this->field !== null;
39
    }
40
41
    private function newEmptyValidationResult(): ValidationResult|ValidationResultByField
42
    {
43
        return
44
            $this->belongsToField() ?
45
                new ValidationResultByField($this->getField()) :
46
                ValidationResult::everythingIsOk();
47
    }
48
}
49