Commit d4f9aaa5 authored by Primoz Hmeljak's avatar Primoz Hmeljak
Browse files

Issue #3259736 by Primsi: Handle failed pexels request more graciously

parent 9bdfb26e
Loading
Loading
Loading
Loading
+58 −1
Original line number Diff line number Diff line
@@ -4,6 +4,13 @@ namespace Drupal\media_pexels;

use Drupal\Core\File\FileSystemInterface;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\ConnectException;
use GuzzleHttp\Exception\RequestException;
use GuzzleHttp\Handler\CurlHandler;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Middleware;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\Psr7\Response;

/**
 * Provides integration with Pexels api.
@@ -11,6 +18,8 @@ use GuzzleHttp\Client;
class PexelsClient {

  const API_URL = 'https://api.pexels.com/v1/';
  const RETRY_TIMES = 2;
  const RETRY_DELAY = 1500;

  /**
   * The http client.
@@ -58,7 +67,11 @@ class PexelsClient {
   * @throws \GuzzleHttp\Exception\GuzzleException
   */
  public function doRequest(string $url): array {
    $result = $this->httpClient
    $handler_stack = HandlerStack::create(new CurlHandler());
    $handler_stack->push(Middleware::retry($this->retryDecider(), $this->retryDelay()));
    $http_client = new Client(['handler' => $handler_stack]);

    $result = $http_client
      ->request('GET', $url, [
          'headers' => [
            'Authorization' => $this->getApiKey(),
@@ -217,4 +230,48 @@ class PexelsClient {
    return $this->fileSystem->saveData($data, $path, $replace);
  }


  /**
   * The retry decinder.
   *
   * @return \Closure
   *   The retry decider.
   */
  public function retryDecider(): \Closure {
    return function ($retries, Request $request, Response $response = NULL, RequestException $exception = NULL) {
      if ($retries >= self::RETRY_TIMES) {
        return FALSE;
      }

      // Retry connection exceptions.
      if ($exception instanceof ConnectException) {
        return TRUE;
      }
      elseif ($exception instanceof RequestException) {
        return TRUE;
      }

      if ($response) {
        // Retry on server errors.
        if ($response->getStatusCode() >= 500) {
          return TRUE;
        }
      }

      return FALSE;
    };
  }

  /**
   * The retry delay.
   *
   * @return \Closure
   *   The retry delay.
   */
  public function retryDelay(): \Closure {
    return function ($number_of_retries) {
      return self::RETRY_DELAY;
    };
  }

}
+3 −2
Original line number Diff line number Diff line
@@ -152,7 +152,7 @@ class PexelsWidget extends WidgetBase {
   *   Logger factory.
   */
  public function setLogger(LoggerChannelFactoryInterface  $logger_factory) {
    $this->logger = $logger_factory;
    $this->loggerFactory = $logger_factory;
  }

  /**
@@ -413,8 +413,9 @@ class PexelsWidget extends WidgetBase {
        $search_results = $results['contents'];
      }
      catch (\Exception $e) {
        $this->messenger()->addError('There was an error while fetching the results. Please contact the system administrator');
        $this->messenger()->addError('There was an error while fetching the results. Please contact the system administrator.');
        $this->loggerFactory->get('media_pexels')->error($e->getMessage());
        return $form;
      }

      if (isset($search_results['total_results']) && $search_results['total_results'] != 0) {