Passed
Push — master ( 5bcbab...45e395 )
by Roman
01:36
created

EnumValidator::validateValue()   A

Complexity

Conditions 5
Paths 8

Size

Total Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 8
rs 9.6111
c 0
b 0
f 0
cc 5
nc 8
nop 1
1
<?php
2
/**
3
 * @author Roman Varkuta <[email protected]>
4
 * @license MIT
5
 * @see https://github.com/myclabs/php-enum PHP enum implementation
6
 * @version 1.0
7
 */
8
9
declare(strict_types=1);
10
11
namespace Kartavik\Yii2\Validators;
12
13
use MyCLabs\Enum\Enum;
14
use yii\validators;
15
16
/**
17
 * Class EnumValidator
18
 *
19
 * ```php
20
 * public function rules(): array
21
 * {
22
 *      return [
23
 *          [
24
 *              ['attribute1', 'attribute2'],
25
 *              Kartavik\Yii2\Validators\EnumValidator::class,
26
 *              'targetEnum' => YourEnum::class
27
 *          ]
28
 *      ]
29
 * }
30
 * ```
31
 *
32
 * @package Kartavik\Yii2\Validators
33
 * @since 1.0
34
 */
35
class EnumValidator extends validators\Validator
36
{
37
    /** @var string|Enum */
38
    public $targetEnum;
39
40
    /** @var bool */
41
    public $useKey = false;
42
43
    /**
44
     * @param mixed $value
45
     * @return array|null
46
     */
47
    protected function validateValue($value): ?array
48
    {
49
        $valid = $value instanceof $this->targetEnum
50
            || $this->useKey && $this->targetEnum::isValidKey($value)
51
            || $this->targetEnum::isValid($value);
52
53
        return !$valid ? [$this->getMessage(), []] : \null;
54
    }
55
56
    /**
57
     * @return string
58
     */
59
    public function getMessage(): string
60
    {
61
        return \Yii::t(static::class, "Attribute [{attribute}] must be instance or be part of {$this->targetEnum}");
62
    }
63
}
64