Skip to content

Instantly share code, notes, and snippets.

@victorjonsson
Created January 18, 2016 22:39
Show Gist options
  • Save victorjonsson/e47d5c4a7f403933e2fe to your computer and use it in GitHub Desktop.
Save victorjonsson/e47d5c4a7f403933e2fe to your computer and use it in GitHub Desktop.
<?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