Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- use InvalidArgumentException;
- abstract class Enum
- {
- protected $value;
- /**
- * The constructor is protected: use the static create method instead
- *
- * @param mixed $value
- */
- protected function __construct($value)
- {
- $this->value = $value;
- }
- /**
- * Instantiates a new Enum
- *
- * @param mixed $value
- * @return Enum
- */
- public static function create($value)
- {
- static::checkIsAcceptableValue($value);
- return new static($value);
- }
- /**
- * Instantiates a new Enum with the default value
- *
- * @param mixed $value
- * @return Enum
- */
- public static function createWithDefault()
- {
- return new static(static::getDefaultValue());
- }
- /**
- * Gets an array of the possible values
- *
- * @return array
- */
- public static function getPossibleValues()
- {
- throw new \Exception('This method should be implemented');
- }
- /**
- * Gets an array of the human representations indexed by possible values
- *
- * @return array
- */
- public static function getReadables()
- {
- throw new \Exception('This method should be implemented');
- }
- /**
- * Gets a default value
- *
- * @return value
- */
- public static function getDefaultValue()
- {
- return null;
- }
- /**
- * Gets the raw value
- *
- * @return mixed
- **/
- public function getValue()
- {
- return $this->value;
- }
- /**
- * Returns the human representation of the value
- *
- * @return string
- **/
- public function getReadable()
- {
- return static::getReadableFor($this->getValue());
- }
- /**
- * Tells is this value is acceptable
- *
- * @param mixed $value
- * @return boolean
- */
- public static function isAcceptableValue($value)
- {
- return in_array($value, static::getPossibleValues());
- }
- /**
- * Checks if this value is acceptable
- *
- * @throws InvalidArgumentException
- * @param mixed $value
- */
- public static function checkIsAcceptableValue($value)
- {
- if (!static::isAcceptableValue($value)) {
- throw new InvalidArgumentException($value.' is not an acceptable value');
- }
- }
- /**
- * Gets the human representation for a given value
- *
- * @return string
- **/
- public static function getReadableFor($value)
- {
- static::checkIsAcceptableValue($value);
- $humanRepresentations = static::getReadables();
- return array_search($value, $humanRepresentations);
- }
- /**
- * Converts to the human representation of the current value
- *
- * @return string
- **/
- public function __toString()
- {
- return (string) $this->getReadable();
- }
- }
Add Comment
Please, Sign In to add comment