There is a function that returns the name of the city. If the user’s ip exists and the site http://ip-api.com can determine the user’s location city by ip address, then the city name is taken from json, if not, then from the configuration.
public function getCity() { $ip = '193.62.157.66'; try { $response_ip = $this->httpClient->get('http://ip-api.com/json/' . $ip); $response_data_ip = $response_ip->getBody(); $data_ip = json_decode($response_data_ip); if ( $data_ip->status == 'success') { return $data_ip->city; } else { return $this->configFactory->get('sydneypro_weather.settings')->get('weather_city'); } } catch ( RequestException $e) { return FALSE; } }
But the configuration is added to ignore using the Config ignore module and when deploy the website to another environment, my configuration (which is ignored) will not be created in the db during drush cim
.
Therefore, if the configuration is missing, I need to return empty build array and throw an error to the drupal logger: https://api.drupal.org/api/drupal/core%21lib%21Drupal.php/function/Drupal%3A%3Alogger/8.2.x
I looked at several examples that drupal logger is used something like this:
Drupal::logger(' ')->error(' ', []);
But I don’t understand how in my case to return an empty build array, throw an error in drupal logger and where to insert all this in the code ? In catch
? Or somewhere else in the WeatherBlock block?
The code of my whole block WeatherBlock:
class WeatherBlock extends BlockBase implements ContainerFactoryPluginInterface { // dependency injection code here public function getCity() { $ip = '193.62.157.66'; try { $response_ip = $this->httpClient->get('http://ip-api.com/json/' . $ip); $response_data_ip = $response_ip->getBody(); $data_ip = json_decode($response_data_ip); if ( $data_ip->status == 'success') { return $data_ip->city; } else { return $this->configFactory->get('sydneypro_weather.settings')->get('weather_city'); } } catch ( RequestException $e) { return FALSE; } } public function build() { $client = $this->httpClient; $api_key = $this->configFactory->get('sydneypro_weather.settings')->get('weather_api_key'); $cid = 'sydneypro_weather'; if (empty( $api_key)) { return [ '#type' => 'markup', '#markup' => $this->t('Please enter your API key in the Admin panel to see the weather'), ]; } try { if ( $cache = $this->cacheBackend->get($cid)) { $data = $cache->data; } else { $response = $client->get('http://api.openweathermap.org/data/2.5/weather?q=' . $this->getCity() . ',&appid=' . $api_key . '&units=metric'); $response_data = $response->getBody(); $data = json_decode($response_data); $this->cacheBackend->set($cid, $data, $this->time->getRequestTime() + 21600); } $build = [ '#theme' => 'weather_block', '#data' => $data, '#attached' => [ 'library' => [ 'sydneypro_weather/sydneypro_weather', ], ], ]; return $build; } catch ( RequestException $e) { return [ '#markup' => Markup::create('<h1>Sorry, no data available</h1>'), ]; } } }