-
-
Notifications
You must be signed in to change notification settings - Fork 6.9k
/
DataFilter.php
841 lines (772 loc) · 27.5 KB
/
DataFilter.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
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
<?php
/**
* @link https://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license https://www.yiiframework.com/license/
*/
namespace yii\data;
use Yii;
use yii\base\InvalidConfigException;
use yii\base\Model;
use yii\helpers\ArrayHelper;
use yii\validators\BooleanValidator;
use yii\validators\EachValidator;
use yii\validators\NumberValidator;
use yii\validators\StringValidator;
use yii\validators\DateValidator;
use yii\validators\Validator;
/**
* DataFilter is a special [[Model]] for processing query filtering specification.
* It allows validating and building a filter condition passed via request.
*
* Filter example:
*
* ```json
* {
* "or": [
* {
* "and": [
* {
* "name": "some name",
* },
* {
* "price": "25",
* }
* ]
* },
* {
* "id": {"in": [2, 5, 9]},
* "price": {
* "gt": 10,
* "lt": 50
* }
* }
* ]
* }
* ```
*
* In the request the filter should be specified using a key name equal to [[filterAttributeName]]. Thus actual HTTP request body
* will look like following:
*
* ```json
* {
* "filter": {"or": {...}},
* "page": 2,
* ...
* }
* ```
*
* Raw filter value should be assigned to [[filter]] property of the model.
* You may populate it from request data via [[load()]] method:
*
* ```php
* use yii\data\DataFilter;
*
* $dataFilter = new DataFilter();
* $dataFilter->load(Yii::$app->request->getBodyParams());
* ```
*
* In order to function this class requires a search model specified via [[searchModel]]. This search model should declare
* all available search attributes and their validation rules. For example:
*
* ```php
* class SearchModel extends \yii\base\Model
* {
* public $id;
* public $name;
*
* public function rules()
* {
* return [
* [['id', 'name'], 'trim'],
* ['id', 'integer'],
* ['name', 'string'],
* ];
* }
* }
* ```
*
* In order to reduce amount of classes, you may use [[\yii\base\DynamicModel]] instance as a [[searchModel]].
* In this case you should specify [[searchModel]] using a PHP callable:
*
* ```php
* function () {
* return (new \yii\base\DynamicModel(['id' => null, 'name' => null]))
* ->addRule(['id', 'name'], 'trim')
* ->addRule('id', 'integer')
* ->addRule('name', 'string');
* }
* ```
*
* You can use [[validate()]] method to check if filter value is valid. If validation fails you can use
* [[getErrors()]] to get actual error messages.
*
* In order to acquire filter condition suitable for fetching data use [[build()]] method.
*
* > Note: This is a base class. Its implementation of [[build()]] simply returns normalized [[filter]] value.
* In order to convert filter to particular format you should use descendant of this class that implements
* [[buildInternal()]] method accordingly.
*
* @see ActiveDataFilter
*
* @property array $errorMessages Error messages in format `[errorKey => message]`. Note that the type of this
* property differs in getter and setter. See [[getErrorMessages()]] and [[setErrorMessages()]] for details.
* @property mixed $filter Raw filter value.
* @property array $searchAttributeTypes Search attribute type map. Note that the type of this property
* differs in getter and setter. See [[getSearchAttributeTypes()]] and [[setSearchAttributeTypes()]] for details.
* @property Model $searchModel Model instance. Note that the type of this property differs in getter and
* setter. See [[getSearchModel()]] and [[setSearchModel()]] for details.
*
* @author Paul Klimov <klimov.paul@gmail.com>
* @since 2.0.13
*/
class DataFilter extends Model
{
const TYPE_INTEGER = 'integer';
const TYPE_FLOAT = 'float';
const TYPE_BOOLEAN = 'boolean';
const TYPE_STRING = 'string';
const TYPE_ARRAY = 'array';
const TYPE_DATETIME = 'datetime';
const TYPE_DATE = 'date';
const TYPE_TIME = 'time';
/**
* @var string name of the attribute that handles filter value.
* The name is used to load data via [[load()]] method.
*/
public $filterAttributeName = 'filter';
/**
* @var string label for the filter attribute specified via [[filterAttributeName]].
* It will be used during error messages composition.
*/
public $filterAttributeLabel;
/**
* @var array keywords or expressions that could be used in a filter.
* Array keys are the expressions used in raw filter value obtained from user request.
* Array values are internal build keys used in this class methods.
*
* Any unspecified keyword will not be recognized as a filter control and will be treated as
* an attribute name. Thus you should avoid conflicts between control keywords and attribute names.
* For example: in case you have control keyword 'like' and an attribute named 'like', specifying condition
* for such attribute will be impossible.
*
* You may specify several keywords for the same filter build key, creating multiple aliases. For example:
*
* ```php
* [
* 'eq' => '=',
* '=' => '=',
* '==' => '=',
* '===' => '=',
* // ...
* ]
* ```
*
* > Note: while specifying filter controls take actual data exchange format, which your API uses, in mind.
* > Make sure each specified control keyword is valid for the format. For example, in XML tag name can start
* > only with a letter character, thus controls like `>`, '=' or `$gt` will break the XML schema.
*/
public $filterControls = [
'and' => 'AND',
'or' => 'OR',
'not' => 'NOT',
'lt' => '<',
'gt' => '>',
'lte' => '<=',
'gte' => '>=',
'eq' => '=',
'neq' => '!=',
'in' => 'IN',
'nin' => 'NOT IN',
'like' => 'LIKE',
];
/**
* @var array maps filter condition keywords to validation methods.
* These methods are used by [[validateCondition()]] to validate raw filter conditions.
*/
public $conditionValidators = [
'AND' => 'validateConjunctionCondition',
'OR' => 'validateConjunctionCondition',
'NOT' => 'validateBlockCondition',
'<' => 'validateOperatorCondition',
'>' => 'validateOperatorCondition',
'<=' => 'validateOperatorCondition',
'>=' => 'validateOperatorCondition',
'=' => 'validateOperatorCondition',
'!=' => 'validateOperatorCondition',
'IN' => 'validateOperatorCondition',
'NOT IN' => 'validateOperatorCondition',
'LIKE' => 'validateOperatorCondition',
];
/**
* @var array specifies the list of supported search attribute types per each operator.
* This field should be in format: 'operatorKeyword' => ['type1', 'type2' ...].
* Supported types list can be specified as `*`, which indicates that operator supports all types available.
* Any unspecified keyword will not be considered as a valid operator.
*/
public $operatorTypes = [
'<' => [self::TYPE_INTEGER, self::TYPE_FLOAT, self::TYPE_DATETIME, self::TYPE_DATE, self::TYPE_TIME],
'>' => [self::TYPE_INTEGER, self::TYPE_FLOAT, self::TYPE_DATETIME, self::TYPE_DATE, self::TYPE_TIME],
'<=' => [self::TYPE_INTEGER, self::TYPE_FLOAT, self::TYPE_DATETIME, self::TYPE_DATE, self::TYPE_TIME],
'>=' => [self::TYPE_INTEGER, self::TYPE_FLOAT, self::TYPE_DATETIME, self::TYPE_DATE, self::TYPE_TIME],
'=' => '*',
'!=' => '*',
'IN' => '*',
'NOT IN' => '*',
'LIKE' => [self::TYPE_STRING],
];
/**
* @var array list of operators keywords, which should accept multiple values.
*/
public $multiValueOperators = [
'IN',
'NOT IN',
];
/**
* @var array actual attribute names to be used in searched condition, in format: [filterAttribute => actualAttribute].
* For example, in case of using table joins in the search query, attribute map may look like the following:
*
* ```php
* [
* 'authorName' => '{{author}}.[[name]]'
* ]
* ```
*
* Attribute map will be applied to filter condition in [[normalize()]] method.
*/
public $attributeMap = [];
/**
* @var string representation of `null` instead of literal `null` in case the latter cannot be used.
* @since 2.0.40
*/
public $nullValue = 'NULL';
/**
* @var array|\Closure list of error messages responding to invalid filter structure, in format: `[errorKey => message]`.
*/
private $_errorMessages;
/**
* @var mixed raw filter specification.
*/
private $_filter;
/**
* @var Model|array|string|callable model to be used for filter attributes validation.
*/
private $_searchModel;
/**
* @var array list of search attribute types in format: attributeName => type
*/
private $_searchAttributeTypes;
/**
* @return mixed raw filter value.
*/
public function getFilter()
{
return $this->_filter;
}
/**
* @param mixed $filter raw filter value.
*/
public function setFilter($filter)
{
$this->_filter = $filter;
}
/**
* @return Model model instance.
* @throws InvalidConfigException on invalid configuration.
*/
public function getSearchModel()
{
if (!is_object($this->_searchModel) || $this->_searchModel instanceof \Closure) {
$model = Yii::createObject($this->_searchModel);
if (!$model instanceof Model) {
throw new InvalidConfigException('`' . get_class($this) . '::$searchModel` should be an instance of `' . Model::className() . '` or its DI compatible configuration.');
}
$this->_searchModel = $model;
}
return $this->_searchModel;
}
/**
* @param Model|array|string|callable $model model instance or its DI compatible configuration.
* @throws InvalidConfigException on invalid configuration.
*/
public function setSearchModel($model)
{
if (is_object($model) && !$model instanceof Model && !$model instanceof \Closure) {
throw new InvalidConfigException('`' . get_class($this) . '::$searchModel` should be an instance of `' . Model::className() . '` or its DI compatible configuration.');
}
$this->_searchModel = $model;
}
/**
* @return array search attribute type map.
*/
public function getSearchAttributeTypes()
{
if ($this->_searchAttributeTypes === null) {
$this->_searchAttributeTypes = $this->detectSearchAttributeTypes();
}
return $this->_searchAttributeTypes;
}
/**
* @param array|null $searchAttributeTypes search attribute type map.
*/
public function setSearchAttributeTypes($searchAttributeTypes)
{
$this->_searchAttributeTypes = $searchAttributeTypes;
}
/**
* Composes default value for [[searchAttributeTypes]] from the [[searchModel]] validation rules.
* @return array attribute type map.
*/
protected function detectSearchAttributeTypes()
{
$model = $this->getSearchModel();
$attributeTypes = [];
foreach ($model->activeAttributes() as $attribute) {
$attributeTypes[$attribute] = self::TYPE_STRING;
}
foreach ($model->getValidators() as $validator) {
$type = $this->detectSearchAttributeType($validator);
if ($type !== null) {
foreach ((array) $validator->attributes as $attribute) {
$attributeTypes[$attribute] = $type;
}
}
}
return $attributeTypes;
}
/**
* Detect attribute type from given validator.
*
* @param Validator $validator validator from which to detect attribute type.
* @return string|null detected attribute type.
* @since 2.0.14
*/
protected function detectSearchAttributeType(Validator $validator)
{
if ($validator instanceof BooleanValidator) {
return self::TYPE_BOOLEAN;
}
if ($validator instanceof NumberValidator) {
return $validator->integerOnly ? self::TYPE_INTEGER : self::TYPE_FLOAT;
}
if ($validator instanceof StringValidator) {
return self::TYPE_STRING;
}
if ($validator instanceof EachValidator) {
return self::TYPE_ARRAY;
}
if ($validator instanceof DateValidator) {
if ($validator->type == DateValidator::TYPE_DATETIME) {
return self::TYPE_DATETIME;
}
if ($validator->type == DateValidator::TYPE_TIME) {
return self::TYPE_TIME;
}
return self::TYPE_DATE;
}
}
/**
* @return array error messages in format `[errorKey => message]`.
*/
public function getErrorMessages()
{
if (!is_array($this->_errorMessages)) {
if ($this->_errorMessages === null) {
$this->_errorMessages = $this->defaultErrorMessages();
} else {
$this->_errorMessages = array_merge(
$this->defaultErrorMessages(),
call_user_func($this->_errorMessages)
);
}
}
return $this->_errorMessages;
}
/**
* Sets the list of error messages responding to invalid filter structure, in format: `[errorKey => message]`.
* Message may contain placeholders that will be populated depending on the message context.
* For each message a `{filter}` placeholder is available referring to the label for [[filterAttributeName]] attribute.
* @param array|\Closure $errorMessages error messages in `[errorKey => message]` format, or a PHP callback returning them.
*/
public function setErrorMessages($errorMessages)
{
if (is_array($errorMessages)) {
$errorMessages = array_merge($this->defaultErrorMessages(), $errorMessages);
}
$this->_errorMessages = $errorMessages;
}
/**
* Returns default values for [[errorMessages]].
* @return array default error messages in `[errorKey => message]` format.
*/
protected function defaultErrorMessages()
{
return [
'invalidFilter' => Yii::t('yii', 'The format of {filter} is invalid.'),
'operatorRequireMultipleOperands' => Yii::t('yii', 'Operator "{operator}" requires multiple operands.'),
'unknownAttribute' => Yii::t('yii', 'Unknown filter attribute "{attribute}"'),
'invalidAttributeValueFormat' => Yii::t('yii', 'Condition for "{attribute}" should be either a value or valid operator specification.'),
'operatorRequireAttribute' => Yii::t('yii', 'Operator "{operator}" must be used with a search attribute.'),
'unsupportedOperatorType' => Yii::t('yii', '"{attribute}" does not support operator "{operator}".'),
];
}
/**
* Parses content of the message from [[errorMessages]], specified by message key.
* @param string $messageKey message key.
* @param array $params params to be parsed into the message.
* @return string composed message string.
*/
protected function parseErrorMessage($messageKey, $params = [])
{
$messages = $this->getErrorMessages();
if (isset($messages[$messageKey])) {
$message = $messages[$messageKey];
} else {
$message = Yii::t('yii', 'The format of {filter} is invalid.');
}
$params = array_merge(
[
'filter' => $this->getAttributeLabel($this->filterAttributeName),
],
$params
);
return Yii::$app->getI18n()->format($message, $params, Yii::$app->language);
}
// Model specific:
/**
* {@inheritdoc}
*/
public function attributes()
{
return [
$this->filterAttributeName,
];
}
/**
* {@inheritdoc}
*/
public function formName()
{
return '';
}
/**
* {@inheritdoc}
*/
public function rules()
{
return [
[$this->filterAttributeName, 'validateFilter', 'skipOnEmpty' => false],
];
}
/**
* {@inheritdoc}
*/
public function attributeLabels()
{
return [
$this->filterAttributeName => $this->filterAttributeLabel,
];
}
// Validation:
/**
* Validates filter attribute value to match filer condition specification.
*/
public function validateFilter()
{
$value = $this->getFilter();
if ($value !== null) {
$this->validateCondition($value);
}
}
/**
* Validates filter condition.
* @param mixed $condition raw filter condition.
*/
protected function validateCondition($condition)
{
if (!is_array($condition)) {
$this->addError($this->filterAttributeName, $this->parseErrorMessage('invalidFilter'));
return;
}
if (empty($condition)) {
return;
}
foreach ($condition as $key => $value) {
$method = 'validateAttributeCondition';
if (isset($this->filterControls[$key])) {
$controlKey = $this->filterControls[$key];
if (isset($this->conditionValidators[$controlKey])) {
$method = $this->conditionValidators[$controlKey];
}
}
$this->$method($key, $value);
}
}
/**
* Validates conjunction condition that consists of multiple independent ones.
* This covers such operators as `and` and `or`.
* @param string $operator raw operator control keyword.
* @param mixed $condition raw condition.
*/
protected function validateConjunctionCondition($operator, $condition)
{
if (!is_array($condition) || !ArrayHelper::isIndexed($condition)) {
$this->addError($this->filterAttributeName, $this->parseErrorMessage('operatorRequireMultipleOperands', ['operator' => $operator]));
return;
}
foreach ($condition as $part) {
$this->validateCondition($part);
}
}
/**
* Validates block condition that consists of a single condition.
* This covers such operators as `not`.
* @param string $operator raw operator control keyword.
* @param mixed $condition raw condition.
*/
protected function validateBlockCondition($operator, $condition)
{
$this->validateCondition($condition);
}
/**
* Validates search condition for a particular attribute.
* @param string $attribute search attribute name.
* @param mixed $condition search condition.
*/
protected function validateAttributeCondition($attribute, $condition)
{
$attributeTypes = $this->getSearchAttributeTypes();
if (!isset($attributeTypes[$attribute])) {
$this->addError($this->filterAttributeName, $this->parseErrorMessage('unknownAttribute', ['attribute' => $attribute]));
return;
}
if (is_array($condition)) {
$operatorCount = 0;
foreach ($condition as $rawOperator => $value) {
if (isset($this->filterControls[$rawOperator])) {
$operator = $this->filterControls[$rawOperator];
if (isset($this->operatorTypes[$operator])) {
$operatorCount++;
$this->validateOperatorCondition($rawOperator, $value, $attribute);
}
}
}
if ($operatorCount > 0) {
if ($operatorCount < count($condition)) {
$this->addError($this->filterAttributeName, $this->parseErrorMessage('invalidAttributeValueFormat', ['attribute' => $attribute]));
}
} else {
// attribute may allow array value:
$this->validateAttributeValue($attribute, $condition);
}
} else {
$this->validateAttributeValue($attribute, $condition);
}
}
/**
* Validates operator condition.
* @param string $operator raw operator control keyword.
* @param mixed $condition attribute condition.
* @param string|null $attribute attribute name.
*/
protected function validateOperatorCondition($operator, $condition, $attribute = null)
{
if ($attribute === null) {
// absence of an attribute indicates that operator has been placed in a wrong position
$this->addError($this->filterAttributeName, $this->parseErrorMessage('operatorRequireAttribute', ['operator' => $operator]));
return;
}
$internalOperator = $this->filterControls[$operator];
// check operator type :
$operatorTypes = $this->operatorTypes[$internalOperator];
if ($operatorTypes !== '*') {
$attributeTypes = $this->getSearchAttributeTypes();
$attributeType = $attributeTypes[$attribute];
if (!in_array($attributeType, $operatorTypes, true)) {
$this->addError($this->filterAttributeName, $this->parseErrorMessage('unsupportedOperatorType', ['attribute' => $attribute, 'operator' => $operator]));
return;
}
}
if (in_array($internalOperator, $this->multiValueOperators, true)) {
// multi-value operator:
if (!is_array($condition)) {
$this->addError($this->filterAttributeName, $this->parseErrorMessage('operatorRequireMultipleOperands', ['operator' => $operator]));
} else {
foreach ($condition as $v) {
$this->validateAttributeValue($attribute, $v);
}
}
} else {
// single-value operator :
$this->validateAttributeValue($attribute, $condition);
}
}
/**
* Validates attribute value in the scope of [[model]].
* @param string $attribute attribute name.
* @param mixed $value attribute value.
*/
protected function validateAttributeValue($attribute, $value)
{
$model = $this->getSearchModel();
if (!$model->isAttributeSafe($attribute)) {
$this->addError($this->filterAttributeName, $this->parseErrorMessage('unknownAttribute', ['attribute' => $attribute]));
return;
}
$model->{$attribute} = $value === $this->nullValue ? null : $value;
if (!$model->validate([$attribute])) {
$this->addError($this->filterAttributeName, $model->getFirstError($attribute));
return;
}
}
/**
* Validates attribute value in the scope of [[searchModel]], applying attribute value filters if any.
* @param string $attribute attribute name.
* @param mixed $value attribute value.
* @return mixed filtered attribute value.
*/
protected function filterAttributeValue($attribute, $value)
{
$model = $this->getSearchModel();
if (!$model->isAttributeSafe($attribute)) {
$this->addError($this->filterAttributeName, $this->parseErrorMessage('unknownAttribute', ['attribute' => $attribute]));
return $value;
}
$model->{$attribute} = $value;
if (!$model->validate([$attribute])) {
$this->addError($this->filterAttributeName, $model->getFirstError($attribute));
return $value;
}
return $model->{$attribute};
}
// Build:
/**
* Builds actual filter specification form [[filter]] value.
* @param bool $runValidation whether to perform validation (calling [[validate()]])
* before building the filter. Defaults to `true`. If the validation fails, no filter will
* be built and this method will return `false`.
* @return mixed|false built actual filter value, or `false` if validation fails.
*/
public function build($runValidation = true)
{
if ($runValidation && !$this->validate()) {
return false;
}
return $this->buildInternal();
}
/**
* Performs actual filter build.
* By default this method returns result of [[normalize()]].
* The child class may override this method providing more specific implementation.
* @return mixed built actual filter value.
*/
protected function buildInternal()
{
return $this->normalize(false);
}
/**
* Normalizes filter value, replacing raw keys according to [[filterControls]] and [[attributeMap]].
* @param bool $runValidation whether to perform validation (calling [[validate()]])
* before normalizing the filter. Defaults to `true`. If the validation fails, no filter will
* be processed and this method will return `false`.
* @return array|bool normalized filter value, or `false` if validation fails.
*/
public function normalize($runValidation = true)
{
if ($runValidation && !$this->validate()) {
return false;
}
$filter = $this->getFilter();
if (!is_array($filter) || empty($filter)) {
return [];
}
return $this->normalizeComplexFilter($filter);
}
/**
* Normalizes complex filter recursively.
* @param array $filter raw filter.
* @return array normalized filter.
*/
private function normalizeComplexFilter(array $filter)
{
$result = [];
foreach ($filter as $key => $value) {
if (isset($this->filterControls[$key])) {
$key = $this->filterControls[$key];
} elseif (isset($this->attributeMap[$key])) {
$key = $this->attributeMap[$key];
}
if (is_array($value)) {
$result[$key] = $this->normalizeComplexFilter($value);
} elseif ($value === $this->nullValue) {
$result[$key] = null;
} else {
$result[$key] = $value;
}
}
return $result;
}
// Property access:
/**
* {@inheritdoc}
*/
public function canGetProperty($name, $checkVars = true, $checkBehaviors = true)
{
if ($name === $this->filterAttributeName) {
return true;
}
return parent::canGetProperty($name, $checkVars, $checkBehaviors);
}
/**
* {@inheritdoc}
*/
public function canSetProperty($name, $checkVars = true, $checkBehaviors = true)
{
if ($name === $this->filterAttributeName) {
return true;
}
return parent::canSetProperty($name, $checkVars, $checkBehaviors);
}
/**
* {@inheritdoc}
*/
public function __get($name)
{
if ($name === $this->filterAttributeName) {
return $this->getFilter();
}
return parent::__get($name);
}
/**
* {@inheritdoc}
*/
public function __set($name, $value)
{
if ($name === $this->filterAttributeName) {
$this->setFilter($value);
} else {
parent::__set($name, $value);
}
}
/**
* {@inheritdoc}
*/
public function __isset($name)
{
if ($name === $this->filterAttributeName) {
return $this->getFilter() !== null;
}
return parent::__isset($name);
}
/**
* {@inheritdoc}
*/
public function __unset($name)
{
if ($name === $this->filterAttributeName) {
$this->setFilter(null);
} else {
parent::__unset($name);
}
}
}