55 lines
1.8 KiB
PHP
55 lines
1.8 KiB
PHP
<?php
|
|
|
|
namespace App\Http\Controllers;
|
|
|
|
use Illuminate\Support\Facades\Http;
|
|
use Illuminate\Http\Client\Response as ClientResponse;
|
|
use App\Models\City;
|
|
|
|
class WeatherstackController extends Controller
|
|
{
|
|
|
|
public static function requestByCity($city) {
|
|
$access_key = config('app.weatherstack_api_key');
|
|
$units = 'm'; /* m for Metric, s for Scientific, f for Fahrenheit */
|
|
$url = 'http://api.weatherstack.com/current';
|
|
|
|
return Http::acceptJson()->get($url, [
|
|
'access_key' => $access_key,
|
|
'units' => $units,
|
|
'query' => $city
|
|
]);
|
|
}
|
|
|
|
public function checkResponse($city, ClientResponse $response) {
|
|
if ($response->successful()) {
|
|
[$isValidResponse, $error] = $this->checkErrorMessage($city, $response);
|
|
}
|
|
elseif ($response->failed()) {
|
|
$isValidResponse = false;
|
|
$error = 'Request failed.';
|
|
}
|
|
|
|
return [$isValidResponse, $error];
|
|
}
|
|
|
|
public static function checkErrorMessage($city, ClientResponse $response) {
|
|
$isValidResponse = true;
|
|
$error = '';
|
|
|
|
if ($response->json('success') === false) {
|
|
$isValidResponse = false;
|
|
|
|
($response->json('error.type') === 'usage_limit_reached') ? $error = 'The usage limit of your API key has been reached.'
|
|
: $error = "No city named '{$city}' could be found.";
|
|
}
|
|
elseif (City::where('location_name', $response->json('location.name'))->exists()) {
|
|
$isValidResponse = false;
|
|
$error = "'{$response->json('location.name')}, {$response->json('location.country')}' has been already added.";
|
|
}
|
|
|
|
return [$isValidResponse, $error];
|
|
}
|
|
|
|
}
|