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