Skip to content

Add static values() method to return array of all Enum instances (fixes #18) #19

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
May 19, 2015
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,7 @@ Static methods:

- `toArray()` method Returns all possible values as an array (constant name in key, constant value in value)
- `keys()` Returns the names (keys) of all constants in the Enum class
- `values()` Returns instances of the Enum class of all Enum constants (constant name in key, Enum instance in value)
- `isValid()` Check if tested value is valid on enum set
- `isValidKey()` Check if tested key is valid on enum set
- `search()` Return key for searched value
Expand Down
16 changes: 16 additions & 0 deletions src/Enum.php
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,22 @@ public static function keys()
return array_keys(self::toArray());
}

/**
* Returns instances of the Enum class of all Enum constants
*
* @return array Constant name in key, Enum instance in value
*/
public static function values()
{
$values = array();

foreach (self::toArray() as $key => $value) {
$values[$key] = new static($value);
}

return $values;
}

/**
* Returns all possible values as an array
*
Expand Down
19 changes: 19 additions & 0 deletions tests/EnumTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,25 @@ public function testKeys()
$this->assertSame($expectedValues, $values);
}

/**
* values()
*/
public function testValues()
{
$values = EnumFixture::values();
$expectedValues = array(
"FOO" => new EnumFixture(EnumFixture::FOO),
"BAR" => new EnumFixture(EnumFixture::BAR),
"NUMBER" => new EnumFixture(EnumFixture::NUMBER),
"PROBLEMATIC_NUMBER" => new EnumFixture(EnumFixture::PROBLEMATIC_NUMBER),
"PROBLEMATIC_NULL" => new EnumFixture(EnumFixture::PROBLEMATIC_NULL),
"PROBLEMATIC_EMPTY_STRING" => new EnumFixture(EnumFixture::PROBLEMATIC_EMPTY_STRING),
"PROBLEMATIC_BOOLEAN_FALSE" => new EnumFixture(EnumFixture::PROBLEMATIC_BOOLEAN_FALSE),
);

$this->assertEquals($expectedValues, $values);
}

/**
* toArray()
*/
Expand Down