This repository was archived by the owner on Dec 26, 2023. It is now read-only.
File tree Expand file tree Collapse file tree 2 files changed +44
-2
lines changed Expand file tree Collapse file tree 2 files changed +44
-2
lines changed Original file line number Diff line number Diff line change 88 * @author Petr Knap <dev@petrknap.cz>
99 * @since 2016-01-23
1010 * @package PetrKnap\Php\Enum
11- * @version 1.0.1
1211 * @license https://github.com/petrknap/php-enum/blob/master/LICENSE MIT
1312 */
1413abstract class AbstractEnum
@@ -56,7 +55,7 @@ protected function __construct($memberName)
5655 *
5756 * @param string $memberName enum key
5857 * @param array $args ignored
59- * @return mixed
58+ * @return self
6059 */
6160 public static function __callStatic ($ memberName , array $ args )
6261 {
@@ -155,4 +154,25 @@ private function get($memberName)
155154
156155 return self ::$ members [get_called_class ()][$ memberName ];
157156 }
157+
158+ /**
159+ * @param mixed $value
160+ * @return self
161+ * @throws EnumException
162+ */
163+ public static function findByValue ($ value )
164+ {
165+ foreach (self ::getMembers () as $ n => $ v ) {
166+ if ($ value === $ v ) {
167+ return self ::__callStatic ($ n , []);
168+ }
169+ }
170+ throw new EnumException (
171+ sprintf (
172+ "Value not found in %s " ,
173+ get_called_class ()
174+ ),
175+ EnumException::OUT_OF_RANGE
176+ );
177+ }
158178}
Original file line number Diff line number Diff 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}
You can’t perform that action at this time.
0 commit comments