Done
This commit is contained in:
@@ -0,0 +1,40 @@
|
||||
<?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;
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user