Passed
Branch main (4c8529)
by Tan
28:05
created

InteractionTypeEnum::isValid()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 11
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 1 Features 2
Metric Value
eloc 5
c 2
b 1
f 2
dl 0
loc 11
rs 10
cc 3
nc 3
nop 1
1
<?php
2
3
namespace CSlant\LaravelLike\Enums;
4
5
enum InteractionTypeEnum: string
6
{
7
    case NEUTRAL = 'neutral';
8
    case LIKE = 'like';
9
    case DISLIKE = 'dislike';
10
    case LOVE = 'love';
11
12
    /**
13
     * Get the values of the enum.
14
     *
15
     * @return array<int, InteractionTypeEnum>
16
     */
17
    public static function getValues(): array
18
    {
19
        return [
20
            self::LIKE,
21
            self::DISLIKE,
22
            self::LOVE,
23
        ];
24
    }
25
26
    /**
27
     * Get the values of the enum as strings.
28
     *
29
     * @return array<string>
30
     */
31
    public static function getValuesAsStrings(): array
32
    {
33
        return [
34
            self::LIKE->value,
35
            self::DISLIKE->value,
36
            self::LOVE->value,
37
        ];
38
    }
39
40
    /**
41
     * Check if the value is like.
42
     *
43
     * @return bool
44
     */
45
    public function isLike(): bool
46
    {
47
        return $this === self::LIKE;
48
    }
49
50
    /**
51
     * Check if the value is dislike.
52
     *
53
     * @return bool
54
     */
55
    public function isDislike(): bool
56
    {
57
        return $this === self::DISLIKE;
58
    }
59
60
    /**
61
     * Check if the value is love.
62
     *
63
     * @return bool
64
     */
65
    public function isLove(): bool
66
    {
67
        return $this === self::LOVE;
68
    }
69
70
    /**
71
     * Get the type by value.
72
     * This method can be used to get the value of InteractionTypeEnum based on the passed string.
73
     * You can use it to convert string value to enum value.
74
     *
75
     * @param  string  $value
76
     *
77
     * @return InteractionTypeEnum
78
     */
79
    public static function getTypeByValue(string $value): InteractionTypeEnum
80
    {
81
        return match ($value) {
82
            self::LIKE->value => self::LIKE,
83
            self::DISLIKE->value => self::DISLIKE,
84
            self::LOVE->value => self::LOVE,
85
            default => self::NEUTRAL,
86
        };
87
    }
88
89
    /**
90
     * Check if the value is valid.
91
     *
92
     * @param  null|InteractionTypeEnum|string  $value
93
     *
94
     * @return bool
95
     */
96
    public static function isValid(InteractionTypeEnum|string|null $value = null): bool
97
    {
98
        if ($value === null) {
99
            return false;
100
        }
101
102
        if ($value instanceof InteractionTypeEnum) {
103
            $value = $value->value;
104
        }
105
106
        return in_array($value, self::getValuesAsStrings());
107
    }
108
}
109