OSDN Git Service

Изменение импорта
[invent/invent.git] / controllers / LocationsController.php
1 <?php
2
3 namespace app\controllers;
4
5 use Yii;
6 use app\models\Locations;
7 use app\models\LocationsSearch;
8 use yii\web\Controller;
9 use yii\web\NotFoundHttpException;
10 use yii\filters\VerbFilter;
11 use app\models\User;
12
13 /**
14  * LocationsController implements the CRUD actions for Locations model.
15  */
16 class LocationsController 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      *        string|NULL  'region'    - наименование региона/подразделения
39      *        integer|NULL 'region_id' - идентификатор региона/подразделения
40      * @return integer|boolean - идентификатор записи места расположения или FALSE
41      */
42     public static function addIfNeed($options)
43     {
44         $result = [
45             'id'    => FALSE,
46             'error' => Yii::t('locations', 'Have not key fields location and region :') . print_r($options, TRUE),
47         ];
48         if (is_array($options) && isset($options[ 'location' ]) && (isset($options[ 'region' ]) || isset($options[ 'region_id' ])))
49         {
50             if (isset($options[ 'region' ]))
51             {
52                 $region = RegionsController::addIfNeed($options);
53             }
54             else
55             {
56                 $region_id = $options[ 'region_id' ];
57             }
58             if ($region['id'] !== FALSE) {
59                 // Ищем расположение, совпадающее по наименованию и региону/подразделению
60                 $location = Locations::find()
61                     ->where([ 'like', 'name', $options[ 'location' ]])
62                     ->andWhere([ 'region_id' => $region['id'] ])
63                     ->all();
64                 if (count($location) > 0)
65                 {
66                     // Если нашли, возвращаем идентификатор записи
67                     $result[ 'id' ] = $location[0]->id;
68                     $result[ 'error' ] = '';
69                 }
70                 else
71                 {
72                     // Не нашли, пробуем добавить место расположения
73                     $location = new Locations();
74                     $location->name = $options[ 'location' ];
75                     $location->region_id = $region[ 'id' ];
76                     if($location->validate() && $location->save())
77                     {
78                         // Если удалось сохранить, вернём идентификатор места расположения
79                         $result[ 'id' ] = $location->id;
80                         $result[ 'error' ] = '';
81                     }
82                     else
83                     {
84                         $result[ 'error' ] = Yii::t('locations', 'Error to create location "{location}"', $options);
85                     }
86                 }
87             }
88             else
89             {
90                 $result[ 'error' ] = $region[ 'error' ];
91             }
92         }
93         return $result; // Записать не удалось, вернём FALSE
94     }
95
96     /**
97      * Список всех мест/размещений.
98      * @return mixed
99      */
100     public function actionIndex()
101     {
102         if (! User::canPermission('createRecord'))
103         {
104             return $this->redirect(['site/index']);
105         }
106         $searchModel = new LocationsSearch();
107         $dataProvider = $searchModel->search(Yii::$app->request->queryParams);
108
109         return $this->render('index', [
110             'searchModel'  => $searchModel,
111             'dataProvider' => $dataProvider,
112         ]);
113     }
114
115     /**
116      * Показ одного места размещения (не используется).
117      * @param integer $id
118      * @return mixed
119      * @throws NotFoundHttpException если отсутствует место/размещение
120      */
121     public function actionView($id)
122     {
123         if (! User::canPermission('updateRecord'))
124         {
125             return $this->redirect(['index']);
126         }
127         return $this->render('view', [
128             'model' => $this->findModel($id),
129         ]);
130     }
131
132     /**
133      * Создание нового места/размещения.
134      * В случае успешного создания,  происходит переход к списку всех мест/размещений.
135      * @return mixed
136      */
137     public function actionCreate()
138     {
139         if (! User::canPermission('createRecord'))
140         {
141             return $this->redirect(['site/index']);
142         }
143         $model = new Locations();
144
145         if ($model->load(Yii::$app->request->post()) && $model->save())
146         {
147             return $this->redirect([ 'index', 'id' => $model->id ]);
148         }
149
150         return $this->render('create', [
151             'model' => $model,
152         ]);
153     }
154
155     /**
156      * Изменение существующего места/размещения.
157      * В случаае успешного изменения, происходит переход к списку всех мест/размещений.
158      * @param integer $id
159      * @return mixed
160      * @throws NotFoundHttpException если отсутствует место/размещение
161      */
162     public function actionUpdate($id)
163     {
164         if (! User::canPermission('updateRecord'))
165         {
166             return $this->redirect(['site/index']);
167         }
168         $model = $this->findModel($id);
169
170         if ($model->load(Yii::$app->request->post()) && $model->save())
171         {
172             return $this->redirect([ 'index', 'id' => $model->id ]);
173         }
174
175         return $this->render('update', [
176             'model' => $model,
177         ]);
178     }
179
180     /**
181      * Удаение существующего места/размещения.
182      * В случае успешного удаления, происходит переход к списку всех мест/размещений.
183      * @param integer $id
184      * @return mixed
185      * @throws NotFoundHttpException Усли отсутствует место/размещение
186      */
187     public function actionDelete($id)
188     {
189         if (! User::canPermission('updateRecord'))
190         {
191             return $this->redirect(['index']);
192         }
193         $this->findModel($id)->delete();
194
195         return $this->redirect([ 'index' ]);
196     }
197
198     /**
199      * Finds the Locations model based on its primary key value.
200      * If the model is not found, a 404 HTTP exception will be thrown.
201      * @param integer $id
202      * @return Locations the loaded model
203      * @throws NotFoundHttpException if the model cannot be found
204      */
205     protected function findModel($id)
206     {
207         if (($model = Locations::findOne($id)) !== null)
208         {
209             return $model;
210         }
211
212         throw new NotFoundHttpException(Yii::t('locations', 'The requested page does not exist.'));
213     }
214 }