DataFilter.php 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835
  1. <?php
  2. /**
  3. * @link http://www.yiiframework.com/
  4. * @copyright Copyright (c) 2008 Yii Software LLC
  5. * @license http://www.yiiframework.com/license/
  6. */
  7. namespace yii\data;
  8. use Yii;
  9. use yii\base\InvalidConfigException;
  10. use yii\base\Model;
  11. use yii\helpers\ArrayHelper;
  12. use yii\validators\BooleanValidator;
  13. use yii\validators\EachValidator;
  14. use yii\validators\NumberValidator;
  15. use yii\validators\StringValidator;
  16. use yii\validators\DateValidator;
  17. use yii\validators\Validator;
  18. /**
  19. * DataFilter is a special [[Model]] for processing query filtering specification.
  20. * It allows validating and building a filter condition passed via request.
  21. *
  22. * Filter example:
  23. *
  24. * ```json
  25. * {
  26. * "or": [
  27. * {
  28. * "and": [
  29. * {
  30. * "name": "some name",
  31. * },
  32. * {
  33. * "price": "25",
  34. * }
  35. * ]
  36. * },
  37. * {
  38. * "id": {"in": [2, 5, 9]},
  39. * "price": {
  40. * "gt": 10,
  41. * "lt": 50
  42. * }
  43. * }
  44. * ]
  45. * }
  46. * ```
  47. *
  48. * In the request the filter should be specified using a key name equal to [[filterAttributeName]]. Thus actual HTTP request body
  49. * will look like following:
  50. *
  51. * ```json
  52. * {
  53. * "filter": {"or": {...}},
  54. * "page": 2,
  55. * ...
  56. * }
  57. * ```
  58. *
  59. * Raw filter value should be assigned to [[filter]] property of the model.
  60. * You may populate it from request data via [[load()]] method:
  61. *
  62. * ```php
  63. * use yii\data\DataFilter;
  64. *
  65. * $dataFilter = new DataFilter();
  66. * $dataFilter->load(Yii::$app->request->getBodyParams());
  67. * ```
  68. *
  69. * In order to function this class requires a search model specified via [[searchModel]]. This search model should declare
  70. * all available search attributes and their validation rules. For example:
  71. *
  72. * ```php
  73. * class SearchModel extends \yii\base\Model
  74. * {
  75. * public $id;
  76. * public $name;
  77. *
  78. * public function rules()
  79. * {
  80. * return [
  81. * [['id', 'name'], 'trim'],
  82. * ['id', 'integer'],
  83. * ['name', 'string'],
  84. * ];
  85. * }
  86. * }
  87. * ```
  88. *
  89. * In order to reduce amount of classes, you may use [[\yii\base\DynamicModel]] instance as a [[searchModel]].
  90. * In this case you should specify [[searchModel]] using a PHP callable:
  91. *
  92. * ```php
  93. * function () {
  94. * return (new \yii\base\DynamicModel(['id' => null, 'name' => null]))
  95. * ->addRule(['id', 'name'], 'trim')
  96. * ->addRule('id', 'integer')
  97. * ->addRule('name', 'string');
  98. * }
  99. * ```
  100. *
  101. * You can use [[validate()]] method to check if filter value is valid. If validation fails you can use
  102. * [[getErrors()]] to get actual error messages.
  103. *
  104. * In order to acquire filter condition suitable for fetching data use [[build()]] method.
  105. *
  106. * > Note: This is a base class. Its implementation of [[build()]] simply returns normalized [[filter]] value.
  107. * In order to convert filter to particular format you should use descendant of this class that implements
  108. * [[buildInternal()]] method accordingly.
  109. *
  110. * @see ActiveDataFilter
  111. *
  112. * @property array $errorMessages Error messages in format `[errorKey => message]`. Note that the type of this
  113. * property differs in getter and setter. See [[getErrorMessages()]] and [[setErrorMessages()]] for details.
  114. * @property mixed $filter Raw filter value.
  115. * @property array $searchAttributeTypes Search attribute type map. Note that the type of this property
  116. * differs in getter and setter. See [[getSearchAttributeTypes()]] and [[setSearchAttributeTypes()]] for details.
  117. * @property Model $searchModel Model instance. Note that the type of this property differs in getter and
  118. * setter. See [[getSearchModel()]] and [[setSearchModel()]] for details.
  119. *
  120. * @author Paul Klimov <klimov.paul@gmail.com>
  121. * @since 2.0.13
  122. */
  123. class DataFilter extends Model
  124. {
  125. const TYPE_INTEGER = 'integer';
  126. const TYPE_FLOAT = 'float';
  127. const TYPE_BOOLEAN = 'boolean';
  128. const TYPE_STRING = 'string';
  129. const TYPE_ARRAY = 'array';
  130. const TYPE_DATETIME = 'datetime';
  131. const TYPE_DATE = 'date';
  132. const TYPE_TIME = 'time';
  133. /**
  134. * @var string name of the attribute that handles filter value.
  135. * The name is used to load data via [[load()]] method.
  136. */
  137. public $filterAttributeName = 'filter';
  138. /**
  139. * @var string label for the filter attribute specified via [[filterAttributeName]].
  140. * It will be used during error messages composition.
  141. */
  142. public $filterAttributeLabel;
  143. /**
  144. * @var array keywords or expressions that could be used in a filter.
  145. * Array keys are the expressions used in raw filter value obtained from user request.
  146. * Array values are internal build keys used in this class methods.
  147. *
  148. * Any unspecified keyword will not be recognized as a filter control and will be treated as
  149. * an attribute name. Thus you should avoid conflicts between control keywords and attribute names.
  150. * For example: in case you have control keyword 'like' and an attribute named 'like', specifying condition
  151. * for such attribute will be impossible.
  152. *
  153. * You may specify several keywords for the same filter build key, creating multiple aliases. For example:
  154. *
  155. * ```php
  156. * [
  157. * 'eq' => '=',
  158. * '=' => '=',
  159. * '==' => '=',
  160. * '===' => '=',
  161. * // ...
  162. * ]
  163. * ```
  164. *
  165. * > Note: while specifying filter controls take actual data exchange format, which your API uses, in mind.
  166. * > Make sure each specified control keyword is valid for the format. For example, in XML tag name can start
  167. * > only with a letter character, thus controls like `>`, '=' or `$gt` will break the XML schema.
  168. */
  169. public $filterControls = [
  170. 'and' => 'AND',
  171. 'or' => 'OR',
  172. 'not' => 'NOT',
  173. 'lt' => '<',
  174. 'gt' => '>',
  175. 'lte' => '<=',
  176. 'gte' => '>=',
  177. 'eq' => '=',
  178. 'neq' => '!=',
  179. 'in' => 'IN',
  180. 'nin' => 'NOT IN',
  181. 'like' => 'LIKE',
  182. ];
  183. /**
  184. * @var array maps filter condition keywords to validation methods.
  185. * These methods are used by [[validateCondition()]] to validate raw filter conditions.
  186. */
  187. public $conditionValidators = [
  188. 'AND' => 'validateConjunctionCondition',
  189. 'OR' => 'validateConjunctionCondition',
  190. 'NOT' => 'validateBlockCondition',
  191. '<' => 'validateOperatorCondition',
  192. '>' => 'validateOperatorCondition',
  193. '<=' => 'validateOperatorCondition',
  194. '>=' => 'validateOperatorCondition',
  195. '=' => 'validateOperatorCondition',
  196. '!=' => 'validateOperatorCondition',
  197. 'IN' => 'validateOperatorCondition',
  198. 'NOT IN' => 'validateOperatorCondition',
  199. 'LIKE' => 'validateOperatorCondition',
  200. ];
  201. /**
  202. * @var array specifies the list of supported search attribute types per each operator.
  203. * This field should be in format: 'operatorKeyword' => ['type1', 'type2' ...].
  204. * Supported types list can be specified as `*`, which indicates that operator supports all types available.
  205. * Any unspecified keyword will not be considered as a valid operator.
  206. */
  207. public $operatorTypes = [
  208. '<' => [self::TYPE_INTEGER, self::TYPE_FLOAT, self::TYPE_DATETIME, self::TYPE_DATE, self::TYPE_TIME],
  209. '>' => [self::TYPE_INTEGER, self::TYPE_FLOAT, self::TYPE_DATETIME, self::TYPE_DATE, self::TYPE_TIME],
  210. '<=' => [self::TYPE_INTEGER, self::TYPE_FLOAT, self::TYPE_DATETIME, self::TYPE_DATE, self::TYPE_TIME],
  211. '>=' => [self::TYPE_INTEGER, self::TYPE_FLOAT, self::TYPE_DATETIME, self::TYPE_DATE, self::TYPE_TIME],
  212. '=' => '*',
  213. '!=' => '*',
  214. 'IN' => '*',
  215. 'NOT IN' => '*',
  216. 'LIKE' => [self::TYPE_STRING],
  217. ];
  218. /**
  219. * @var array list of operators keywords, which should accept multiple values.
  220. */
  221. public $multiValueOperators = [
  222. 'IN',
  223. 'NOT IN',
  224. ];
  225. /**
  226. * @var array actual attribute names to be used in searched condition, in format: [filterAttribute => actualAttribute].
  227. * For example, in case of using table joins in the search query, attribute map may look like the following:
  228. *
  229. * ```php
  230. * [
  231. * 'authorName' => '{{author}}.[[name]]'
  232. * ]
  233. * ```
  234. *
  235. * Attribute map will be applied to filter condition in [[normalize()]] method.
  236. */
  237. public $attributeMap = [];
  238. /**
  239. * @var array|\Closure list of error messages responding to invalid filter structure, in format: `[errorKey => message]`.
  240. */
  241. private $_errorMessages;
  242. /**
  243. * @var mixed raw filter specification.
  244. */
  245. private $_filter;
  246. /**
  247. * @var Model|array|string|callable model to be used for filter attributes validation.
  248. */
  249. private $_searchModel;
  250. /**
  251. * @var array list of search attribute types in format: attributeName => type
  252. */
  253. private $_searchAttributeTypes;
  254. /**
  255. * @return mixed raw filter value.
  256. */
  257. public function getFilter()
  258. {
  259. return $this->_filter;
  260. }
  261. /**
  262. * @param mixed $filter raw filter value.
  263. */
  264. public function setFilter($filter)
  265. {
  266. $this->_filter = $filter;
  267. }
  268. /**
  269. * @return Model model instance.
  270. * @throws InvalidConfigException on invalid configuration.
  271. */
  272. public function getSearchModel()
  273. {
  274. if (!is_object($this->_searchModel) || $this->_searchModel instanceof \Closure) {
  275. $model = Yii::createObject($this->_searchModel);
  276. if (!$model instanceof Model) {
  277. throw new InvalidConfigException('`' . get_class($this) . '::$searchModel` should be an instance of `' . Model::className() . '` or its DI compatible configuration.');
  278. }
  279. $this->_searchModel = $model;
  280. }
  281. return $this->_searchModel;
  282. }
  283. /**
  284. * @param Model|array|string|callable $model model instance or its DI compatible configuration.
  285. * @throws InvalidConfigException on invalid configuration.
  286. */
  287. public function setSearchModel($model)
  288. {
  289. if (is_object($model) && !$model instanceof Model && !$model instanceof \Closure) {
  290. throw new InvalidConfigException('`' . get_class($this) . '::$searchModel` should be an instance of `' . Model::className() . '` or its DI compatible configuration.');
  291. }
  292. $this->_searchModel = $model;
  293. }
  294. /**
  295. * @return array search attribute type map.
  296. */
  297. public function getSearchAttributeTypes()
  298. {
  299. if ($this->_searchAttributeTypes === null) {
  300. $this->_searchAttributeTypes = $this->detectSearchAttributeTypes();
  301. }
  302. return $this->_searchAttributeTypes;
  303. }
  304. /**
  305. * @param array|null $searchAttributeTypes search attribute type map.
  306. */
  307. public function setSearchAttributeTypes($searchAttributeTypes)
  308. {
  309. $this->_searchAttributeTypes = $searchAttributeTypes;
  310. }
  311. /**
  312. * Composes default value for [[searchAttributeTypes]] from the [[searchModel]] validation rules.
  313. * @return array attribute type map.
  314. */
  315. protected function detectSearchAttributeTypes()
  316. {
  317. $model = $this->getSearchModel();
  318. $attributeTypes = [];
  319. foreach ($model->activeAttributes() as $attribute) {
  320. $attributeTypes[$attribute] = self::TYPE_STRING;
  321. }
  322. foreach ($model->getValidators() as $validator) {
  323. $type = $this->detectSearchAttributeType($validator);
  324. if ($type !== null) {
  325. foreach ((array) $validator->attributes as $attribute) {
  326. $attributeTypes[$attribute] = $type;
  327. }
  328. }
  329. }
  330. return $attributeTypes;
  331. }
  332. /**
  333. * Detect attribute type from given validator.
  334. *
  335. * @param Validator validator from which to detect attribute type.
  336. * @return string|null detected attribute type.
  337. * @since 2.0.14
  338. */
  339. protected function detectSearchAttributeType(Validator $validator)
  340. {
  341. if ($validator instanceof BooleanValidator) {
  342. return self::TYPE_BOOLEAN;
  343. }
  344. if ($validator instanceof NumberValidator) {
  345. return $validator->integerOnly ? self::TYPE_INTEGER : self::TYPE_FLOAT;
  346. }
  347. if ($validator instanceof StringValidator) {
  348. return self::TYPE_STRING;
  349. }
  350. if ($validator instanceof EachValidator) {
  351. return self::TYPE_ARRAY;
  352. }
  353. if ($validator instanceof DateValidator) {
  354. if ($validator->type == DateValidator::TYPE_DATETIME) {
  355. return self::TYPE_DATETIME;
  356. }
  357. if ($validator->type == DateValidator::TYPE_TIME) {
  358. return self::TYPE_TIME;
  359. }
  360. return self::TYPE_DATE;
  361. }
  362. }
  363. /**
  364. * @return array error messages in format `[errorKey => message]`.
  365. */
  366. public function getErrorMessages()
  367. {
  368. if (!is_array($this->_errorMessages)) {
  369. if ($this->_errorMessages === null) {
  370. $this->_errorMessages = $this->defaultErrorMessages();
  371. } else {
  372. $this->_errorMessages = array_merge(
  373. $this->defaultErrorMessages(),
  374. call_user_func($this->_errorMessages)
  375. );
  376. }
  377. }
  378. return $this->_errorMessages;
  379. }
  380. /**
  381. * Sets the list of error messages responding to invalid filter structure, in format: `[errorKey => message]`.
  382. * Message may contain placeholders that will be populated depending on the message context.
  383. * For each message a `{filter}` placeholder is available referring to the label for [[filterAttributeName]] attribute.
  384. * @param array|\Closure $errorMessages error messages in `[errorKey => message]` format, or a PHP callback returning them.
  385. */
  386. public function setErrorMessages($errorMessages)
  387. {
  388. if (is_array($errorMessages)) {
  389. $errorMessages = array_merge($this->defaultErrorMessages(), $errorMessages);
  390. }
  391. $this->_errorMessages = $errorMessages;
  392. }
  393. /**
  394. * Returns default values for [[errorMessages]].
  395. * @return array default error messages in `[errorKey => message]` format.
  396. */
  397. protected function defaultErrorMessages()
  398. {
  399. return [
  400. 'invalidFilter' => Yii::t('yii', 'The format of {filter} is invalid.'),
  401. 'operatorRequireMultipleOperands' => Yii::t('yii', 'Operator "{operator}" requires multiple operands.'),
  402. 'unknownAttribute' => Yii::t('yii', 'Unknown filter attribute "{attribute}"'),
  403. 'invalidAttributeValueFormat' => Yii::t('yii', 'Condition for "{attribute}" should be either a value or valid operator specification.'),
  404. 'operatorRequireAttribute' => Yii::t('yii', 'Operator "{operator}" must be used with a search attribute.'),
  405. 'unsupportedOperatorType' => Yii::t('yii', '"{attribute}" does not support operator "{operator}".'),
  406. ];
  407. }
  408. /**
  409. * Parses content of the message from [[errorMessages]], specified by message key.
  410. * @param string $messageKey message key.
  411. * @param array $params params to be parsed into the message.
  412. * @return string composed message string.
  413. */
  414. protected function parseErrorMessage($messageKey, $params = [])
  415. {
  416. $messages = $this->getErrorMessages();
  417. if (isset($messages[$messageKey])) {
  418. $message = $messages[$messageKey];
  419. } else {
  420. $message = Yii::t('yii', 'The format of {filter} is invalid.');
  421. }
  422. $params = array_merge(
  423. [
  424. 'filter' => $this->getAttributeLabel($this->filterAttributeName),
  425. ],
  426. $params
  427. );
  428. return Yii::$app->getI18n()->format($message, $params, Yii::$app->language);
  429. }
  430. // Model specific:
  431. /**
  432. * {@inheritdoc}
  433. */
  434. public function attributes()
  435. {
  436. return [
  437. $this->filterAttributeName,
  438. ];
  439. }
  440. /**
  441. * {@inheritdoc}
  442. */
  443. public function formName()
  444. {
  445. return '';
  446. }
  447. /**
  448. * {@inheritdoc}
  449. */
  450. public function rules()
  451. {
  452. return [
  453. [$this->filterAttributeName, 'validateFilter', 'skipOnEmpty' => false],
  454. ];
  455. }
  456. /**
  457. * {@inheritdoc}
  458. */
  459. public function attributeLabels()
  460. {
  461. return [
  462. $this->filterAttributeName => $this->filterAttributeLabel,
  463. ];
  464. }
  465. // Validation:
  466. /**
  467. * Validates filter attribute value to match filer condition specification.
  468. */
  469. public function validateFilter()
  470. {
  471. $value = $this->getFilter();
  472. if ($value !== null) {
  473. $this->validateCondition($value);
  474. }
  475. }
  476. /**
  477. * Validates filter condition.
  478. * @param mixed $condition raw filter condition.
  479. */
  480. protected function validateCondition($condition)
  481. {
  482. if (!is_array($condition)) {
  483. $this->addError($this->filterAttributeName, $this->parseErrorMessage('invalidFilter'));
  484. return;
  485. }
  486. if (empty($condition)) {
  487. return;
  488. }
  489. foreach ($condition as $key => $value) {
  490. $method = 'validateAttributeCondition';
  491. if (isset($this->filterControls[$key])) {
  492. $controlKey = $this->filterControls[$key];
  493. if (isset($this->conditionValidators[$controlKey])) {
  494. $method = $this->conditionValidators[$controlKey];
  495. }
  496. }
  497. $this->$method($key, $value);
  498. }
  499. }
  500. /**
  501. * Validates conjunction condition that consists of multiple independent ones.
  502. * This covers such operators as `and` and `or`.
  503. * @param string $operator raw operator control keyword.
  504. * @param mixed $condition raw condition.
  505. */
  506. protected function validateConjunctionCondition($operator, $condition)
  507. {
  508. if (!is_array($condition) || !ArrayHelper::isIndexed($condition)) {
  509. $this->addError($this->filterAttributeName, $this->parseErrorMessage('operatorRequireMultipleOperands', ['operator' => $operator]));
  510. return;
  511. }
  512. foreach ($condition as $part) {
  513. $this->validateCondition($part);
  514. }
  515. }
  516. /**
  517. * Validates block condition that consists of a single condition.
  518. * This covers such operators as `not`.
  519. * @param string $operator raw operator control keyword.
  520. * @param mixed $condition raw condition.
  521. */
  522. protected function validateBlockCondition($operator, $condition)
  523. {
  524. $this->validateCondition($condition);
  525. }
  526. /**
  527. * Validates search condition for a particular attribute.
  528. * @param string $attribute search attribute name.
  529. * @param mixed $condition search condition.
  530. */
  531. protected function validateAttributeCondition($attribute, $condition)
  532. {
  533. $attributeTypes = $this->getSearchAttributeTypes();
  534. if (!isset($attributeTypes[$attribute])) {
  535. $this->addError($this->filterAttributeName, $this->parseErrorMessage('unknownAttribute', ['attribute' => $attribute]));
  536. return;
  537. }
  538. if (is_array($condition)) {
  539. $operatorCount = 0;
  540. foreach ($condition as $rawOperator => $value) {
  541. if (isset($this->filterControls[$rawOperator])) {
  542. $operator = $this->filterControls[$rawOperator];
  543. if (isset($this->operatorTypes[$operator])) {
  544. $operatorCount++;
  545. $this->validateOperatorCondition($rawOperator, $value, $attribute);
  546. }
  547. }
  548. }
  549. if ($operatorCount > 0) {
  550. if ($operatorCount < count($condition)) {
  551. $this->addError($this->filterAttributeName, $this->parseErrorMessage('invalidAttributeValueFormat', ['attribute' => $attribute]));
  552. }
  553. } else {
  554. // attribute may allow array value:
  555. $this->validateAttributeValue($attribute, $condition);
  556. }
  557. } else {
  558. $this->validateAttributeValue($attribute, $condition);
  559. }
  560. }
  561. /**
  562. * Validates operator condition.
  563. * @param string $operator raw operator control keyword.
  564. * @param mixed $condition attribute condition.
  565. * @param string $attribute attribute name.
  566. */
  567. protected function validateOperatorCondition($operator, $condition, $attribute = null)
  568. {
  569. if ($attribute === null) {
  570. // absence of an attribute indicates that operator has been placed in a wrong position
  571. $this->addError($this->filterAttributeName, $this->parseErrorMessage('operatorRequireAttribute', ['operator' => $operator]));
  572. return;
  573. }
  574. $internalOperator = $this->filterControls[$operator];
  575. // check operator type :
  576. $operatorTypes = $this->operatorTypes[$internalOperator];
  577. if ($operatorTypes !== '*') {
  578. $attributeTypes = $this->getSearchAttributeTypes();
  579. $attributeType = $attributeTypes[$attribute];
  580. if (!in_array($attributeType, $operatorTypes, true)) {
  581. $this->addError($this->filterAttributeName, $this->parseErrorMessage('unsupportedOperatorType', ['attribute' => $attribute, 'operator' => $operator]));
  582. return;
  583. }
  584. }
  585. if (in_array($internalOperator, $this->multiValueOperators, true)) {
  586. // multi-value operator:
  587. if (!is_array($condition)) {
  588. $this->addError($this->filterAttributeName, $this->parseErrorMessage('operatorRequireMultipleOperands', ['operator' => $operator]));
  589. } else {
  590. foreach ($condition as $v) {
  591. $this->validateAttributeValue($attribute, $v);
  592. }
  593. }
  594. } else {
  595. // single-value operator :
  596. $this->validateAttributeValue($attribute, $condition);
  597. }
  598. }
  599. /**
  600. * Validates attribute value in the scope of [[model]].
  601. * @param string $attribute attribute name.
  602. * @param mixed $value attribute value.
  603. */
  604. protected function validateAttributeValue($attribute, $value)
  605. {
  606. $model = $this->getSearchModel();
  607. if (!$model->isAttributeSafe($attribute)) {
  608. $this->addError($this->filterAttributeName, $this->parseErrorMessage('unknownAttribute', ['attribute' => $attribute]));
  609. return;
  610. }
  611. $model->{$attribute} = $value;
  612. if (!$model->validate([$attribute])) {
  613. $this->addError($this->filterAttributeName, $model->getFirstError($attribute));
  614. return;
  615. }
  616. }
  617. /**
  618. * Validates attribute value in the scope of [[searchModel]], applying attribute value filters if any.
  619. * @param string $attribute attribute name.
  620. * @param mixed $value attribute value.
  621. * @return mixed filtered attribute value.
  622. */
  623. protected function filterAttributeValue($attribute, $value)
  624. {
  625. $model = $this->getSearchModel();
  626. if (!$model->isAttributeSafe($attribute)) {
  627. $this->addError($this->filterAttributeName, $this->parseErrorMessage('unknownAttribute', ['attribute' => $attribute]));
  628. return $value;
  629. }
  630. $model->{$attribute} = $value;
  631. if (!$model->validate([$attribute])) {
  632. $this->addError($this->filterAttributeName, $model->getFirstError($attribute));
  633. return $value;
  634. }
  635. return $model->{$attribute};
  636. }
  637. // Build:
  638. /**
  639. * Builds actual filter specification form [[filter]] value.
  640. * @param bool $runValidation whether to perform validation (calling [[validate()]])
  641. * before building the filter. Defaults to `true`. If the validation fails, no filter will
  642. * be built and this method will return `false`.
  643. * @return mixed|false built actual filter value, or `false` if validation fails.
  644. */
  645. public function build($runValidation = true)
  646. {
  647. if ($runValidation && !$this->validate()) {
  648. return false;
  649. }
  650. return $this->buildInternal();
  651. }
  652. /**
  653. * Performs actual filter build.
  654. * By default this method returns result of [[normalize()]].
  655. * The child class may override this method providing more specific implementation.
  656. * @return mixed built actual filter value.
  657. */
  658. protected function buildInternal()
  659. {
  660. return $this->normalize(false);
  661. }
  662. /**
  663. * Normalizes filter value, replacing raw keys according to [[filterControls]] and [[attributeMap]].
  664. * @param bool $runValidation whether to perform validation (calling [[validate()]])
  665. * before normalizing the filter. Defaults to `true`. If the validation fails, no filter will
  666. * be processed and this method will return `false`.
  667. * @return array|bool normalized filter value, or `false` if validation fails.
  668. */
  669. public function normalize($runValidation = true)
  670. {
  671. if ($runValidation && !$this->validate()) {
  672. return false;
  673. }
  674. $filter = $this->getFilter();
  675. if (!is_array($filter) || empty($filter)) {
  676. return [];
  677. }
  678. return $this->normalizeComplexFilter($filter);
  679. }
  680. /**
  681. * Normalizes complex filter recursively.
  682. * @param array $filter raw filter.
  683. * @return array normalized filter.
  684. */
  685. private function normalizeComplexFilter(array $filter)
  686. {
  687. $result = [];
  688. foreach ($filter as $key => $value) {
  689. if (isset($this->filterControls[$key])) {
  690. $key = $this->filterControls[$key];
  691. } elseif (isset($this->attributeMap[$key])) {
  692. $key = $this->attributeMap[$key];
  693. }
  694. if (is_array($value)) {
  695. $result[$key] = $this->normalizeComplexFilter($value);
  696. } else {
  697. $result[$key] = $value;
  698. }
  699. }
  700. return $result;
  701. }
  702. // Property access:
  703. /**
  704. * {@inheritdoc}
  705. */
  706. public function canGetProperty($name, $checkVars = true, $checkBehaviors = true)
  707. {
  708. if ($name === $this->filterAttributeName) {
  709. return true;
  710. }
  711. return parent::canGetProperty($name, $checkVars, $checkBehaviors);
  712. }
  713. /**
  714. * {@inheritdoc}
  715. */
  716. public function canSetProperty($name, $checkVars = true, $checkBehaviors = true)
  717. {
  718. if ($name === $this->filterAttributeName) {
  719. return true;
  720. }
  721. return parent::canSetProperty($name, $checkVars, $checkBehaviors);
  722. }
  723. /**
  724. * {@inheritdoc}
  725. */
  726. public function __get($name)
  727. {
  728. if ($name === $this->filterAttributeName) {
  729. return $this->getFilter();
  730. }
  731. return parent::__get($name);
  732. }
  733. /**
  734. * {@inheritdoc}
  735. */
  736. public function __set($name, $value)
  737. {
  738. if ($name === $this->filterAttributeName) {
  739. $this->setFilter($value);
  740. } else {
  741. parent::__set($name, $value);
  742. }
  743. }
  744. /**
  745. * {@inheritdoc}
  746. */
  747. public function __isset($name)
  748. {
  749. if ($name === $this->filterAttributeName) {
  750. return $this->getFilter() !== null;
  751. }
  752. return parent::__isset($name);
  753. }
  754. /**
  755. * {@inheritdoc}
  756. */
  757. public function __unset($name)
  758. {
  759. if ($name === $this->filterAttributeName) {
  760. $this->setFilter(null);
  761. } else {
  762. parent::__unset($name);
  763. }
  764. }
  765. }