Exemplo n.º 1
0
 /**
  * Gets heroes list from STEAM API and loads them to database (in heroes table)
  *
  * @author Dzianis Kotau <*****@*****.**>
  * @return int Exit code
  */
 public function actionHeroList()
 {
     try {
         $data = $this->getRawData(self::METHOD_URL_HERO_LIST);
     } catch (Exception $e) {
         if (!$this->quiet) {
             $this->stderr('An error occurred while fetching data from remote API method URL "' . self::METHOD_URL_HERO_LIST . '" with error: "' . $e->getMessage() . '"' . PHP_EOL, Console::FG_RED);
         }
         return self::EXIT_CODE_BAD_RAW_DATA;
     }
     $data = $data['result']->{'heroes'};
     if (empty($data)) {
         if (!$this->quiet) {
             $this->stdout('Nothing to update.' . PHP_EOL, Console::FG_YELLOW);
         }
         return self::EXIT_CODE_NORMAL;
     }
     $data = array_map(function ($val) {
         $val->{'id'} = (int) $val->{'id'};
         $val->{'name'} = trim($val->{'name'});
         $val->{'localized_name'} = trim($val->{'localized_name'});
         return $val;
     }, $data);
     $newIds = [];
     foreach ($data as $val) {
         $newIds[] = (int) $val->{'id'};
     }
     $heroes = $leagues = Hero::find()->asArray()->all();
     $oldIds = [];
     foreach ($heroes as $hero) {
         $oldIds[] = (int) $hero['id'];
     }
     $inactiveIds = array_diff($oldIds, $newIds);
     $newIds = array_diff($newIds, $oldIds);
     $data = array_filter($data, function ($val) use($inactiveIds) {
         return !in_array($val->{'id'}, $inactiveIds);
     });
     $dataInsert = array_filter($data, function ($val) use($newIds) {
         return in_array($val->{'id'}, $newIds);
     });
     $dataUpdate = array_filter($data, function ($val) use($newIds) {
         return !in_array($val->{'id'}, $newIds);
     });
     foreach ($dataUpdate as $val) {
         /** @var Hero $model */
         $model = Hero::findOne($val->{'id'});
         if ($model->id === $val->{'id'} && $model->name === $val->{'name'} && $model->localized_name === $val->{'localized_name'}) {
             // noting to update
             continue;
         }
         $model->id = $val->{'id'};
         $model->name = $val->{'name'};
         $model->localized_name = $val->{'localized_name'};
         $model->active = true;
         $model->save();
     }
     $model = new Hero();
     $model->addHeroes($dataInsert);
     $model->disableHeroes($inactiveIds);
     if ($this->verbose) {
         $this->stdout('All done.' . PHP_EOL, Console::FG_GREEN);
     }
     return self::EXIT_CODE_NORMAL;
 }
Exemplo n.º 2
0
 /**
  * @return \yii\db\ActiveQuery
  */
 public function getHero()
 {
     return $this->hasOne(Hero::className(), ['id' => 'hero_id']);
 }