/** * Сохраняем код страны отправителя * @param bool $insert * @return bool */ function beforeSave($insert) { if (parent::beforeSave($insert)) { if ($this->ip) { $geoip = new GeoIP(); $geoip->setHost(long2ip($this->ip)); try { $this->country_code = $geoip->getCountryCode(); } catch (\Exception $e) { } } return true; } else { return false; } }
/** * Устанавливает коды стран отправителей исходя из IP адресов * @throws \Exception */ function actionIndex() { if (!extension_loaded('geoip')) { throw new \Exception(Console::ansiFormat('Расширение GeoIP недоступно')); } $comments = Comments::find()->where(['country_code' => null])->all(); $geoip = new GeoIP(); foreach ($comments as $item) { if (!$item->country_code) { $ip = long2ip($item->ip); try { $geoip->setHost($ip); $code = $geoip->getCountryCode(); $item->country_code = $code; $item->save(); echo Console::ansiFormat($item->id . ': ' . $ip . ' - ' . $code, [Console::FG_GREEN]) . PHP_EOL; } catch (\Exception $e) { echo Console::ansiFormat($item->id . ': ' . $ip . ' - ' . 'host не обнаружен!', [Console::FG_RED]) . PHP_EOL; } } } }