-
Notifications
You must be signed in to change notification settings - Fork 17
/
EnumBehavior.php
315 lines (275 loc) · 9.63 KB
/
EnumBehavior.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
<?php
declare(strict_types=1);
/**
* Copyright 2015 - 2023, Cake Development Corporation (http://cakedc.com)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2015 - 2023, Cake Development Corporation (http://cakedc.com)
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
namespace CakeDC\Enum\Model\Behavior;
use ArrayObject;
use BadMethodCallException;
use Cake\Event\EventInterface;
use Cake\ORM\Behavior;
use Cake\ORM\Query;
use Cake\ORM\RulesChecker;
use Cake\Utility\Hash;
use Cake\Utility\Inflector;
use CakeDC\Enum\Model\Behavior\Exception\MissingEnumConfigurationException;
use CakeDC\Enum\Model\Behavior\Exception\MissingEnumStrategyException;
use CakeDC\Enum\Model\Behavior\Strategy\ConfigStrategy;
use CakeDC\Enum\Model\Behavior\Strategy\ConstStrategy;
use CakeDC\Enum\Model\Behavior\Strategy\LookupStrategy;
use CakeDC\Enum\Model\Behavior\Strategy\StrategyInterface;
class EnumBehavior extends Behavior
{
/**
* Default configuration.
*
* - `defaultStrategy`: the default strategy to use.
* - `translate`: Whether values of lists returned by enum() method should
* be translated. Defaults to `false`.
* - `translationDomain`: Domain to use when translating list value.
* Defaults to "default".
* - `nested`: (bool) If `true` the array returned by enum() method will be of form
* `[['value' => 'v1', 'text' => 't1'], ['value' => 'v2', 'text' => 't2']`
* instead of default `['v1' => 't1', 'v2' => 't2']`.
* - `implementedMethods`: custom table methods made accessible by this behavior.
* - `lists`: the defined enumeration lists. Lists can use different strategies,
* use prefixes to differentiate them (defaults to the uppercased list name) and
* are persisted into a table's field (default to the underscored list name).
*
* Example:
*
* ```php
* $lists = [
* 'priority' => [
* 'strategy' => 'lookup',
* 'prefix' => 'PRIORITY',
* 'field' => 'priority',
* 'errorMessage' => 'Invalid priority',
* // Create application rule to ensure only valid enum value can be saved.
* 'applicationRules' => true,
* // Allow saving field without any enum value.
* 'allowEmpty' => false
* ],
* ];
* ```
*
* @var array
*/
protected array $_defaultConfig = [
'defaultStrategy' => 'lookup',
'translate' => false,
'translationDomain' => 'default',
'implementedMethods' => [
'enum' => 'enum',
],
'classMap' => [],
'lists' => [],
];
/**
* Class map.
*
* @var array
*/
protected array $classMap = [
'lookup' => LookupStrategy::class,
'const' => ConstStrategy::class,
'config' => ConfigStrategy::class,
];
/**
* Stack of strategies in use.
*
* @var array
*/
protected array $strategies = [];
/**
* Initializes the behavior.
*
* @param array $config Strategy's configuration.
* @return void
*/
public function initialize(array $config): void
{
parent::initialize($config);
$this->normalizeConfig();
}
/**
* Getter/setter for strategies.
*
* @param string $alias Strategy's alias.
* @param mixed $strategy Strategy name from the class map or some strategy instance.
* @return \CakeDC\Enum\Model\Behavior\Strategy\StrategyInterface
* @throws \CakeDC\Enum\Model\Behavior\Exception\MissingEnumStrategyException
*/
public function strategy(string $alias, mixed $strategy): StrategyInterface
{
if (!empty($this->strategies[$alias])) {
return $this->strategies[$alias];
}
$this->strategies[$alias] = $strategy;
if ($strategy instanceof StrategyInterface) {
return $strategy;
}
$class = null;
if (isset($this->classMap[$strategy])) {
$class = $this->classMap[$strategy];
}
if ($class === null || !class_exists($class)) {
throw new MissingEnumStrategyException([$class]);
}
return $this->strategies[$alias] = new $class($alias, $this->_table);
}
/**
* Normalizes the strategies configuration and initializes the strategies.
*
* @return void
*/
protected function normalizeConfig(): void
{
$classMap = $this->getConfig('classMap');
$this->classMap = array_merge($this->classMap, $classMap);
$lists = $this->getConfig('lists');
$defaultStrategy = $this->getConfig('defaultStrategy');
foreach ($lists as $alias => $config) {
if (is_numeric($alias)) {
unset($lists[$alias]);
$alias = $config;
$config = [];
$lists[$alias] = $config;
}
if (is_string($config)) {
$config = ['prefix' => strtoupper($config)];
}
if (empty($config['strategy'])) {
$config['strategy'] = $defaultStrategy;
}
$strategy = $this->strategy($alias, $config['strategy']);
$strategy->initialize($config);
$lists[$alias] = $strategy->getConfig();
}
$this->setConfig('lists', $lists, false);
}
/**
* @param array|string|null $alias Defined list's alias/name.
* @return array
* @throws \CakeDC\Enum\Model\Behavior\Exception\MissingEnumConfigurationException
*/
public function enum(array|string|null $alias = null): array
{
if (is_string($alias)) {
$config = $this->getConfig('lists.' . $alias);
if (empty($config)) {
throw new MissingEnumConfigurationException([$alias]);
}
return $this->enumList($alias, $config);
}
$lists = $this->getConfig('lists');
if (!empty($alias)) {
$lists = array_intersect_key($lists, array_flip($alias));
}
$return = [];
foreach ($lists as $alias => $config) {
$return[$alias] = $this->enumList($alias, $config);
}
return $return;
}
/**
* @param string $alias List alias.
* @param array $config Config
* @return array
*/
protected function enumList(string $alias, array $config): array
{
$return = $this->strategy($alias, $config['strategy'])->enum($config);
if ($this->getConfig('translate')) {
$return = $this->translate($return);
}
if ($this->getConfig('nested')) {
array_walk(
$return,
function (&$item, $val) {
$item = ['value' => $val, 'text' => $item];
}
);
$return = array_values($return);
}
return $return;
}
/**
* Translate list values.
*
* @param array $list List.
* @return array
*/
protected function translate(array $list): array
{
$domain = $this->getConfig('translationDomain');
return array_map(function ($value) use ($domain) {
return __d($domain, $value);
}, $list);
}
/**
* @param \Cake\Event\Event $event Event.
* @param \Cake\ORM\RulesChecker $rules Rules checker.
* @return \Cake\ORM\RulesChecker
*/
public function buildRules(EventInterface $event, RulesChecker $rules): RulesChecker
{
foreach ($this->getConfig('lists') as $alias => $config) {
if (Hash::get($config, 'applicationRules') === false) {
continue;
}
$ruleName = 'isValid' . Inflector::camelize($alias);
$rules->add([$this, $ruleName], $ruleName, [
'errorField' => $config['field'],
'message' => $config['errorMessage'],
]);
}
return $rules;
}
/**
* Universal validation rule for lists.
*
* @param string $method Method name.
* @param array $args Method's arguments.
* @return bool
* @throws \BadMethodCallException
* @throws \CakeDC\Enum\Model\Behavior\Exception\MissingEnumConfigurationException
*/
public function __call(string $method, array $args): bool
{
if (!str_starts_with($method, 'isValid')) {
throw new BadMethodCallException(sprintf('Call to undefined method (%s)', $method));
}
$alias = Inflector::underscore(str_replace('isValid', '', $method));
[$entity, ] = $args;
$config = $this->getConfig('lists.' . $alias);
if ($config === null) {
throw new MissingEnumConfigurationException([$alias]);
}
if (!$entity->has($config['field']) && Hash::get($config, 'allowEmpty') === true) {
return true;
}
return array_key_exists($entity->{$config['field']}, $this->enum($alias));
}
/**
* @param \Cake\Event\EventInterface $event The beforeFind event that was fired.
* @param \Cake\ORM\Query $query Query
* @param \ArrayObject $options The options for the query
* @return void
*/
public function beforeFind(EventInterface $event, Query $query, ArrayObject $options): void
{
foreach ($this->getConfig('lists') as $alias => $config) {
$strategy = $this->strategy($alias, $config['strategy']);
if (method_exists($strategy, 'beforeFind') && $strategy->getConfig('callBeforeFind')) {
$strategy->beforeFind($event, $query, $options);
}
}
}
}