fedi-feed-router/backend/app/Services/Http/HttpFetcher.php

81 lines
2.5 KiB
PHP
Raw Normal View History

2025-06-29 21:33:18 +02:00
<?php
namespace App\Services\Http;
use Illuminate\Support\Facades\Http;
use Exception;
class HttpFetcher
{
public static function fetchHtml(string $url): string
{
try {
$response = Http::get($url);
if (!$response->successful()) {
throw new Exception("Failed to fetch URL: {$url} - Status: {$response->status()}");
}
return $response->body();
} catch (Exception $e) {
logger()->error('HTTP fetch failed', [
'url' => $url,
'error' => $e->getMessage()
]);
throw $e;
}
}
2025-07-07 00:51:32 +02:00
/**
* @param array<int, string> $urls
* @return array<int, array<string, mixed>>
*/
2025-06-29 21:33:18 +02:00
public static function fetchMultipleUrls(array $urls): array
{
try {
$responses = Http::pool(function ($pool) use ($urls) {
foreach ($urls as $url) {
$pool->get($url);
}
});
return collect($responses)
->map(function ($response, $index) use ($urls) {
if (!isset($urls[$index])) {
return null;
}
$url = $urls[$index];
try {
if ($response->successful()) {
return [
'url' => $url,
'html' => $response->body(),
'success' => true
];
} else {
return [
'url' => $url,
'html' => null,
'success' => false,
'status' => $response->status()
];
}
} catch (Exception) {
return [
'url' => $url,
'html' => null,
'success' => false,
'error' => 'Exception occurred'
];
}
})
->filter(fn($result) => $result !== null)
->toArray();
} catch (Exception $e) {
logger()->error('Multiple URL fetch failed', ['error' => $e->getMessage()]);
return [];
}
}
}