Skip to content

Commit 60a7795

Browse files
committed
Implemented the possibility for PHP >= 5.3 calling a constant
to instantiate an enum with the called constant value.
1 parent 3596ccd commit 60a7795

File tree

2 files changed

+33
-0
lines changed

2 files changed

+33
-0
lines changed

src/MabeEnum/Enum.php

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -118,4 +118,26 @@ final public function __toString()
118118
{
119119
return (string) $this->value;
120120
}
121+
122+
/**
123+
* Instantiate an enum by a name of a constant.
124+
*
125+
* This will be called automatically on calling a method
126+
* with the same name of a defined constant.
127+
*
128+
* NOTE: THIS WORKS FOR PHP >= 5.3 ONLY
129+
*
130+
* @param string $const The name of the constant to instantiate the enum with
131+
* @param array $args There should be no arguments
132+
* @throws BadMethodCallException
133+
*/
134+
final public static function __callStatic($const, array $args)
135+
{
136+
$class = get_called_class();
137+
$classConst = $class . '::' . $const;
138+
if (!defined($classConst)) {
139+
throw new BadMethodCallException($classConst . ' not defined');
140+
}
141+
return new $class(constant($classConst));
142+
}
121143
}

tests/MabeEnumTest/EnumTest.php

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -88,4 +88,15 @@ public function testConstuctorNonStrictValue()
8888
$this->assertSame(2, $enum->getValue());
8989
$this->assertSame(1, $enum->getOrdinal());
9090
}
91+
92+
public function testInstantiateUsingMagicMethod()
93+
{
94+
if (version_compare(PHP_VERSION, '5.3', '<')) {
95+
$this->markTestSkipped("Instantiating using magic method doesn't work for PHP < 5.3");
96+
}
97+
98+
$enum = MabeEnumTest_TestAsset_EnumInheritance::ONE();
99+
$this->assertInstanceOf('MabeEnumTest_TestAsset_EnumInheritance', $enum);
100+
$this->assertSame(MabeEnumTest_TestAsset_EnumInheritance::ONE, $enum->getValue());
101+
}
91102
}

0 commit comments

Comments
 (0)