Skip to content

Instantly share code, notes, and snippets.

@webrobert
Last active January 13, 2023 23:36
Show Gist options
  • Select an option

  • Save webrobert/01855c974fb3bc1c345ee151800b3e45 to your computer and use it in GitHub Desktop.

Select an option

Save webrobert/01855c974fb3bc1c345ee151800b3e45 to your computer and use it in GitHub Desktop.
a code snippet for using Pool Client to check urls are valid. It was an answer I wrote for laracasts.

Use Http Pool Client to check urls are valid.

This was orginally an answer I wrote for Laracasts.

$urls = collect([
    'http://google.com',
    'http://googsdfsdle.com',
    'http://yelp.com',
    'http://testwwerer.com',
]);

// make requests
$responses = Http::pool( fn(Pool $pool) =>
    $urls->each( fn($url) => $pool->head($url))
);

// check responses
$keyedResponses = collect($responses)->map( fn($response) => match (true) {

    $response instanceof \Illuminate\Http\Client\Response
    && $response->ok()
        => 'good url',

    $response instanceof \GuzzleHttp\Exception\ConnectException
    && Str::contains($response->getMessage(), 'cURL error 6: Could not resolve host:')
        => 'Could not resolve',

    default
    // maybe double check this url. There could have been some other network issue, etc...
        => 'something else happened'

});

// process results
$urls->each(fn ($item, $key) => match($keyedResponses[$key]) {
    'good url' => dump("save $item its good"), // InternalUrls::update([ ... ]),
    'Could not resolve' => dump("kill $item its bad"), // mark as bad
    'something else happened' => dump("something else happened with $item") // mark for recheck
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment