File tree Expand file tree Collapse file tree 3 files changed +75
-4
lines changed
Expand file tree Collapse file tree 3 files changed +75
-4
lines changed Original file line number Diff line number Diff line change @@ -165,6 +165,21 @@ public static function search($value)
165165 return array_search ($ value , static ::toArray (), true );
166166 }
167167
168+ /**
169+ * Returns Enum by key
170+ *
171+ * @return static
172+ */
173+ public static function fromKey ($ name )
174+ {
175+ $ array = static ::toArray ();
176+ if (array_key_exists ($ name , $ array )) {
177+ return EnumManager::get (new static ($ array [$ name ]));
178+ }
179+
180+ return null ;
181+ }
182+
168183 /**
169184 * Returns a value when called statically like so: MyEnum::SOME_VALUE() given SOME_VALUE is a class constant
170185 *
@@ -176,11 +191,13 @@ public static function search($value)
176191 */
177192 public static function __callStatic ($ name , $ arguments )
178193 {
179- $ array = static ::toArray ();
180- if (isset ($ array [$ name ])) {
181- return new static ($ array [$ name ]);
194+ $ result = static ::fromKey ($ name );
195+
196+ if ($ result === null ) {
197+ $ msg = "No static method or enum constant ' $ name' in class " . get_called_class ();
198+ throw new \BadMethodCallException ($ msg );
182199 }
183200
184- throw new \ BadMethodCallException ( " No static method or enum constant ' $ name ' in class " . get_called_class ()) ;
201+ return $ result ;
185202 }
186203}
Original file line number Diff line number Diff line change 1+ <?php
2+ /**
3+ * @link http://github.com/myclabs/php-enum
4+ * @license http://www.opensource.org/licenses/mit-license.php MIT (see the LICENSE file)
5+ */
6+
7+ namespace MyCLabs \Enum ;
8+
9+ use ReflectionObject ;
10+
11+ /**
12+ * Enum instance manager
13+ *
14+ * @internal
15+ */
16+ abstract class EnumManager
17+ {
18+ /**
19+ * Store existing Enum instances.
20+ *
21+ * @var array
22+ */
23+ private static $ instances = array ();
24+
25+ /**
26+ * Returns the Enum instance for the given prototype
27+ *
28+ * @return Enum
29+ */
30+ public static function get (Enum $ enum )
31+ {
32+ $ reflection = new ReflectionObject ($ enum );
33+ $ class = $ reflection ->getName ();
34+ $ name = $ enum ->getKey ();
35+
36+ if (isset (self ::$ instances [$ class ][$ name ])) {
37+ return self ::$ instances [$ class ][$ name ];
38+ }
39+
40+ self ::$ instances [$ class ][$ name ] = $ enum ;
41+ return $ enum ;
42+ }
43+ }
Original file line number Diff line number Diff line change @@ -225,6 +225,17 @@ public function testEquals()
225225 $ this ->assertTrue ($ foo ->equals ($ anotherFoo ));
226226 }
227227
228+ /**
229+ * __callStatic()
230+ */
231+ public function testSameInstance ()
232+ {
233+ $ foo1 = EnumFixture::FOO ();
234+ $ foo2 = EnumFixture::FOO ();
235+
236+ $ this ->assertSame ($ foo1 , $ foo2 );
237+ }
238+
228239 /**
229240 * equals()
230241 */
You can’t perform that action at this time.
0 commit comments