Completed
Pull Request — master (#12)
by
unknown
12:12
created

EnumRule::passes()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 6
ccs 3
cts 3
cp 1
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 3
nc 1
nop 2
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->validateEnumClass($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
        $enumClassName = explode('\\', $this->enumClass);
52
53 2
        return 'The :attribute it not a valid value for the ' . array_pop($enumClassName);
54
    }
55
56
    /**
57
     * Validate that the given class is an Enum
58
     *
59
     * @param string $enumClass
60
     *
61
     * @return bool
62
     */
63 6
    protected function validateEnumClass(string $enumClass): bool
64
    {
65 6
        return !class_exists($enumClass)
66 6
            || !(new ReflectionClass($enumClass))->isSubclassOf(Enum::class);
67
    }
68
69
    /**
70
     * Pretty error message to indicate which class to implement
71
     *
72
     * @param string $enumClass
73
     *
74
     * @return string
75
     */
76 2
    protected function invalidEnumMessage(string $enumClass): string
77
    {
78 2
        return sprintf(
79 2
            '%s needs to be valid and implement %s for the EnumRule',
80 2
            $enumClass,
81 2
            Enum::class
82
        );
83
    }
84
}
85