Util.php 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. <?php
  2. /*
  3. * This file is part of the Monolog package.
  4. *
  5. * (c) Jordi Boggiano <j.boggiano@seld.be>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Monolog\Handler\Curl;
  11. class Util
  12. {
  13. private static $retriableErrorCodes = array(
  14. CURLE_COULDNT_RESOLVE_HOST,
  15. CURLE_COULDNT_CONNECT,
  16. CURLE_HTTP_NOT_FOUND,
  17. CURLE_READ_ERROR,
  18. CURLE_OPERATION_TIMEOUTED,
  19. CURLE_HTTP_POST_ERROR,
  20. CURLE_SSL_CONNECT_ERROR,
  21. );
  22. /**
  23. * Executes a CURL request with optional retries and exception on failure
  24. *
  25. * @param resource $ch curl handler
  26. * @throws \RuntimeException
  27. */
  28. public static function execute($ch, $retries = 5, $closeAfterDone = true)
  29. {
  30. while ($retries--) {
  31. if (curl_exec($ch) === false) {
  32. $curlErrno = curl_errno($ch);
  33. if (false === in_array($curlErrno, self::$retriableErrorCodes, true) || !$retries) {
  34. $curlError = curl_error($ch);
  35. if ($closeAfterDone) {
  36. curl_close($ch);
  37. }
  38. throw new \RuntimeException(sprintf('Curl error (code %s): %s', $curlErrno, $curlError));
  39. }
  40. continue;
  41. }
  42. if ($closeAfterDone) {
  43. curl_close($ch);
  44. }
  45. break;
  46. }
  47. }
  48. }