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

MaybeBelongsToField::withField()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 5
c 0
b 0
f 0
nc 2
nop 1
dl 0
loc 9
rs 10
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