OSDN Git Service

Добавлен контроль доступа по ролям (RBAC). Пользователи хранятся в базе данных. Созда...
[invent/invent.git] / controllers / RegionsController.php
1 <?php
2
3 namespace app\controllers;
4
5 use Yii;
6 use app\models\Regions;
7 use app\models\RegionsSearch;
8 use yii\web\Controller;
9 use yii\web\NotFoundHttpException;
10 use yii\filters\VerbFilter;
11 use app\models\User;
12
13 /**
14  * RegionsController implements the CRUD actions for Regions model.
15  */
16 class RegionsController extends Controller
17 {
18     /**
19      * {@inheritdoc}
20      */
21     public function behaviors()
22     {
23         return [
24             'verbs' => [
25                 'class'   => VerbFilter::className(),
26                 'actions' => [
27                     'delete' => [ 'POST' ],
28                 ],
29             ],
30         ];
31     }
32
33     /**
34      * Добавление региона/подразделения
35      *
36      * @param array $options
37               string 'name'    - наименование
38      * @return integer|boolean - Идентификатор записи или FALSE, если записать не удалось
39      */
40     public function addIfNeed($options)
41     {
42         if (is_array($options) && isset($options[ 'name' ]))
43         {
44             // Ищем регион
45             $region = Regions::find()
46                 ->where(['like', 'name', $options[ 'name' ]])
47                 ->all();
48             if (count($region) > 0)
49             {
50                 return $region[0]->id; // Нашёлся, вернём первый найденный
51             }
52             $region = new Regions();   // Не нашёлся, добавляем новый
53             $region->name = $options[ 'name' ];
54             if ($region->validate() && $region->save()) // Пробуем записать
55             {
56                 return $region->id; // Если удалось записать, возвращаем идентификатор
57             }
58         }
59         return FALSE; // Если не удалась запись, вернём FALSE
60     }
61
62     /**
63      * Список всех регионов/подразделений.
64      * @return mixed
65      */
66     public function actionIndex()
67     {
68         if (! User::canPermission('createRecord'))
69         {
70             return $this->redirect(['site/index']);
71         }
72         $searchModel  = new RegionsSearch();
73         $dataProvider = $searchModel->search(Yii::$app->request->queryParams);
74
75         return $this->render('index', [
76             'searchModel'  => $searchModel,
77             'dataProvider' => $dataProvider,
78         ]);
79     }
80
81     /**
82      * Плказ одного региона/подразделения (не используется).
83      * @param integer $id
84      * @return mixed
85      * @throws NotFoundHttpException если отсутствует регион/подразделение
86      */
87     public function actionView($id)
88     {
89         if (! User::canPermission('updateRecord'))
90         {
91             return $this->redirect(['site/index']);
92         }
93         return $this->render('view', [
94             'model' => $this->findModel($id),
95         ]);
96     }
97
98     /**
99      * Создание нового региона/подразделения.
100      * В случае успешного создания региона/подразделения, происходит переход к списку всех регионов/подразделений.
101      * @return mixed
102      */
103     public function actionCreate()
104     {
105         if (! User::canPermission('createRecord'))
106         {
107             return $this->redirect(['site/index']);
108         }
109         $model = new Regions();
110
111         if ($model->load(Yii::$app->request->post()) && $model->save())
112         {
113             return $this->redirect([ 'index', 'id' => $model->id ]);
114         }
115
116         return $this->render('create', [
117             'model' => $model,
118         ]);
119     }
120
121     /**
122      * Изменение существующего региона/подразделения.
123      * В случае успешного редактирования, происходит переход к списку всех ергионов/подразделений.
124      * @param integer $id
125      * @return mixed
126      * @throws NotFoundHttpException если отсутствует регион/подразделение
127      */
128     public function actionUpdate($id)
129     {
130         if (! User::canPermission('updateRecord'))
131         {
132             return $this->redirect(['site/index']);
133         }
134         $model = $this->findModel($id);
135
136         if ($model->load(Yii::$app->request->post()) && $model->save())
137         {
138             return $this->redirect([ 'index', 'id' => $model->id ]);
139         }
140
141         return $this->render('update', [
142             'model' => $model,
143         ]);
144     }
145
146     /**
147      * Удаление существующего региона/подразделения.
148      * В случае успешного удаления, происходит переход к списку всех регоинов/подразделений.
149      * @param integer $id
150      * @return mixed
151      * @throws NotFoundHttpException если отсутсвует регион/подразделение
152      */
153     public function actionDelete($id)
154     {
155         if (! User::canPermission('updateRecord'))
156         {
157             return $this->redirect(['site/index']);
158         }
159         $this->findModel($id)->delete();
160
161         return $this->redirect([ 'index' ]);
162     }
163
164     /**
165      * Finds the Regions model based on its primary key value.
166      * If the model is not found, a 404 HTTP exception will be thrown.
167      * @param integer $id
168      * @return Regions the loaded model
169      * @throws NotFoundHttpException if the model cannot be found
170      */
171     protected function findModel($id)
172     {
173         if (($model = Regions::findOne($id)) !== null)
174         {
175             return $model;
176         }
177
178         throw new NotFoundHttpException(Yii::t('regions', 'The requested page does not exist.'));
179     }
180 }