You are here

public function DevelKintApiClientProfiler::__invoke in Apigee Edge 8

File

modules/apigee_edge_debug/src/HttpClientMiddleware/DevelKintApiClientProfiler.php, line 98

Class

DevelKintApiClientProfiler
Http client middleware that profiles Apigee Edge API calls.

Namespace

Drupal\apigee_edge_debug\HttpClientMiddleware

Code

public function __invoke() {
  return function ($handler) {
    return function (RequestInterface $request, array $options) use ($handler) {

      // If devel kint module is enabled and the user has devel kint permission.
      if ($this->moduleHandler
        ->moduleExists('kint') && $this->currentUser
        ->hasPermission('access kint')) {

        // If the formatter has been initialized yet then do nothing.
        if (!$this->formatter) {
          return $handler($request, $options);
        }
        $formatter = $this->formatter;
        $rest_call = [];
        if (isset($options[RequestOptions::ON_STATS])) {
          $next = $options[RequestOptions::ON_STATS];
        }
        else {
          $next = function (TransferStats $stats) {
          };
        }
        $options[RequestOptions::ON_STATS] = function (TransferStats $stats) use ($request, $next, $formatter) {
          $this->messenger
            ->addStatus(t('<h3>Edge Calls</h3>'));
          $level = LogLevel::DEBUG;

          // Do not modify the original request object in the subsequent calls.
          $request_clone = clone $request;
          $rest_call['Request'] = $formatter
            ->formatRequest($request_clone);
          if ($stats
            ->hasResponse()) {

            // Do not modify the original response object in the subsequent calls.
            $response_clone = clone $stats
              ->getResponse();
            $rest_call['Response'] = $formatter
              ->formatResponse($response_clone, $request_clone);
            if ($stats
              ->getResponse()
              ->getStatusCode() >= 400) {
              $level = LogLevel::WARNING;
            }
          }
          else {
            $level = LogLevel::ERROR;
            $error = $stats
              ->getHandlerErrorData();
            if (is_object($error)) {
              if (method_exists($error, '__toString')) {
                $error = (string) $error;
              }
              else {
                $error = json_encode($error);
              }
            }
            $rest_call['Error'] = $error;
          }
          $next($stats);
          $rest_call['Time Elapsed'] = $formatter
            ->formatStats($stats);
          $rest_call['Severity'] = isset($level) ? $level : '';
          ksm($rest_call);
        };
      }
      return $handler($request, $options);
    };
  };
}