1+ <?php
2+ declare (strict_types = 1 );
3+ namespace Forensic \FeedParser \Enums ;
4+
5+ use ReflectionClass ;
6+ use Forensic \FeedParser \Exceptions \UnexpectedValueException ;
7+
8+ class BaseEnum
9+ {
10+ const __default = null ;
11+
12+ protected $ _value = null ;
13+
14+ /**
15+ *@param mixed [$value] - the instance value
16+ *@param boolean [$strict=true] - boolean indicating if value comparison should be strict
17+ */
18+ public function __construct ($ value = null , bool $ strict = true )
19+ {
20+ $ resolved_value = null ;
21+ $ const_list = $ this ->getConstList (true );
22+ if (is_null ($ value ) && array_key_exists ('__default ' , $ const_list ))
23+ {
24+ $ resolved_value = $ const_list ['__default ' ];
25+ }
26+ else if (!is_null ($ value ))
27+ {
28+ foreach ($ const_list as $ const_key => $ const_value )
29+ {
30+ if (($ strict && $ const_value === $ value ) || (!$ strict && $ const_value == $ value ))
31+ {
32+ $ resolved_value = $ const_value ;
33+ break ;
34+ }
35+ }
36+ }
37+
38+ if (is_null ($ resolved_value ))
39+ throw new UnexpectedValueException ('unknown enum value ' );
40+ else
41+ $ this ->_value = $ resolved_value ;
42+ }
43+
44+ /**
45+ * returns array of enum constants
46+ *
47+ *@param boolean [$include_default=false] - boolean value indicating if it should include
48+ * the class default enum constant
49+ *@return array
50+ */
51+ public function getConstList (bool $ include_default = false )
52+ {
53+ $ reflector = new ReflectionClass (get_class ($ this ));
54+ $ const_list = $ reflector ->getConstants ();
55+
56+ if (!$ include_default && array_key_exists ('__default ' , $ const_list ))
57+ unset($ const_list ['__default ' ]);
58+
59+ return $ const_list ;
60+ }
61+
62+ /**
63+ *@return mixed
64+ */
65+ public function value ()
66+ {
67+ return $ this ->_value ;
68+ }
69+
70+ /**
71+ *@return string
72+ */
73+ public function __toString ()
74+ {
75+ return strval ($ this ->_value );
76+ }
77+ }
0 commit comments