vendor/eightpoints/guzzle-bundle/src/Middleware/RequestTimeMiddleware.php line 43

Open in your IDE?
  1. <?php
  2. namespace EightPoints\Bundle\GuzzleBundle\Middleware;
  3. use EightPoints\Bundle\GuzzleBundle\Log\Logger;
  4. use EightPoints\Bundle\GuzzleBundle\Log\LoggerInterface;
  5. use EightPoints\Bundle\GuzzleBundle\DataCollector\HttpDataCollector;
  6. use Psr\Http\Message\RequestInterface;
  7. use GuzzleHttp\TransferStats;
  8. class RequestTimeMiddleware
  9. {
  10.     /** @var \EightPoints\Bundle\GuzzleBundle\Log\LoggerInterface */
  11.     protected $logger;
  12.     /** @var \EightPoints\Bundle\GuzzleBundle\DataCollector\HttpDataCollector */
  13.     private $dataCollector;
  14.     /**
  15.      * @param \EightPoints\Bundle\GuzzleBundle\Log\LoggerInterface $logger
  16.      * @param \EightPoints\Bundle\GuzzleBundle\DataCollector\HttpDataCollector $dataCollector
  17.      */
  18.     public function __construct(LoggerInterface $loggerHttpDataCollector $dataCollector)
  19.     {
  20.         $this->logger $logger;
  21.         $this->dataCollector $dataCollector;
  22.     }
  23.     /**
  24.      * @param callable $handler
  25.      *
  26.      * @return \Closure
  27.      */
  28.     public function __invoke(callable $handler) : \Closure
  29.     {
  30.         return function (RequestInterface $request, array $options) use ($handler) {
  31.             $options['on_stats'] = $this->getOnStatsCallback(
  32.                 isset($options['on_stats']) ? $options['on_stats'] : null,
  33.                 isset($options['request_id']) ? $options['request_id'] : null
  34.             );
  35.             // Continue the handler chain.
  36.             return $handler($request$options);
  37.         };
  38.     }
  39.     /**
  40.      * Create callback for on_stats options.
  41.      * If request has on_stats option, it will be called inside of this callback.
  42.      *
  43.      * @param null|callable $initialOnStats
  44.      * @param null|string $requestId
  45.      *
  46.      * @return \Closure
  47.      */
  48.     protected function getOnStatsCallback(?callable $initialOnStats, ?string $requestId) : \Closure
  49.     {
  50.         return function (TransferStats $stats) use ($initialOnStats$requestId) {
  51.             if (is_callable($initialOnStats)) {
  52.                 call_user_func($initialOnStats$stats);
  53.             }
  54.             $this->dataCollector->addTotalTime((float)$stats->getTransferTime());
  55.             if (($this->logger instanceof Logger) && $requestId) {
  56.                 $this->logger->addTransferTimeByRequestId($requestId, (float)$stats->getTransferTime());
  57.             }
  58.         };
  59.     }
  60. }