3 * The Enum base class for Enum functionality
7 * @category PHPCryptLib
9 * @author Anthony Ferrara <ircmaxell@ircmaxell.com>
10 * @copyright 2011 The Authors
11 * @license http://www.opensource.org/licenses/mit-license.html MIT License
12 * @version Build @@version@@
14 namespace CryptLib\Core
;
16 use \ReflectionObject
;
19 * The Enum base class for Enum functionality
21 * This is based off of the SplEnum class implementation (which is only available
22 * as a PECL extension in 5.3)
24 * @see http://www.php.net/manual/en/class.splenum.php
25 * @category PHPCryptLib
27 * @author Anthony Ferrara <ircmaxell@ircmaxell.com>
32 * A default value of null is provided. Override this to set your own default
34 const __DEFAULT
= null;
37 * @var string The name of the constant this instance is using
42 * @var scalar The value of the constant this instance is using.
44 protected $value = '';
47 * Creates a new value of the Enum type
49 * @param mixed $value The value this instance represents
50 * @param boolean $strict Not Implemented at this time
53 * @throws UnexpectedValueException If the value is not a constant
55 public function __construct($value = null, $strict = false) {
56 if (is_null($value)) {
57 $value = static::__DEFAULT
;
59 $validValues = $this->getConstList();
60 $this->name
= array_search($value, $validValues);
62 throw new \
UnexpectedValueException(
63 'Value not a const in enum ' . get_class($this)
66 $this->value
= $value;
70 * Cast the current object to a string and return its value
72 * @return mixed the current value of the instance
74 public function __toString() {
75 return (string) $this->value
;
79 * Compare two enums using numeric comparison
81 * @param Enum $arg The enum to compare this instance to
83 * @return int 0 if same, 1 if the argument is greater, -1 else
85 public function compare(Enum
$arg) {
86 if ($this->value
== $arg->value
) {
88 } elseif ($this->value
> $arg->value
) {
96 * Returns all constants (including values) as an associative array
98 * @param boolean $include_default Include the __default magic value?
100 * @return array All of the constants found against this instance
102 public function getConstList($include_default = false) {
103 static $constCache = array();
104 $class = get_class($this);
105 if (!isset($constCache[$class])) {
106 $reflector = new ReflectionObject($this);
107 $constCache[$class] = $reflector->getConstants();
109 if (!$include_default) {
110 $constants = $constCache[$class];
111 unset($constants['__DEFAULT']);
114 return $constCache[$class];