Skip to content

Commit

Permalink
Always return the same instance of a const
Browse files Browse the repository at this point in the history
Implement EnumManager to keep track of all instances
  • Loading branch information
adrium committed Jan 30, 2017
1 parent e42fa9d commit 5eca803
Show file tree
Hide file tree
Showing 3 changed files with 74 additions and 4 deletions.
24 changes: 20 additions & 4 deletions src/Enum.php
Original file line number Diff line number Diff line change
Expand Up @@ -165,6 +165,21 @@ public static function search($value)
return array_search($value, static::toArray(), true);
}

/**
* Returns Enum by key
*
* @return static
*/
public static function fromKey($name)
{
$array = static::toArray();
if (array_key_exists($name, $array)) {
return EnumManager::get(new static($array[$name]));
}

return null;
}

/**
* Returns a value when called statically like so: MyEnum::SOME_VALUE() given SOME_VALUE is a class constant
*
Expand All @@ -176,11 +191,12 @@ public static function search($value)
*/
public static function __callStatic($name, $arguments)
{
$array = static::toArray();
if (isset($array[$name])) {
return new static($array[$name]);
$result = static::fromKey($name);

if ($result === null) {
throw new \BadMethodCallException("No static method or enum constant '$name' in class " . get_called_class());
}

throw new \BadMethodCallException("No static method or enum constant '$name' in class " . get_called_class());
return $result;
}
}
43 changes: 43 additions & 0 deletions src/EnumManager.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
<?php
/**
* @link http://github.com/myclabs/php-enum
* @license http://www.opensource.org/licenses/mit-license.php MIT (see the LICENSE file)
*/

namespace MyCLabs\Enum;

use ReflectionObject;

/**
* Enum instance manager
*
* @internal
*/
abstract class EnumManager
{
/**
* Store existing Enum instances.
*
* @var array
*/
private static $instances = array();

/**
* Returns the Enum instance for the given prototype
*
* @return Enum
*/
public static function get(Enum $enum)
{
$reflection = new ReflectionObject($enum);
$class = $reflection->getName();
$name = $enum->getKey();

if (isset(self::$instances[$class][$name])) {
return self::$instances[$class][$name];
}

self::$instances[$class][$name] = $enum;
return $enum;
}
}
11 changes: 11 additions & 0 deletions tests/EnumTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -228,6 +228,17 @@ public function testEquals()
$this->assertTrue($foo->equals($anotherFoo));
}

/**
* __callStatic()
*/
public function testSameInstance()
{
$foo1 = EnumFixture::FOO();
$foo2 = EnumFixture::FOO();

$this->assertSame($foo1, $foo2);
}

/**
* equals()
*/
Expand Down

0 comments on commit 5eca803

Please sign in to comment.