1+ <?php
2+
3+ namespace Kakadu \Yii2Enum ;
4+
5+ /**
6+ * Class Enum
7+ * @package Kakadu\Yii2Enum
8+ * @author Konstantin Timoshenko
9+ * @author Yarmaliuk Mikhail
10+ * @version 2.0
11+ *
12+ * @since 2.0 rename to Enum
13+ * @since 1.0 AbstractDictionary
14+ */
15+ abstract class Enum
16+ {
17+ /**
18+ * Default item
19+ *
20+ * @var array
21+ */
22+ protected static $ notSetMessage = ['app ' , 'Не указано ' ];
23+
24+ /**
25+ * Enum model attribute name
26+ *
27+ * @var string|NULL
28+ */
29+ protected static $ attribute = NULL ;
30+
31+ /**
32+ * Get all items
33+ *
34+ * @return array
35+ *
36+ * @since 2.0 not abstract
37+ * @since 1.0 abstract function
38+ */
39+ public static function all (): array
40+ {
41+ return [];
42+ }
43+
44+ /**
45+ * Enum constructor.
46+ *
47+ * @return void
48+ */
49+ private function __construct ()
50+ {
51+ }
52+
53+ /**
54+ * Get all items keys
55+ *
56+ * @return array
57+ */
58+ public static function keys (): array
59+ {
60+ return array_keys (static ::all ());
61+ }
62+
63+ /**
64+ * Get title by vendor
65+ *
66+ * @param mixed $key
67+ *
68+ * @return string|NULL
69+ */
70+ public static function get ($ key ): ?string
71+ {
72+ $ key = \is_object ($ key ) ? $ key ->{self ::$ attribute } : $ key ;
73+
74+ return static ::all ()[$ key ] ?? static ::getDefault ();
75+ }
76+
77+ /**
78+ * Get default item
79+ *
80+ * @return string
81+ */
82+ public static function getDefault (): string
83+ {
84+ [$ category , $ message ] = static ::$ notSetMessage ;
85+
86+ return \Yii::t ($ category , $ message );
87+ }
88+
89+ /**
90+ * If model attribute has key
91+ *
92+ * @param mixed $model
93+ * @param string|int $key
94+ *
95+ * @return bool
96+ */
97+ public static function has ($ model , $ key ): bool
98+ {
99+ if (is_object ($ model )) {
100+ if ($ attribute = static ::$ attribute ) {
101+ return $ model ->$ attribute == $ key ;
102+ }
103+ } else {
104+ return $ model == $ key ;
105+ }
106+
107+ return false ;
108+ }
109+
110+ /**
111+ * If model attribute has key in range
112+ *
113+ * @param mixed $model
114+ * @param array $keys
115+ *
116+ * @return bool
117+ */
118+ public static function hasIn ($ model , array $ keys ): bool
119+ {
120+ if (is_object ($ model )) {
121+ if ($ attribute = static ::$ attribute ) {
122+ return \in_array ($ model ->$ attribute , $ keys );
123+ }
124+ } else {
125+ return \in_array ($ model , $ keys );
126+ }
127+
128+ return false ;
129+ }
130+ }
0 commit comments