Initial
This commit is contained in:
86
app/Remote/ImageFetcher.php
Normal file
86
app/Remote/ImageFetcher.php
Normal file
@@ -0,0 +1,86 @@
|
||||
<?php
|
||||
|
||||
namespace App\Remote;
|
||||
|
||||
use App\Enum\MimeType;
|
||||
use Illuminate\Http\Client\ConnectionException;
|
||||
use Illuminate\Support\Facades\Cache;
|
||||
use Illuminate\Support\Facades\Http;
|
||||
|
||||
class ImageFetcher
|
||||
{
|
||||
|
||||
private array $options = [
|
||||
'cache' => [
|
||||
'enabled' => true,
|
||||
'prefix' => 'image_fetcher_',
|
||||
'ttl' => 3600,
|
||||
],
|
||||
'http' => [
|
||||
'timeout' => 60,
|
||||
'userAgent' => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36'
|
||||
]
|
||||
];
|
||||
|
||||
public function __construct(private readonly string $url = "")
|
||||
{
|
||||
// Global useragent
|
||||
Http::globalRequestMiddleware(fn ($request) => $request->withHeader(
|
||||
'User-Agent', $this->options['http']['userAgent']
|
||||
));
|
||||
}
|
||||
|
||||
public function forget(): bool
|
||||
{
|
||||
if (!$this->options['cache']['enabled']) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return Cache::forget($this->cacheName($this->url));
|
||||
}
|
||||
|
||||
public function getExtension(): string
|
||||
{
|
||||
$path = parse_url($this->url, PHP_URL_PATH);
|
||||
return pathinfo($path, PATHINFO_EXTENSION);
|
||||
}
|
||||
|
||||
public function getMimeType(): MimeType
|
||||
{
|
||||
return MimeType::{$this->getExtension()};
|
||||
}
|
||||
|
||||
private function cacheName(string $url): string
|
||||
{
|
||||
return $this->options['cache']['prefix'] . base64_encode($url);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return bool
|
||||
*/
|
||||
protected function isCached(): bool
|
||||
{
|
||||
return $this->options['cache']['enabled'] && Cache::has($this->cacheName($this->url));
|
||||
}
|
||||
|
||||
/**
|
||||
* @throws ConnectionException
|
||||
*/
|
||||
public function fetch()
|
||||
{
|
||||
if ($this->isCached()) {
|
||||
return Cache::get($this->cacheName($this->url));
|
||||
}
|
||||
|
||||
$response = Http::timeout($this->options['http']['timeout'])->get($this->url);
|
||||
$image = $response->body();
|
||||
|
||||
// Write to cache
|
||||
if ($this->options['cache']['enabled']) {
|
||||
Cache::add($this->cacheName($this->url), $image, $this->options['cache']['ttl']);
|
||||
}
|
||||
|
||||
return $image;
|
||||
}
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user