EnumValidator   A
last analyzed

Complexity

Total Complexity 6

Size/Duplication

Total Lines 29
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 2

Importance

Changes 0
Metric Value
wmc 6
lcom 1
cbo 2
dl 0
loc 29
rs 10
c 0
b 0
f 0

2 Methods

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