<?php
/* Copyright (c) 2013, J.P.Westerhof <jurgen.westerhof@gmail.com>
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
*/
if(isset($_GET['show_source'])) {
show_source(__FILE__);
die();
}
if(!class_exists('ParseException')) {
class ParseException extends Exception {}
}
if(!class_exists('InvalidArgumentException')) {
class InvalidArgumentException extends Exception {}
}
if(!class_exists('CastException')) {
class CastException extends Exception {}
}
abstract class Enum {
private $value = null;
private $constants = null;
private static $errorMessage = '\'%s\' does not declare a value \'%s\'';
private function __CONSTRUCT($constantName = null) {
if($constantName != null) {
$this->constants = static::getConstantsByReflection();
if(!isset($this->constants[$constantName])) {
throw new InvalidArgumentException(sprintf(self::$errorMessage, get_class(new static()), $constantName));
}
$this->value = $constantName;
}
}
public static function __callStatic($name, $arguments) {
return new static($name);
}
public function __toString() {
return $this->value;
}
public function __invoke() {
return $this->constants[$this->value];
}
private static function getConstantsByReflection() {
$ref = new ReflectionClass(get_class(new static()));
return $ref->getConstants();
}
public static function getValues() {
$result = array();
foreach(static::getConstantsByReflection() as $k => $v) {
$result[] = new static($k);
}
return $result;
}
public static function tryParse($value, &$fruit) {
try {
$fruit = new static($value);
return true;
} catch(Exception $e) {}
$fruit = null;
return false;
}
public static function parse($value) {
try {
return new static($value);
} catch(Exception $e) {}
throw new ParseException(sprintf(self::$errorMessage, get_class(new static()), $value));
}
public static function cast($value) {
foreach(static::getConstantsByReflection() as $k => $v) {
if($v == $value) {
return new static($k);
}
}
throw new CastException(sprintf(self::$errorMessage, get_class(new static()), $value));
}
}