Skip to content

Commit 7c4cd65

Browse files
committed
Merge pull request #19 from chriseskow/values
Add static values() method to return array of all Enum instances (fixes #18)
2 parents b5ca36f + 718d333 commit 7c4cd65

File tree

3 files changed

+36
-0
lines changed

3 files changed

+36
-0
lines changed

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -62,6 +62,7 @@ Static methods:
6262

6363
- `toArray()` method Returns all possible values as an array (constant name in key, constant value in value)
6464
- `keys()` Returns the names (keys) of all constants in the Enum class
65+
- `values()` Returns instances of the Enum class of all Enum constants (constant name in key, Enum instance in value)
6566
- `isValid()` Check if tested value is valid on enum set
6667
- `isValidKey()` Check if tested key is valid on enum set
6768
- `search()` Return key for searched value

src/Enum.php

+16
Original file line numberDiff line numberDiff line change
@@ -83,6 +83,22 @@ public static function keys()
8383
return array_keys(self::toArray());
8484
}
8585

86+
/**
87+
* Returns instances of the Enum class of all Enum constants
88+
*
89+
* @return array Constant name in key, Enum instance in value
90+
*/
91+
public static function values()
92+
{
93+
$values = array();
94+
95+
foreach (self::toArray() as $key => $value) {
96+
$values[$key] = new static($value);
97+
}
98+
99+
return $values;
100+
}
101+
86102
/**
87103
* Returns all possible values as an array
88104
*

tests/EnumTest.php

+19
Original file line numberDiff line numberDiff line change
@@ -98,6 +98,25 @@ public function testKeys()
9898
$this->assertSame($expectedValues, $values);
9999
}
100100

101+
/**
102+
* values()
103+
*/
104+
public function testValues()
105+
{
106+
$values = EnumFixture::values();
107+
$expectedValues = array(
108+
"FOO" => new EnumFixture(EnumFixture::FOO),
109+
"BAR" => new EnumFixture(EnumFixture::BAR),
110+
"NUMBER" => new EnumFixture(EnumFixture::NUMBER),
111+
"PROBLEMATIC_NUMBER" => new EnumFixture(EnumFixture::PROBLEMATIC_NUMBER),
112+
"PROBLEMATIC_NULL" => new EnumFixture(EnumFixture::PROBLEMATIC_NULL),
113+
"PROBLEMATIC_EMPTY_STRING" => new EnumFixture(EnumFixture::PROBLEMATIC_EMPTY_STRING),
114+
"PROBLEMATIC_BOOLEAN_FALSE" => new EnumFixture(EnumFixture::PROBLEMATIC_BOOLEAN_FALSE),
115+
);
116+
117+
$this->assertEquals($expectedValues, $values);
118+
}
119+
101120
/**
102121
* toArray()
103122
*/

0 commit comments

Comments
 (0)