Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
| Total | |
20.45% |
9 / 44 |
|
0.00% |
0 / 2 |
CRAP | |
0.00% |
0 / 1 |
| HttpFetcher | |
20.45% |
9 / 44 |
|
0.00% |
0 / 2 |
49.77 | |
0.00% |
0 / 1 |
| fetchHtml | |
90.00% |
9 / 10 |
|
0.00% |
0 / 1 |
3.01 | |||
| fetchMultipleUrls | |
0.00% |
0 / 34 |
|
0.00% |
0 / 1 |
42 | |||
| 1 | <?php |
| 2 | |
| 3 | namespace App\Services\Http; |
| 4 | |
| 5 | use Illuminate\Support\Facades\Http; |
| 6 | use Exception; |
| 7 | |
| 8 | class HttpFetcher |
| 9 | { |
| 10 | public static function fetchHtml(string $url): string |
| 11 | { |
| 12 | try { |
| 13 | $response = Http::get($url); |
| 14 | |
| 15 | if (!$response->successful()) { |
| 16 | throw new Exception("Failed to fetch URL: {$url} - Status: {$response->status()}"); |
| 17 | } |
| 18 | |
| 19 | return $response->body(); |
| 20 | } catch (Exception $e) { |
| 21 | logger()->error('HTTP fetch failed', [ |
| 22 | 'url' => $url, |
| 23 | 'error' => $e->getMessage() |
| 24 | ]); |
| 25 | throw $e; |
| 26 | } |
| 27 | } |
| 28 | |
| 29 | /** |
| 30 | * @param array<int, string> $urls |
| 31 | * @return array<int, array<string, mixed>> |
| 32 | */ |
| 33 | public static function fetchMultipleUrls(array $urls): array |
| 34 | { |
| 35 | try { |
| 36 | $responses = Http::pool(function ($pool) use ($urls) { |
| 37 | foreach ($urls as $url) { |
| 38 | $pool->get($url); |
| 39 | } |
| 40 | }); |
| 41 | |
| 42 | return collect($responses) |
| 43 | ->map(function ($response, $index) use ($urls) { |
| 44 | if (!isset($urls[$index])) { |
| 45 | return null; |
| 46 | } |
| 47 | |
| 48 | $url = $urls[$index]; |
| 49 | |
| 50 | try { |
| 51 | if ($response->successful()) { |
| 52 | return [ |
| 53 | 'url' => $url, |
| 54 | 'html' => $response->body(), |
| 55 | 'success' => true |
| 56 | ]; |
| 57 | } else { |
| 58 | return [ |
| 59 | 'url' => $url, |
| 60 | 'html' => null, |
| 61 | 'success' => false, |
| 62 | 'status' => $response->status() |
| 63 | ]; |
| 64 | } |
| 65 | } catch (Exception) { |
| 66 | return [ |
| 67 | 'url' => $url, |
| 68 | 'html' => null, |
| 69 | 'success' => false, |
| 70 | 'error' => 'Exception occurred' |
| 71 | ]; |
| 72 | } |
| 73 | }) |
| 74 | ->filter(fn($result) => $result !== null) |
| 75 | ->toArray(); |
| 76 | } catch (Exception $e) { |
| 77 | logger()->error('Multiple URL fetch failed', ['error' => $e->getMessage()]); |
| 78 | return []; |
| 79 | } |
| 80 | } |
| 81 | } |