Completed
Pull Request — master (#19)
by
unknown
09:01
created

EnumRule::message()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 2
cts 2
cp 1
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 0
crap 1
1
<?php
2
3
namespace Nasyrov\Laravel\Enums\Rules;
4
5
use Illuminate\Contracts\Validation\Rule;
6
use Nasyrov\Laravel\Enums\Enum;
7
use ReflectionClass;
8
use InvalidArgumentException;
9
10
class EnumRule implements Rule
11
{
12
    /** @property string $enumClass */
13
    protected $enumClass;
14
15
    /**
16
    * @param string $enumClass Class of the enum to validate against
17
    */
18 6
    public function __construct(string $enumClass)
19
    {
20 6
        if (!$this->isEnumClass($enumClass)) {
21 2
            throw new InvalidArgumentException(
22 2
                $this->invalidEnumMessage($enumClass)
23
            );
24
        }
25
26 4
        $this->enumClass = $enumClass;
27 4
    }
28
29
    /**
30
     * Determine if the validation rule is an valid enum.
31
     *
32
     * @param string $attribute
33
     * @param mixed  $value
34
     *
35
     * @return bool
36
     */
37 4
    public function passes($attribute, $value): bool
38
    {
39 4
        $values = $this->enumClass::constants()->flip();
0 ignored issues
show
Bug introduced by
The method constants cannot be called on $this->enumClass (of type string).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
40
41 4
        return $values->has($value);
42
    }
43
44
    /**
45
     * Get the validation error message.
46
     *
47
     * @return string
48
     */
49 2
    public function message()
50
    {
51 2
        return 'The :attribute is not a valid value for the ' . Enum::class;
52
    }
53
54
    /**
55
     * Validate that the given class is an Enum
56
     *
57
     * @param string $enumClass
58
     *
59
     * @return bool
60
     */
61 6
    protected function isEnumClass(string $enumClass): bool
62
    {
63 6
        return !(!class_exists($enumClass)
64 6
            || !(new ReflectionClass($enumClass))->isSubclassOf(Enum::class));
65
    }
66
67
    /**
68
     * Pretty error message to indicate which class to implement
69
     *
70
     * @param string $enumClass
71
     *
72
     * @return string
73
     */
74 2
    protected function invalidEnumMessage(string $enumClass): string
75
    {
76 2
        return sprintf(
77 2
            '%s needs to be valid and implement %s for the EnumRule',
78 2
            $enumClass,
79 2
            Enum::class
80
        );
81
    }
82
}
83