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 8
8
* @author Petr Knap <dev@petrknap.cz>
9
9
* @since 2016-01-23
10
10
* @package PetrKnap\Php\Enum
11
- * @version 1.0.1
12
11
* @license https://github.com/petrknap/php-enum/blob/master/LICENSE MIT
13
12
*/
14
13
abstract class AbstractEnum
@@ -56,7 +55,7 @@ protected function __construct($memberName)
56
55
*
57
56
* @param string $memberName enum key
58
57
* @param array $args ignored
59
- * @return mixed
58
+ * @return self
60
59
*/
61
60
public static function __callStatic ($ memberName , array $ args )
62
61
{
@@ -155,4 +154,25 @@ private function get($memberName)
155
154
156
155
return self ::$ members [get_called_class ()][$ memberName ];
157
156
}
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
+ }
158
178
}
Original file line number Diff line number Diff line change @@ -78,4 +78,26 @@ public function testGetMembers()
78
78
$ this ->assertArrayHasKey ("MY_FALSE " , $ members );
79
79
$ this ->assertEquals (2 , $ members ["MY_FALSE " ]);
80
80
}
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
+ }
81
103
}
You can’t perform that action at this time.
0 commit comments