Created
January 18, 2016 22:39
-
-
Save victorjonsson/e47d5c4a7f403933e2fe to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* | |
* @example | |
* <?php | |
* | |
* class Day extends EnumeratedType | |
* { | |
* const MONDAY = 'Monday'; | |
* const TUEASDAY = 'Tuesday'; | |
* const WEDENESDAY = 'Wednesday'; | |
* const THURSDAY = 'Thursday'; | |
* const FRIDAY = 'Friday'; | |
* const SATURDAY = 'Saturday'; | |
* const SUNDAY = 'Sunday'; | |
* } | |
* | |
* $day = new Day(Day::MONDAY); | |
* assert($day->is(Day::MONDAY), 'Created day is Monday'); | |
* | |
* class FavouriteColor extends EnumeratedType { | |
* | |
* const GREEN = 9001; | |
* const BLUE = 9002; | |
* const YELLOW = 9003; | |
* const PINK = 9004; | |
* | |
* const _DEFAULT = self::PINK; | |
* } | |
* | |
*/ | |
abstract class EnumeratedType | |
{ | |
const _DEFAULT = ''; | |
/** @var string|int */ | |
protected $value; | |
/** | |
* @param string|int $value | |
*/ | |
final public function __constuct($value=null) | |
{ | |
$this->value = $value === null ? static::_DEFAULT : $value; | |
if (!$this->hasValue($value)) { | |
throw new \InvalidArgumentException('Trying to construct object '.static::class.' with undeclared value'); | |
} | |
} | |
/** | |
* @param string|int $value | |
* @return bool | |
*/ | |
public function is($value) | |
{ | |
return $this->value == $value; | |
} | |
/** | |
* @return string|int | |
*/ | |
public function getValue() | |
{ | |
return $this->value; | |
} | |
/** | |
* @return string | |
*/ | |
public function __toString() | |
{ | |
return (string)$this->value; | |
} | |
/** @var array */ | |
private static $constants = []; | |
/** | |
* @return bool | |
*/ | |
private function hasValue($value) | |
{ | |
$className = static::class; | |
if (!isset(self::$constants[$className])) { | |
$reflection = new \ReflectionClass($className); | |
self::$constants[$className] = $reflection->getConstants(); | |
} | |
return in_array(self::$constants[$className], $value); | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment