Completed
Pull Request — master (#108)
by Brent
19:52 queued 18:46
created

ValidStateRule   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 48
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 0

Importance

Changes 0
Metric Value
wmc 8
lcom 1
cbo 0
dl 0
loc 48
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace Spatie\ModelStates\Validation;
4
5
use Illuminate\Contracts\Validation\Rule;
6
7
class ValidStateRule implements Rule
8
{
9
    private string $baseStateClass;
0 ignored issues
show
Bug introduced by
This code did not parse for me. Apparently, there is an error somewhere around this line:

Syntax error, unexpected T_STRING, expecting T_FUNCTION or T_CONST
Loading history...
10
11
    private bool $nullable = false;
12
13
    public static function make(string $abstractStateClass): ValidStateRule
14
    {
15
        return new self($abstractStateClass);
16
    }
17
18
    public function __construct(string $abstractStateClass)
19
    {
20
        $this->baseStateClass = $abstractStateClass;
21
    }
22
23
    public function nullable(): ValidStateRule
24
    {
25
        $this->nullable = true;
26
27
        return $this;
28
    }
29
30
    public function required(): ValidStateRule
31
    {
32
        $this->nullable = false;
33
34
        return $this;
35
    }
36
37
    public function passes($attribute, $value): bool
38
    {
39
        if ($this->nullable && $value === null) {
40
            return true;
41
        }
42
43
        $stateClass = $this->baseStateClass::resolveStateClass($value);
44
45
        return is_subclass_of($stateClass, $this->baseStateClass);
46
    }
47
48
    public function message(): string
49
    {
50
        return 'This value is invalid';
51
    }
52
}
53