OSDN Git Service

Возвращение обработки тестов только на php 7.4
[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         $result = [
43             'id' => FALSE,
44             'error' => Yii::t('regions', 'Regions: Key field "region" missing: ') . print_r($options, TRUE),
45         ];
46         if (is_array($options) && isset($options[ 'region' ]))
47         {
48             // Ищем регион
49             $model = Regions::find()
50                 ->where(['like', 'name', $options[ 'region' ]])
51                 ->all();
52             if (count($model) > 0)
53             {
54                 $result[ 'id' ] = $model[0]->id; // Нашёлся, вернём первый найденный
55                 $result[ 'error' ] = '';
56             }
57             else
58             {
59                 $model = new Regions();   // Не нашёлся, добавляем новый
60                 $model->name = $options[ 'region' ];
61                 if ($model->validate() && $model->save()) // Пробуем записать
62                 {
63                     $result[ 'id' ] = $model->id; // Если удалось записать, возвращаем идентификатор
64                     $result[ 'error' ] = '';
65                 }
66                 else
67                 {
68                     $result[ 'error' ] = Yii::t('regions', 'Regions: can\'t add region "{region}": ', $options) . print_r($model->errors, TRUE);
69                 }
70             }
71         }
72         return $result; // Если не удалась запись, вернём FALSE
73     }
74
75     /**
76      * Список всех регионов/подразделений.
77      * @return mixed
78      */
79     public function actionIndex()
80     {
81         if (! User::canPermission('createRecord'))
82         {
83             return $this->redirect(['site/index']);
84         }
85         $searchModel  = new RegionsSearch();
86         if (isset(Yii::$app->request->queryParams['id'])) {
87             $id = Yii::$app->request->queryParams['id'];
88             $dataProvider = $searchModel->search(Yii::$app->request->queryParams);
89             //$dataProvider->query->select(Regions::tableName() . '.id');
90             $pageSize = $dataProvider->pagination->pageSize;
91             $dataProvider->pagination = FALSE;
92             $rows = $dataProvider->getModels();
93             $page = 0;
94             foreach ($rows as $key => $val) {
95                 if ($id == $val->id) {
96                     $page = ceil(($key + 1) / $pageSize);
97                     break;
98                 }
99             }
100             return $this->redirect(['index', 'page' => $page]);
101         }
102         $dataProvider = $searchModel->search(Yii::$app->request->queryParams);
103
104         return $this->render('index', [
105             'searchModel'  => $searchModel,
106             'dataProvider' => $dataProvider,
107         ]);
108     }
109
110     /**
111      * Плказ одного региона/подразделения (не используется).
112      * @param integer $id
113      * @return mixed
114      * @throws NotFoundHttpException если отсутствует регион/подразделение
115      */
116     public function actionView($id)
117     {
118         if (! User::canPermission('updateRecord'))
119         {
120             return $this->redirect(['site/index']);
121         }
122         return $this->render('view', [
123             'model' => $this->findModel($id),
124         ]);
125     }
126
127     /**
128      * Создание нового региона/подразделения.
129      * В случае успешного создания региона/подразделения, происходит переход к списку всех регионов/подразделений.
130      * @return mixed
131      */
132     public function actionCreate()
133     {
134         if (! User::canPermission('createRecord'))
135         {
136             return $this->redirect(['site/index']);
137         }
138         $model = new Regions();
139
140         if ($model->load(Yii::$app->request->post()) && $model->save())
141         {
142             return $this->redirect([ 'index', 'id' => $model->id ]);
143         }
144
145         return $this->render('create', [
146             'model' => $model,
147         ]);
148     }
149
150     /**
151      * Изменение существующего региона/подразделения.
152      * В случае успешного редактирования, происходит переход к списку всех ергионов/подразделений.
153      * @param integer $id
154      * @return mixed
155      * @throws NotFoundHttpException если отсутствует регион/подразделение
156      */
157     public function actionUpdate($id)
158     {
159         if (! User::canPermission('updateRecord'))
160         {
161             return $this->redirect(['site/index']);
162         }
163         $model = $this->findModel($id);
164
165         if ($model->load(Yii::$app->request->post()) && $model->save())
166         {
167             return $this->redirect([ 'index', 'id' => $model->id ]);
168         }
169
170         return $this->render('update', [
171             'model' => $model,
172         ]);
173     }
174
175     /**
176      * Удаление существующего региона/подразделения.
177      * В случае успешного удаления, происходит переход к списку всех регоинов/подразделений.
178      * @param integer $id
179      * @return mixed
180      * @throws NotFoundHttpException если отсутсвует регион/подразделение
181      */
182     public function actionDelete($id)
183     {
184         if (! User::canPermission('updateRecord'))
185         {
186             return $this->redirect(['site/index']);
187         }
188         $this->findModel($id)->delete();
189
190         return $this->redirect([ 'index' ]);
191     }
192
193     /**
194      * Finds the Regions model based on its primary key value.
195      * If the model is not found, a 404 HTTP exception will be thrown.
196      * @param integer $id
197      * @return Regions the loaded model
198      * @throws NotFoundHttpException if the model cannot be found
199      */
200     protected function findModel($id)
201     {
202         if (($model = Regions::findOne($id)) !== null)
203         {
204             return $model;
205         }
206
207         throw new NotFoundHttpException(Yii::t('regions', 'The requested page does not exist.'));
208     }
209 }