/** * Imports commodity information from EDDB */ public function actionCommodities() { $eddbApi = Yii::$app->params['eddb']['archive'] . 'commodities.json'; $curl = new Curl(); $curl->get($eddbApi); if ($curl->error) { throw new \yii\base\Exception('Error: ' . $curl->errorCode . ': ' . $curl->errorMessage); } // Iterate through all the categories via the curl response and insert them into the database foreach ($curl->response as $k => $obj) { $this->stdOut("Importing: "); $this->stdOut("{$obj->name}\r", Console::BOLD); $category = CommodityCategory::find()->where(['id' => $obj->category_id])->one(); if ($category === NULL) { $this->stdOut('Importing new category: ' . $obj->category->name . "\n"); $category = new CommodityCategory(); $category->id = $obj->category_id; } $category->name = $obj->category->name; $category->save(); // Import the commodity $commodity = Commodity::find()->where(['id' => $obj->id])->one(); if ($commodity === NULL) { $this->stdOut('Importing new commodity: ' . $obj->name . "\n"); $commodity = new Commodity(); $commodity->id = $obj->id; $commodity->name = $obj->name; } $commodity->average_price = $obj->average_price; $commodity->category_id = $obj->category_id; $commodity->save(); } $this->stdOut("\n\r"); }
/** * Paginated endpoint for display all commodities from Eddb * @return array */ public function actionIndex() { $query = Commodity::find(); if (Yii::$app->request->get('category', false)) { // Find the requested category first $category = CommodityCategory::find()->where(['name' => Inflector::humanize(Yii::$app->request->get('category', NULL))])->one(); if ($category === NULL) { throw new HttpException(404, 'Could not find commodities for the requested category'); } // Append it to the query $query->andWhere(['category_id' => $category->id]); } // Also provide filtering by name if (Yii::$app->request->get('name', false)) { $query->andWhere(['name' => Inflector::humanize(Yii::$app->request->get('name', 'nothing'))]); } return ResponseBuilder::build($query, 'commodities', Yii::$app->request->get('sort', 'id'), Yii::$app->request->get('order', 'asc')); }
/** * @return \yii\db\ActiveQuery */ public function getCategory() { return $this->hasOne(CommodityCategory::className(), ['id' => 'category_id']); }