Skip to content

Instantly share code, notes, and snippets.

@neverything
Last active July 8, 2024 06:32
Show Gist options
  • Save neverything/504a030ebff5f52bb8cabd7a9c6568b7 to your computer and use it in GitHub Desktop.
Save neverything/504a030ebff5f52bb8cabd7a9c6568b7 to your computer and use it in GitHub Desktop.
<?php
declare(strict_types=1);
namespace App\FaviconFetcher\Drivers;
use AshAllenDesign\FaviconFetcher\Collections\FaviconCollection;
use AshAllenDesign\FaviconFetcher\Concerns\HasDefaultFunctionality;
use AshAllenDesign\FaviconFetcher\Concerns\MakesHttpRequests;
use AshAllenDesign\FaviconFetcher\Concerns\ValidatesUrls;
use AshAllenDesign\FaviconFetcher\Contracts\Fetcher;
use AshAllenDesign\FaviconFetcher\Exceptions\FaviconFetcherException;
use AshAllenDesign\FaviconFetcher\Exceptions\FaviconNotFoundException;
use AshAllenDesign\FaviconFetcher\Exceptions\FeatureNotSupportedException;
use AshAllenDesign\FaviconFetcher\Exceptions\InvalidUrlException;
use AshAllenDesign\FaviconFetcher\Favicon;
use Illuminate\Http\Client\Response;
class UnavatarServices implements Fetcher
{
use HasDefaultFunctionality;
use MakesHttpRequests;
use ValidatesUrls;
private const BASE_URL = 'https://unavatar.io/';
/**
* Attempt to fetch the favicon for the given URL.
*
*
* @throws InvalidUrlException
* @throws FaviconNotFoundException
* @throws FaviconFetcherException
*/
public function fetch(string $url): ?Favicon
{
if (! $this->urlIsValid($url)) {
throw new InvalidUrlException($url.' is not a valid URL');
}
if ($this->useCache && $favicon = $this->attemptToFetchFromCache($url)) {
return $favicon;
}
$urlWithoutProtocol = str_replace(['https://', 'http://'], '', $url);
$patterns = [
'/github.com\/([a-zA-Z0-9-]+)/' => 'github/',
'/(?:twitter.com|x.com)\/([a-zA-Z0-9-]+)/' => 'twitter/',
];
foreach ($patterns as $pattern => $prefix) {
if (preg_match($pattern, $urlWithoutProtocol, $matches)) {
$urlWithoutProtocol = $prefix.$matches[1];
break;
}
}
$faviconUrl = self::BASE_URL.$urlWithoutProtocol.'?fallback=false';
$response = $this->withRequestExceptionHandling(
fn (): Response => $this->httpClient()->get($faviconUrl)
);
return $response->successful()
? new Favicon(url: $url, faviconUrl: $faviconUrl, fromDriver: $this)
: $this->notFound($url);
}
/**
* @throws FeatureNotSupportedException
*/
public function fetchAll(string $url): FaviconCollection
{
throw new FeatureNotSupportedException('The Unavatar API does not support fetching all favicons.');
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment