REBELinBLUE
3/14/2017 - 10:26 AM

enum.php

<?php

abstract class Enum
{
    protected $value;

    /**
     * @param $checkValue
     * @return bool
     */
    public function isValidEnumValue($checkValue): bool
    {
        $reflector = new ReflectionClass(get_class($this));
        foreach ($reflector->getConstants() as $validValue) {
            if ($validValue == $checkValue) {
                return true;
            }
        }
        
        return false;
    }

    /**
     * @param $value
     * @throws \Exception
     */
    function __construct($value)
    {
        if (!$this->isValidEnumValue($value)) {
            throw new \Exception('Invalid enum value: ' . $value);
        }

        $this->value = $value;
    }

    /**
     * @param $property
     * @return mixed
     */
    function __get(string $property)
    {
        return $this->value;
    }

    /**
     * @return string
     */
    function __toString(): string
    {
        return (string) $this->value;
    }
}