/
v.bolshakov
/
AIEcosystem-Testing
Обзор
Документация
Войти
/
v.bolshakov
/
AIEcosystem-Testing
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
CI/CD
Аналитика
Безопасность
dev
common/models/base/Model.php
242 строки
6 KB
Developer
Initial commit
03 авг 2026, 17:43
03 авг 2026, 17:43
7433917
Код
Авторство
О чём код?
<?php namespace common\models\base; use common\helpers\ModelHelper; use common\traits\FactoryTrait; use Yii; use yii\base\Component; use yii\helpers\ArrayHelper; /** * Базовая модель * * @author Dmitry E. Semenov <sde.tomsk@gmail.com> * @copyright Self (c) 2019 */ abstract class Model extends \yii\base\Model { use FactoryTrait; /** * Имя формы * @var array|string */ protected $modelName = []; /** * Результат работы формы * @var BaseModel */ protected $model = null; /** * Название модели * @return array|string */ public function modelName($index = 0) { if (is_array($this->modelName)) { if ($index == -1) { return $this->modelName; } else { return Yii::t('app', ArrayHelper::getValue($this->modelName, $index)); } } return Yii::t('app', $this->modelName); } /** * Получить публичные поля модели * * @return array */ public function getPublicFields() { return []; } /** * Первоначальное состояние модели * @var array */ protected $state = []; /** * Подготовить поле модели подразделения для вывода в селекте * * @param $query * @param string $textField * @param string $searchField * @param string $primaryKeyName * * @return array|null */ public function prepareSelectField($query, $searchField = 'id', $textField = 'name', $primaryKeyName = 'id') { if ($this->{$searchField} == null) { return null; } $a = $query->alias; $model = $query ->alias($a) ->andFilterWhere([$a . '.' . $primaryKeyName => $this->{$searchField}]) ->one(); if (!$model) { return null; } if ($textField instanceof \Closure) { $text = call_user_func_array($textField, [$model]); } else { $text = $model->{$textField}; } return [ [ 'id' => $model->getPrimaryKey(), 'text' => Yii::t('app', $text), ] ]; } /** * * @param string $textField * @return mixed */ public function prepareArrayField($textField = 'name') { $model = $this->getModel(); if ($model && $array = $model->getRelation($textField)) { $items = $array->indexBy('id')->all(); $result = []; foreach ($items as $item) { $result[] = [ 'id' => $item->getPrimaryKey(), 'text' => $item->title, ]; } return $result; } else { return []; } } /** * Базовый метод который нужно перегружать в дочерних класса для использования * в Crud формах * * @param $condition */ public function loadModel($condition) { } /** * @inheritdoc */ public function load($data, $formName = null) { $result = parent::load($data, $formName); $this->state = ModelHelper::prepareState($this); return $result; } /** * @inheritdoc */ public function getId() { if ($this->model) { return $this->model->getId(); } else { return null; } } /** * @inheritdoc */ public function getModel() { return $this->model; } /** * @inheritdoc */ public function getIsNewRecord() { if ($this->model) { return $this->model->getIsNewRecord(); } else { return true; } } /** * Инициализация первоначального состояния, загрузка данных из базы * данный метод заполняет поля модели * * @param Component $object объект, от которого происходит инициализация модели */ public function initState($object) { $fields = $this->getPublicFields(); if ($object) { foreach ($fields as $index => $field) { if ($field instanceof \Closure) { $name = $index; } else { $name = $field; } if ($object->hasProperty($name)) { $this->{$name} = $object->{$name}; } } } $this->model = $object; $this->state = ModelHelper::prepareState($this, $fields); } /** * Получение данных для подставление в Widgets * * @param string $key ключ для получения данных из модели * @return mixed */ public function getStateKey($key) { return ArrayHelper::getValue($this->state, $key); } /** * Возвращает TRUE если модель инициализирова * @return bool */ public function hasState() { return is_array($this->state) and count($this->state) > 0; } /** * Возвращает массив ключ => значение, которое возвращается после упешной заполнении формы и сохранения в AJAX запросах * @return array */ public function getData() { return []; } }