Skip to content
This repository was archived by the owner on Dec 26, 2023. It is now read-only.

Commit 56ae125

Browse files
author
Petr Knap
committed
Added findByValue method
1 parent 9df24ca commit 56ae125

File tree

2 files changed

+44
-1
lines changed

2 files changed

+44
-1
lines changed

src/Enum/AbstractEnum.php

Lines changed: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -56,7 +56,7 @@ protected function __construct($memberName)
5656
*
5757
* @param string $memberName enum key
5858
* @param array $args ignored
59-
* @return mixed
59+
* @return self
6060
*/
6161
public static function __callStatic($memberName, array $args)
6262
{
@@ -155,4 +155,25 @@ private function get($memberName)
155155

156156
return self::$members[get_called_class()][$memberName];
157157
}
158+
159+
/**
160+
* @param mixed $value
161+
* @return self
162+
* @throws EnumException
163+
*/
164+
public static function findByValue($value)
165+
{
166+
foreach (self::getMembers() as $n => $v) {
167+
if ($value === $v) {
168+
return self::__callStatic($n, []);
169+
}
170+
}
171+
throw new EnumException(
172+
sprintf(
173+
"Value not found in %s",
174+
get_called_class()
175+
),
176+
EnumException::OUT_OF_RANGE
177+
);
178+
}
158179
}

tests/Enum/EnumTest.php

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -78,4 +78,26 @@ public function testGetMembers()
7878
$this->assertArrayHasKey("MY_FALSE", $members);
7979
$this->assertEquals(2, $members["MY_FALSE"]);
8080
}
81+
82+
/**
83+
* @dataProvider dataFindByValue
84+
* @param mixed $value
85+
* @param mixed $expected
86+
*/
87+
public function testFindByValue($value, $expected)
88+
{
89+
if ($expected instanceof \Exception) {
90+
$this->setExpectedException(get_class($expected));
91+
}
92+
$this->assertSame($expected, MyBoolean::findByValue($value));
93+
}
94+
95+
public function dataFindByValue()
96+
{
97+
return [
98+
[1, MyBoolean::MY_TRUE()],
99+
[2, MyBoolean::MY_FALSE()],
100+
[3, new EnumException()]
101+
];
102+
}
81103
}

0 commit comments

Comments
 (0)