Skip to content

Instantly share code, notes, and snippets.

@tomasnorre
Last active April 22, 2021 21:04
Show Gist options
  • Save tomasnorre/4326a23b6a4b5e8e9be75846f83b392b to your computer and use it in GitHub Desktop.
Save tomasnorre/4326a23b6a4b5e8e9be75846f83b392b to your computer and use it in GitHub Desktop.
DataServer to Fetch JSON from URL and store in cache.
<?php
declare(strict_types=1);
namespace App\Services;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\GuzzleException;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;
use stdClass;
class DataService
{
public function getDataFromUrl(string $url): stdClass
{
$response = null;
$client = new Client();
try {
$response = $client->get($url);
} catch (GuzzleException $e) {
Log::error('GuzzleRequest Failed: ' . $e->getMessage());
}
$cacheIdentifier = sha1($url);
if ($response !== null
&& Cache::has($cacheIdentifier . '-etag')
&& $response->getHeader('ETag')[0] === Cache::get($cacheIdentifier . '-etag')
) {
return Cache::get($cacheIdentifier);
}
Cache::put($cacheIdentifier, json_decode((string) $response->getBody(), false, 512, JSON_THROW_ON_ERROR));
Cache::put($cacheIdentifier . '-etag', $response->getHeader('ETag')[0]);
return Cache::get($cacheIdentifier);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment