SettingsController.php 2.8 KB
<?php
    namespace backend\controllers;
    
    use backend\models\Mail;
    use common\models\Settings;
    use yii\base\InvalidConfigException;
    use yii\base\Model;
    use yii\filters\AccessControl;
    use yii\web\Controller;
    use Yii;
    use yii2tech\filedb\ActiveQuery;

    /**
     * Class SettingsController
     *
     * @package artbox\core\controllers
     */
    class SettingsController extends Controller
    {
        /**
         * @inheritdoc
         */
        public function behaviors()
        {
            return [
                'access' => [
                    'class' => AccessControl::className(),
                    'rules' => [
                        [
                            'actions' => [
                                'login',
                                'error',
                            ],
                            'allow'   => true,
                        ],
                        [
                            'allow' => true,
                            'roles' => [ '@' ],
                        ],
                    ],
                ],
            ];
        }
        
        /**
         * Display site settings page
         *
         * @return string|\yii\web\Response
         */
        public function actionIndex()
        {
            $model = $this->findSettings();
            $mail = Mail::findOne(1);
            if ($model->load(Yii::$app->request->post()) && Model::loadMultiple($model->getVariationModels(), \Yii::$app->request->post())) {
                foreach ($model->getVariationModels() as $index => $lang){
                    $lang->id = $index+1;
                }
                $model->save();
                Yii::$app->session->setFlash('success', \Yii::t('core', 'Settings saved'));
                $mail->load(Yii::$app->request->post());
                $mail->save();
                return $this->goHome();
            }
            
            return $this->render(
                'settings',
                [
                    'model' => $model,
                    'mail'  => $mail
                ]
            );
        }
        
        
        
        /**
         * Find site settings
         *
         * @return \yii2tech\filedb\ActiveRecord
         * @throws \yii\base\InvalidConfigException
         */
        public function findSettings()
        {
            if ($model = Settings::find()
                                 ->with(['languages' => function (ActiveQuery $query){
                                    $query->indexBy('id');
                                 }])
                                 ->one()
            ) {
                return $model;
            } else {
                throw new InvalidConfigException('Файл настроек не найден');
            }
        }
        
    }