41 lines
1.1 KiB
PHP
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;
|
|
}
|
|
}
|
|
}
|