OSDN Git Service

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