通过 API 请求验证 API 键和城市名称

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

我创建了一个自定义模块,在块中我使用来自 https://openweathermap.org/

的数据显示天气

本区块代码:
https://phpsandbox.io/n/sweet-forest-1lew-1wmof

我还有 WeatherForm.php 文件,其中添加了一个配置城市和一个需要显示天气的 API 键。

我需要添加表单验证:

  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'));
    }
  }

但我在代码审查后得到了这些评论:

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。我的代码应该是什么样子,这样它也可以通过 API 请求验证 API 键和城市名称?

我的表格的所有代码:
https://phpsandbox.io/n/spring-mountain-gdnn-emozx

为什么不同时使用两者,与我一起集思广益……

function validateWeatherData($city, $apikey) {
  try {
    $url = "https://api.openweather.org/data/2.5/weather?q=$city_name&appid=$api_key"; // Build the URL
    $response = file_get_contents($url); // You can use cURL here as well incase CORS blocks file_get_contents
        return $response; // Return the data from the call made above
  }
  catch (Exception $e) {
    return $e;
  }
}

 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'));
          return false; // Failed to validate city, return false go back start again
    }
    if (preg_match($pattern, $form_state->getValue('weather_city'))) {
      $form_state->setErrorByName('weather_city', $this->t('City name should not contain numbers')); 
          return false; // Failed to validate city, return false go back start again
    }
        $apikey = "ABCDEFG"; // API key (can be conditional based on city via CASE/IF when needed)
        $weatherdata = validateWeatherData($form_state->getValue('weather_city'), $apikey); // Validate weather data
        return $weatherdata; // Return validateWeatherData's response or do something else with it
 }