You are here

public function HttpClientMiddleware::__invoke in Raven: Sentry Integration 3.x

File

src/Http/HttpClientMiddleware.php, line 20

Class

HttpClientMiddleware
Instrument Guzzle HTTP requests.

Namespace

Drupal\raven\Http

Code

public function __invoke() {
  return function ($handler) {
    return function (RequestInterface $request, array $options) use ($handler) {
      $span = NULL;
      if (class_exists(SentrySdk::class) && ($parent = SentrySdk::getCurrentHub()
        ->getSpan())) {
        $context = new SpanContext();
        $context
          ->setOp('http.guzzle');
        $context
          ->setDescription($request
          ->getMethod() . ' ' . $request
          ->getUri());
        $span = $parent
          ->startChild($context);
      }
      $handlerPromiseCallback = static function ($responseOrException) use ($span) {
        if ($span) {
          $span
            ->finish();
        }
        if ($responseOrException instanceof \Throwable) {

          // @phpstan-ignore-next-line for compatibility with older Guzzle versions.
          return class_exists(Create::class) ? Create::rejectionFor($responseOrException) : rejection_for($responseOrException);
        }
        return $responseOrException;
      };
      return $handler($request, $options)
        ->then($handlerPromiseCallback, $handlerPromiseCallback);
    };
  };
}