Enum::check()   B
last analyzed

Complexity

Conditions 7
Paths 4

Size

Total Lines 14
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 13.125

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 7
eloc 8
c 1
b 0
f 0
nc 4
nop 1
dl 0
loc 14
ccs 2
cts 4
cp 0.5
crap 13.125
rs 8.8333
1
<?php
2
3
/**
4
 * This file is part of Dimtrovich/Validation.
5
 *
6
 * (c) 2023 Dimitri Sitchet Tomkeu <[email protected]>
7
 *
8
 * For the full copyright and license information, please view
9
 * the LICENSE file that was distributed with this source code.
10
 */
11
12
namespace Dimtrovich\Validation\Rules;
13
14
use Rakit\Validation\Rule;
15
use TypeError;
16
17
class Enum extends AbstractRule
18
{
19
    /**
20
     * @param string $type Type de l'enumeration
21
     */
22
    public function __construct(protected string $type = '')
23
    {
24 132
        $this->type = $type;
25
    }
26
27
    /**
28
     * {@inheritDoc}
29
     */
30
    public function fillParameters(array $params): Rule
31
    {
32
        if (count($params) === 1 && is_string($params[0])) {
33 2
            $this->type = $params[0];
34
        }
35
36 2
        return $this;
37
    }
38
39
    /**
40
     * Modifie le type de l'enumeration
41
     */
42
    public function type(string $type): self
43
    {
44 2
        $this->type = $type;
45
46 2
        return $this;
47
    }
48
49
    /**
50
     * {@inheritDoc}
51
     */
52
    public function check($value): bool
53
    {
54
        if ($value instanceof $this->type) {
55
            return true;
56
        }
57
58
        if (empty($value) || ! function_exists('enum_exists') || ! enum_exists($this->type) || ! method_exists($this->type, 'tryFrom')) {
59 2
            return false;
60
        }
61
62
        try {
63 2
            return null !== $this->type::tryFrom($value);
64
        } catch (TypeError $e) {
65
            return false;
66
        }
67
    }
68
}
69