Skip to content

Commit ded1c64

Browse files
committed
Add static values() method to return array of all Enum instances (fixes #18)
1 parent b5ca36f commit ded1c64

File tree

3 files changed

+32
-0
lines changed

3 files changed

+32
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
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

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -83,6 +83,18 @@ 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+
return array_map(function ($value) {
94+
return new static($value);
95+
}, self::toArray());
96+
}
97+
8698
/**
8799
* Returns all possible values as an array
88100
*

tests/EnumTest.php

Lines changed: 19 additions & 0 deletions
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)