Completed
Pull Request — master (#32)
by Brent
01:13
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
    /** @var string|\Spatie\ModelStates\State */
10
    private $abstractStateClass;
11
12
    private bool $nullable = false;
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...
13
14
    public static function make(string $abstractStateClass): ValidStateRule
15
    {
16
        return new self($abstractStateClass);
17
    }
18
19
    public function __construct(string $abstractStateClass)
20
    {
21
        $this->abstractStateClass = $abstractStateClass;
22
    }
23
24
    public function nullable(): ValidStateRule
25
    {
26
        $this->nullable = true;
27
28
        return $this;
29
    }
30
31
    public function required(): ValidStateRule
32
    {
33
        $this->nullable = false;
34
35
        return $this;
36
    }
37
38
    public function passes($attribute, $value): bool
39
    {
40
        if ($this->nullable && $value === null) {
41
            return true;
42
        }
43
44
        $stateClass = $this->abstractStateClass::resolveStateClass($value);
45
46
        return is_subclass_of($stateClass, $this->abstractStateClass);
47
    }
48
49
    public function message(): string
50
    {
51
        return 'This value is invalid';
52
    }
53
}
54