You are here

HttpClientMiddleware.php in Raven: Sentry Integration 3.x

Namespace

Drupal\raven\Http

File

src/Http/HttpClientMiddleware.php
View source
<?php

namespace Drupal\raven\Http;

use GuzzleHttp\Promise\Create;
use Psr\Http\Message\RequestInterface;
use Sentry\SentrySdk;
use Sentry\Tracing\SpanContext;
use function GuzzleHttp\Promise\rejection_for;

/**
 * Instrument Guzzle HTTP requests.
 */
class HttpClientMiddleware {

  /**
   * {@inheritdoc}
   */
  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);
      };
    };
  }

}

Classes

Namesort descending Description
HttpClientMiddleware Instrument Guzzle HTTP requests.