OSDN Git Service

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