This commit is contained in:
foobar
2022-08-21 21:39:06 +02:00
commit 27c1969aaa
7354 changed files with 897064 additions and 0 deletions

View File

@@ -0,0 +1,54 @@
<?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];
}
}