ItemController.php 7.19 KB
<?php

namespace frontend\modules\map\controllers;

use Yii;
use yii\web\Response;
use yii\filters\{
    AccessControl, VerbFilter
};
use yii\helpers\Url;
use yii\web\NotFoundHttpException;
//
use thread\actions\fileapi\{
    DeleteAction, UploadAction
};
use thread\actions\CreateWithLang;
use thread\app\bootstrap\ActiveForm;
//
use frontend\modules\map\Map;
use frontend\modules\map\models\{
    Area, Item, ItemLang
};
use frontend\modules\page\models\Page;


/**
 * Class ItemController
 *
 * @package frontend\modules\map\controllers
 * @author Alla Kuzmenko
 * @copyright (c) 2017
 */
class ItemController extends \frontend\components\BaseController
{

    public $title = "Item";
    public $layout = "@app/layouts/base";
    public $defaultAction = 'index';
    public $actionListLinkStatus = '';
    //
    /**
     * Назва базової моделі
     * @var string
     */
    protected $model = Item::class;

    /**
     * Назва базової моделі мови
     * @var string
     */
    protected $modelLang = ItemLang::class;

    /**
     * Хлібні крихти
     */

    public $breadcrumbs = [];

    /**
     *
     */
    public function init()
    {
        parent::init();

        $this->breadcrumbs = [
            [
                'label' => Yii::t('map', 'Objects base'),
                'url' => Url::toRoute(['/map/list/list'])
            ]
        ];
    }

    /**
     * @return array
     */
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::class,
                'actions' => [
                    'view' => ['get'],
                    'create' => ['get', 'post']
                ],
            ],
            'AccessControl' => [
                'class' => AccessControl::class,
                'rules' => [
                    [
                        'allow' => true,
                        'actions' => ['create', 'validation'],
                        'roles' => ['@'],
                    ],
                    [
                        'allow' => false,
                        'actions' => ['create', 'validation'],
                        'roles' => ['?'],
                    ],
                    [
                        'allow' => true,
                    ],
                ],
            ],
        ];
    }

    /**
     * @return array
     * @throws NotFoundHttpException
     */
    public function actions()
    {
        return [
            'create' => [
                'class' => CreateWithLang::class,
                'layout' => $this->layout,
                'modelClass' => Item::class,
                'modelClassLang' => ItemLang::class,
                'redirect' => function () {
                    $page = Page::getPageResult();
                    return Url::toRoute(['/page/page/view', 'alias' => $page['alias']]);
                },
                'afterSaveCallback' => function () {
                    /**
                     * @var $growl \thread\modules\sys\modules\growl\components\Growl
                     */
                    $growl = Yii::$app->growl;
                    $growl->sendToUsersByRole('admin', 'Додано новий проект', 'notice', '/backend/map/item/list');
                }
            ],
            'fileupload' => [
                'class' => UploadAction::class,
                'path' => $this->module->getItemUploadPath(),
                'uploadOnlyImage' => false,
                'unique' => false,
            ],
            'filedelete' => [
                'class' => DeleteAction::class,
                'path' => $this->module->getItemUploadPath()
            ],
        ];
    }

    /**
     * @param $alias
     * @return string
     * @throws NotFoundHttpException
     */
    public function actionView($alias)
    {
        $model = Item::getByAlias($alias);
        if ($model == null) {
            throw new NotFoundHttpException;
        }

        $types = Map::typeRange();

        $this->breadcrumbs[] = [
            'label' => $types[$model['type']] ?? '',
            'url' => Map::getUrlTypeObjectListPage($model['type'])
        ];
        $this->breadcrumbs[] = [
            'label' => $model['lang']['title'],
        ];
        //SEO
        Yii::$app->metatag->registerModel($model);
        //SEO
        return $this->render('view', [
            'model' => $model,
            'area' => Area::findById($model['area_id']) ?? null
        ]);
    }

    /**
     * @return array
     */
    public function actionValidation()
    {
        $models = [];
        $id = (isset($_GET['id'])) ? $_GET['id'] : 0;
        /** @var Model $model */
        $model = ($id > 0) ? $this->findModel($id) : new $this->model;
        $model->setScenario('backend');
        //CATCH
        $model->type = 'project';
        $model->user_id = Yii::$app->getUser()->getId();
        $_POST['Item']['alias'] = $_POST['ItemLang']['title'];
        //
        $model->load(Yii::$app->getRequest()->post());
        $model->alias = $_POST['Item']['alias'];
        $models[] = $model;

        /** @var Model $modelLang */
        $modelLang = (class_exists($this->modelLang)) ? ($id) ? $this->findModelLang($id) : new $this->modelLang : null;
        if ($modelLang !== null) {
            $modelLang = new $this->modelLang;
            $modelLang->setScenario('backend');
            $modelLang->load(Yii::$app->getRequest()->post());
            $modelLang->rid = $model->id;
            $modelLang->lang = Yii::$app->language;
            $models[] = $modelLang;
        }

        Yii::$app->getResponse()->format = Response::FORMAT_JSON;

        return ActiveForm::validateMultiple($models);
    }

    /**
     * Пошук моделі по первинному ключу
     * Якщо модель не знайдена, повертається null
     * @param integer|array $id Ідентифікатор моделі
     * @return Model|null Повернення знайденої моделі
     */
    protected function findModel($id)
    {
        /** @var ActiveRecord $modelClass */
        $modelClass = $this->model;
        $keys = $modelClass::primaryKey();
        $model = null;
        if (count($keys) > 1) {
            $values = explode(',', $id);
            if (count($keys) === count($values)) {
                $model = $modelClass::findOne(array_combine($keys, $values));
            }
        } elseif ($id !== null) {
            $model = $modelClass::findOne($id);
        }
        return $model;
    }

    /**
     * Пошук мовної моделі по первинному ключу
     * Якщо модель не знайдена, повертається null
     * @param integer $id Ідентифікатор моделі
     * @return Model Lang Повернення знайденої моделі
     */
    protected function findModelLang($id)
    {
        if (!(class_exists($this->modelLang))) {
            return null;
        }
        $model = null;
        /** @var ActiveRecord $m */
        $m = new $this->modelLang;
        if ($id) {
            $model = $m->find()->andWhere(['rid' => $id])->one();
        }
        if ($model === null) {
            $model = $m->loadDefaultValues();
        }
        return $model;
    }


}