Completed
Push — master ( 9aa938...9d4d2d )
by Nate
02:20
created

AbstractEnum::equals()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 4
rs 10
cc 1
eloc 2
nc 1
nop 1
1
<?php
2
/*
3
 * Copyright (c) 2015 Nate Brunette.
4
 * Distributed under the MIT License (http://opensource.org/licenses/MIT)
5
 */
6
7
namespace Tebru\Enum;
8
9
use ArrayIterator;
10
use IteratorAggregate;
11
use RuntimeException;
12
13
/**
14
 * Class AbstractEnum
15
 *
16
 * @author Nate Brunette <[email protected]>
17
 */
18
abstract class AbstractEnum implements EnumInterface, IteratorAggregate
19
{
20
    /**
21
     * @var string
22
     */
23
    private $value;
24
25
    /**
26
     * Constructor
27
     *
28
     * @param string $value
29
     */
30
    public function __construct($value)
31
    {
32
        if (!static::exists($value)) {
33
            throw new RuntimeException(sprintf('%s is not a valid value for this enum.', $value));
34
        }
35
36
        $this->value = $value;
37
    }
38
39
    /**
40
     * Return the value as a string
41
     *
42
     * @return string
43
     */
44
    public function __toString()
45
    {
46
        return (string)$this->value;
47
    }
48
49
    /**
50
     * Do a comparison to check if the enums are non-strictly equal
51
     *
52
     * @param AbstractEnum $enum
53
     * @return bool
54
     */
55
    public function equals(AbstractEnum $enum)
56
    {
57
        return $this == $enum;
58
    }
59
60
    /**
61
     * Create a new instance of the enum
62
     *
63
     * @param string $value
64
     * @return $this
65
     */
66
    public static function create($value)
67
    {
68
        return new static($value);
69
    }
70
71
    /**
72
     * Return true if the value is valid for the enum
73
     *
74
     * @param string $value
75
     * @return bool
76
     */
77
    public static function exists($value)
78
    {
79
        return in_array($value, static::values());
80
    }
81
82
    /**
83
     * Get an array of the enum values
84
     *
85
     * @return array
86
     */
87
    public static function values()
88
    {
89
        return array_values(static::getConstants());
90
    }
91
92
    /**
93
     * Return enum as an array with keys matching values
94
     *
95
     * @return array
96
     */
97
    public static function toArray()
98
    {
99
        return array_combine(self::values(), self::values());
100
    }
101
102
    /**
103
     * Get the current enum value
104
     *
105
     * @return string
106
     */
107
    public function getValue()
108
    {
109
        return $this->value;
110
    }
111
112
    /**
113
     * Return the values to be used in a loop
114
     *
115
     * @return array
116
     */
117
    public function getIterator()
118
    {
119
        return new ArrayIterator(static::values());
120
    }
121
}
122