@aleksandrkotov

Validate the API key and the city name by the API?

Я создал кастомный модуль, где в блоке отображаю погоду, используя данные из https://openweathermap.org/

Код этого блока:
https://phpsandbox.io/n/sweet-forest-1lew-1wmof

Также у меня есть файл WeatherForm.php с формой, которая добавляет в конфигурацию город и API-key, необходие чтобы отображать погоду.

Мне нужно было добавить проверку формы:
1. поля не должны быть пустыми
2. Название города не должно содержать цифр

Я сделал это следующим образом:

public function validateForm(array &$form, FormStateInterface $form_state) {
    $pattern = '/[0-9]/';

    if (empty($form_state->getValue('weather_city'))) {
      $form_state->setErrorByName('weather_city', $this->t('Fields should not be empty'));
    }
    if (preg_match($pattern, $form_state->getValue('weather_city'))) {
      $form_state->setErrorByName('weather_city', $this->t('City name should not contain numbers'));
    }
  }

Но я получил это замечание после code review:

Also, will be good to validate the API key and the city name by the API request.


Я нашел пример как это реализовать:

public function validateWeatherData(string $city_name, $api_key):bool {
  try {
    $url = "https://api.openweather.org/data/2.5/weather?q=$city_name&appid=$api_key";
    $response = $this->client->request('GET', $url);
    if ($response->getStatusCode() != 200) {
      throw new \Exception('Failed to retrieve data.');
    }
    $reg_ex = "#^[A-Za-z-]=$#";
    return preg_match($reg_ex, $city_name);
  }
  catch (GuzzleException $e) {
    return FALSE;
  }
}


Но я не знаю, как интегрировать код примера в мою функцию validateForm. Подскажите пожалуйста как это сделать?
Весь код моей формы:
https://phpsandbox.io/n/spring-mountain-gdnn-emozx
  • Вопрос задан
  • 22 просмотра
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы