/
v.bolshakov
/
AIEcosystem-Testing
Обзор
Документация
Войти
/
v.bolshakov
/
AIEcosystem-Testing
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
CI/CD
Аналитика
Безопасность
dev
common/search/base/BaseSearch.php
256 строк
6 KB
Developer
Initial commit
03 авг 2026, 17:43
03 авг 2026, 17:43
7433917
Код
Авторство
О чём код?
<?php namespace common\search\base; use common\models\base\BaseQuery; use common\models\base\Model; use Yii; use yii\base\InvalidConfigException; use yii\data\ActiveDataProvider; /** * Базовый класс для реализации поиска в моделях. * * @author Dmitry E. Semenov <sde.tomsk@gmail.com> * @copyright Self (c) 2019 */ abstract class BaseSearch extends Model { /** * Параметры сортировки по умолчанию * @var array */ protected $defaultOrder = []; /** * Имя класса модели * @var string */ protected $modelClass = ''; /** * Модель * @var null */ public $model = null; /** * Название модели. * @var */ public $modelName = []; /** * Родительская модель для работы с данными * @var null */ public $parentModel = null; /** * Объект который используется для поиска даных для построение в BaseSearch * @var BaseQuery */ protected $query; /** * Определяем размер на страницу * @var null */ public $pageSize = null; /** * @inheritdoc */ public function init() { parent::init(); if ($this->modelClass) { $model = $this->getObject(); $this->query = $model::find(); $this->model = $model; $this->query->alias($model::getAlias()); } } /** * Инициализируем класс * * @return object * @throws InvalidConfigException */ protected function getObject() { return Yii::createObject($this->modelClass); } /** * Поиск и фильтрация по полям. * @param array $params Входящие параметры. * @return mixed */ public function search($params) { $dataProvider = new ActiveDataProvider([ 'query' => $this->query, 'pagination' => [ 'pageSize' => $this->pageSize, 'defaultPageSize' => 25 ] ]); $this->setSortForDataProvider($dataProvider); $this->beforeSearch($this->query); if (!($this->load($params) && $this->validate())) { return $dataProvider; } $this->afterSearch(); return $dataProvider; } /** * Устанавливает ActiveQuery * * @param $query */ public function setQuery($query) { $query->alias($query->alias); $this->query = $query; } /** * Получает текущий экземпляр объекта * * @return BaseQuery */ public function getQuery() { return $this->query; } /** * Вызывается для обработки поиска * @param BaseQuery $query */ protected function beforeSearch($query) { } /** * Вызывает событие после выборки по фильтруемым полям * @return mixed */ public function afterSearch() { return true; } /** * Параметры кастомной сортировки * Должен возвращать массив вида * [ * 'id' => [ * 'asc' => ['model_table_name.id' => SORT_ASC], * 'desc' => ['model_table_name.id' => SORT_DESC], * 'label' => 'Id', * 'default' => SORT_ASC, * ], * ... * ] * См. ActiveDataProvider::setSort() документацию * При джоине нескольких таблиц с одинаковыми названиями полей - обязательно конфигурировать сортировку * с указанием имен таблиц * @return array */ protected function getSortConfig() { return [ 'id' => [ 'asc' => [$this->query->alias . '.id' => SORT_ASC], 'desc' => [$this->query->alias . '.id' => SORT_DESC], 'default' => SORT_DESC ], ]; } /** * Задает параметры для сортировки данных data provider * @param ActiveDataProvider $dataProvider */ protected function setSortForDataProvider(ActiveDataProvider $dataProvider) { $sortConfig = []; if ($this->defaultOrder) { $sortConfig['defaultOrder'] = $this->defaultOrder; } if ($config = $this->getSortConfig()) { if ($this->defaultOrder) { foreach ($this->defaultOrder as $filed => $default_sort) { $config[$filed] = [ 'asc' => [$this->query->alias . '.' . $filed => SORT_ASC], 'desc' => [$this->query->alias . '.' . $filed => SORT_DESC], 'default' => $default_sort ]; } } $sortConfig['attributes'] = $config; } if (!empty($sortConfig)) { $dataProvider->setSort($sortConfig); } } /** * Дополнительные условия для фильтрации данных * * @param array $conditions */ public function condition($conditions) { if (is_array($conditions)) { foreach ($conditions as $conditions_callback) { call_user_func_array($conditions_callback, [$this->query]); } } } /** * Поиск и фильтрация по полям * * @return mixed */ protected function doSearch() { return true; } /** * реализация поиска * @return mixed */ public function execute() { if (!$this->validate()) { return false; } $this->beforeSearch($this->query); if ($result = $this->doSearch()) { $this->afterSearch(); } return $result; } }