/
v.bolshakov
/
AIEcosystem-Testing
Обзор
Документация
Войти
/
v.bolshakov
/
AIEcosystem-Testing
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
CI/CD
Аналитика
Безопасность
dev
common/controllers/base/CrudController.php
374 строки
10 KB
Developer
Initial commit
03 авг 2026, 17:43
03 авг 2026, 17:43
7433917
Код
Авторство
О чём код?
<?php namespace common\controllers\base; use common\components\crud\BaseCrud; use common\components\crud\FormCrud; use common\components\crud\GridPanelCrud; use common\helpers\ModelHelper; use common\models\base\BaseModel; use Yii; use yii\filters\AccessControl; use yii\helpers\ArrayHelper; use yii\helpers\Inflector; use yii\helpers\VarDumper; use yii\httpclient\debug\SearchModel; use yii\web\NotFoundHttpException; /** * Базовый контроллер для работы с CRUD * * @author Dmitry E. Semenov <sde.tomsk@gmail.com> * @copyright Self (c) 2020 */ abstract class CrudController extends DashboardController { /** * Путь для папки классов CRUD * @var null|string */ protected $modelClassPath = ''; /** * @var string */ protected $classPrefix = ''; /** * Разрешено добавлять объекты данной модели * @var bool */ protected $canAdd = true; /** * Имя класса компонентной модели для работы с формой (редактирование объекта) * @var string */ protected $modelName = [ 'form' => null, 'search' => null, 'view' => null, 'grid' => null, 'grid-panel' => null, ]; /** * Шаблон для работы с объектамиы * @var string */ protected $template = [ 'index' => '@common/views/base/index', 'create' => '@common/views/base/create', 'update' => '@common/views/base/update', 'view' => '@common/views/base/view', ]; /** * Получить правило для проверки в ACL * @param $action * @return string */ public function getPermission($action) { // return $this->camel2acl() . '.' . $action; return $action; } /** * @inheritdoc */ public function behaviors() { $behaviors = parent::behaviors(); $permission = $this->getPermission(Yii::$app->controller->action->id); $behaviors['access'] = [ 'class' => AccessControl::class, 'rules' => [ [ 'allow' => true, 'roles' => [$permission], ], ] ]; return $behaviors; } /** * Получить имя класса для работы * * @param string $class Имя класса которое ищем * @param string $default Имя класса по умолчанию * @return string */ protected function getClass($class, $default = null) { if ($this->modelClassPath) { return $this->modelClassPath . '\\' . $this->classPrefix . $class; } else { return ArrayHelper::getValue($this->modelClass, Inflector::camel2id($class)); } } /** * Формирование параметров для создания объектов * @return array */ protected function getParams($input) { return $input; } /** * Фильтрация данных, данный метод необходим что бы ограничить доступ к данным * @return array */ protected function condition() { return []; } /** * Получить модель для работы * * @param $id * @param string $class * @return array * @throws NotFoundHttpException * @throws \yii\base\InvalidConfigException */ protected function getModel($id, $class = 'Form') { $params = $this->getParams([ 'class' => $class ]); /** @var BaseCrud $crud */ $crud = Yii::createObject($params); if ($id) { $model = $crud->createModel($id, $this->condition()); if (!$model) { throw new NotFoundHttpException(Yii::t('app', 'No model found')); } } else { $model = $crud->createModel(); } $crud->controller = $this; return [ 'crud' => $crud, 'model' => $model ]; } /** * Формирование хлебных крошек * * @param $crud * @param null $parent * @param BaseModel $model * @param string $title */ protected function breadcrumbs($crud, $parent = null, $model = null, $title = null) { if (!$title) { /** @var FormCrud $crud */ $title = $crud->getTitle($model && !$model->isNewRecord); } $breadcrumbs = $crud->breadcrumbs($parent); $this->view->title = $title; $breadcrumbs[] = [ 'label' => $title ]; Yii::$app->view->params['breadcrumbs'] = $breadcrumbs; } /** * Постраничное отображение данных * @return mixed */ public function actionIndex() { $params = $this->getParams([ 'class' => $this->getClass('GridPanel') ]); /** @var GridPanelCrud $crud */ $crud = Yii::createObject($params); $params = $this->getParams([ 'class' => $this->getClass('Search'), ]); /** @var SearchModel $modelSearch */ $modelSearch = Yii::createObject($params); $modelSearch->condition($this->condition()); $dataProvider = $modelSearch->search(Yii::$app->request->queryParams); $dataProvider->pagination->defaultPageSize = $crud->defaultPageSize; $filters = $crud->getFilters($modelSearch->getQuery()); $crud->controller = $this; $form = null; if ($this->canAdd) { $permission = $this->getPermission('create'); if (Yii::$app->user->can($permission) and ($class = $this->getClass('Form'))) { if (class_exists($class)) { /** @var FormCrud $crud */ $form = Yii::createObject($class); } } } $this->breadcrumbs($crud); return $this->render($this->getTemplate('Index'), [ 'model' => $modelSearch, 'crud' => $crud, 'form' => $form, 'filters' => $filters, 'canAdd' => $this->canAdd, 'dataProvider' => $dataProvider, ]); } /** * Просмотр одной записи * @param integer $id * @return mixed */ public function actionView($id) { // Yii::$app->request->validateSig(); $data = $this->getModel($id, $this->getClass('View')); $this->breadcrumbs($data['crud']); return $this->render($this->getTemplate('View'), $data); } /** * Создание новой модели * * @return string|\yii\web\Response */ public function actionCreate() { $data = $this->getModel(null, $this->getClass('Form')); $model = $data['model']; if ($model->load(Yii::$app->request->post()) && $model->save()) { Yii::$app->session->addFlash('success', Yii::t('app', 'Data updated')); if ($url = ArrayHelper::getValue($model->getData(), 'redirect')) { return $this->redirect($url); } return $this->redirect(['view', 'id' => $model->getId()]); } else { $this->breadcrumbs($data['crud'], null, $model); return $this->render($this->getTemplate('Create'), $data); } } /** * Обновление одной модели * @param integer $id * @return mixed */ public function actionUpdate($id) { // Yii::$app->request->validateSig(); $data = $this->getModel($id, $this->getClass('Form')); $model = $data['model']; $this->breadcrumbs($data['crud'], null, $model); if ($model->load(Yii::$app->request->post()) && $model->save()) { Yii::$app->session->addFlash('success', Yii::t('app', 'Data updated')); return $this->refresh(); } else { return $this->render($this->getTemplate('Update'), $data); } } /** * Обработка удаления данных * @param $model * @return bool */ protected function doDelete($model) { $response = ''; Yii::debug(VarDumper::dumpAsString([ 'class' => get_class($model) ])); if (ModelHelper::doDelete($model, $response)) { Yii::$app->session->addFlash('success', $response); } else { Yii::$app->session->addFlash('error', $response); } return true; } /** * Удаление одной модели * * @param integer $id * @return mixed */ public function actionDelete($id) { Yii::$app->request->validateSig(); $data = $this->getModel($id, $this->getClass('Form')); $this->doDelete($data['model']); return $this->goReferrer(); } /** * Получить путь к шаблону * * @param $action * @return mixed|string */ protected function getTemplate($action) { $appPath = '@app/views/'; $className = get_class($this); $pos = strrpos($className, '\\'); $class = strtolower(substr(substr($className, $pos + 1), 0, -10)); $folders = explode('controllers\\', $className); if (isset($folders[1])) { $folders = explode('\\', $folders[1]); unset($folders[count($folders) - 1]); $folders = '/' . implode('/', $folders); } else { $folders = ''; } $path = '@app/views' . $folders . '/' . $class . '/' . strtolower($action) . '.twig'; if (is_file(Yii::getAlias($path))) { return $path; } return ArrayHelper::getValue($this->template, Inflector::camel2id($action)); } }