Files
dredgenews/app/Services/OgImageResolver.php
T
dredgy 439139a057
linter / quality (push) Has been cancelled
tests / ci (8.3) (push) Has been cancelled
tests / ci (8.4) (push) Has been cancelled
tests / ci (8.5) (push) Has been cancelled
Done
2026-07-04 23:09:00 +10:00

41 lines
1.1 KiB
PHP

<?php
namespace App\Services;
use Illuminate\Support\Facades\Http;
class OgImageResolver
{
public function resolve(string $pageUrl): ?string
{
try {
$response = Http::withHeaders([
'User-Agent' => 'Mozilla/5.0 (compatible; DredgeNewsBot/1.0)',
])->timeout(8)->get($pageUrl);
if (! $response->successful()) {
return null;
}
libxml_use_internal_errors(true); // suppress warnings from imperfect HTML
$dom = new \DOMDocument();
$dom->loadHTML($response->body());
$xpath = new \DOMXPath($dom);
foreach (['og:image', 'twitter:image', 'twitter:image:src'] as $property) {
$node = $xpath->query("//meta[@property='{$property}']/@content")->item(0)
?? $xpath->query("//meta[@name='{$property}']/@content")->item(0);
if ($node && filled($node->nodeValue)) {
return $node->nodeValue;
}
}
return null;
} catch (\Throwable $e) {
report($e);
return null;
}
}
}