You are here

public function DebuggerMiddleware::__invoke in Acquia Purge 8

File

src/Http/DebuggerMiddleware.php, line 18

Class

DebuggerMiddleware
HTTP middleware which logs requests and responses for debugging purposes.

Namespace

Drupal\acquia_purge\Http

Code

public function __invoke() {
  return function (callable $handler) {
    return function ($req, array $options) use ($handler) {

      // Don't interfere on requests not made by the acquia_purge module, or
      // set the debgger object (::setDebugger will do input type validation).
      if (!isset($options['acquia_purge_debugger'])) {
        return $handler($req, $options);
      }
      else {
        $this
          ->setDebugger($options['acquia_purge_debugger'], FALSE);
      }

      // Render a visual separation between middleware invocations.
      $this
        ->debugger()
        ->writeSeparator('█');

      // Guzzle Request Options.
      $info = [];
      foreach ($options as $key => $value) {
        if (is_scalar($value)) {
          $info[$key] = $value;
        }
      }
      $this
        ->debugger()
        ->writeTable($info, 'Guzzle Request Options');

      // Cache Tags Mapping.
      if (isset($options['acquia_purge_tags'])) {
        $this
          ->debugger()
          ->writeTable($options['acquia_purge_tags']
          ->getTagsMap(), 'Cache Tags Mapping');
      }

      // Request table.
      $info = $this
        ->debugger()
        ->extractRequestInfo($req);
      $this
        ->debugger()
        ->writeTable($info);

      // Return a handler which writes out a response table.
      return $handler($req, $options)
        ->then(function (ResponseInterface $rsp) {
        $info = $this
          ->debugger()
          ->extractResponseInfo($rsp);
        $this
          ->debugger()
          ->writeTable($info);
        return $rsp;
      });
    };
  };
}