You are here

abstract class DebugMessageFormatterPluginBase in Apigee Edge 8

Defines a base class for debug message formatter plugins.

Hierarchy

Expanded class hierarchy of DebugMessageFormatterPluginBase

File

modules/apigee_edge_debug/src/Plugin/DebugMessageFormatter/DebugMessageFormatterPluginBase.php, line 36

Namespace

Drupal\apigee_edge_debug\Plugin\DebugMessageFormatter
View source
abstract class DebugMessageFormatterPluginBase extends PluginBase implements ContainerFactoryPluginInterface, DebugMessageFormatterPluginInterface {

  /**
   * Whether to mask the organization in the request URI or not.
   *
   * @var bool
   */
  protected $maskOrganization;

  /**
   * Whether to remove the authorization header from the request or not.
   *
   * @var bool
   */
  protected $removeCredentials;

  /**
   * DebugMessageFormatterPluginBase constructor.
   *
   * @param \Drupal\Core\Config\ConfigFactoryInterface $config
   *   The config factory.
   * @param array $configuration
   *   Plugin configuration.
   * @param string $plugin_id
   *   The plugin id.
   * @param mixed $plugin_definition
   *   The plugin definition.
   */
  public function __construct(ConfigFactoryInterface $config, array $configuration, string $plugin_id, $plugin_definition) {
    parent::__construct($configuration, $plugin_id, $plugin_definition);
    $this->maskOrganization = $config
      ->get('apigee_edge_debug.settings')
      ->get('mask_organization');
    $this->removeCredentials = $config
      ->get('apigee_edge_debug.settings')
      ->get('remove_credentials');
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static($container
      ->get('config.factory'), $configuration, $plugin_id, $plugin_definition);
  }

  /**
   * {@inheritdoc}
   */
  public function getId() : string {
    return $this->pluginDefinition['id'];
  }

  /**
   * {@inheritdoc}
   */
  public function getLabel() : string {
    return $this->pluginDefinition['label'];
  }

  /**
   * {@inheritdoc}
   */
  public function formatRequest(RequestInterface $request) : string {

    // Do not modify the original request object.
    if ($this->removeCredentials) {
      $request = $request
        ->withoutHeader('Authorization');
      if ($request
        ->getMethod() === 'POST' && $request
        ->getUri()
        ->getPath() === '/oauth/token') {
        $body = (string) $request
          ->getBody();
        $body = preg_replace('/(.*refresh_token=)([^\\&]+)(.*)/', '$1***refresh-token***$3', $body);
        $body = preg_replace('/(.*mfa_token=)([^\\&]+)(.*)/', '$1***mfa-token***$3', $body);
        $body = preg_replace('/(.*username=)([^\\&]+)(.*)/', '$1***username***$3', $body);
        $body = preg_replace('/(.*password=)([^\\&]+)(.*)/', '$1***password***$3', $body);
        $request = $request
          ->withBody(Psr7\stream_for($body));
      }
    }
    if ($this->maskOrganization) {
      $pattern = '/(\\/v\\d+\\/(?:mint\\/)?(?:o|organizations))(?:\\/)([^\\/]+)(?:\\/?)(.*)/';
      $path = rtrim(preg_replace($pattern, '$1/***organization***/$3', $request
        ->getUri()
        ->getPath()), '/');
      $request = $request
        ->withUri($request
        ->getUri()
        ->withPath($path));
    }
    return $this
      ->getFormatter()
      ->formatRequest($request);
  }

  /**
   * Returns the wrapped message formatter.
   *
   * @return \Http\Message\Formatter
   *   Message formatter.
   */
  protected abstract function getFormatter() : Formatter;

  /**
   * {@inheritdoc}
   */
  public function formatResponse(ResponseInterface $response, RequestInterface $request) : string {
    if ($this->removeCredentials) {
      $request = $request
        ->withoutHeader('Authorization');
      $masks = [
        'consumerKey' => '***consumer-key***',
        'consumerSecret' => '***consumer-secret***',
      ];
      $json = json_decode((string) $response
        ->getBody(), TRUE);
      if (json_last_error() === JSON_ERROR_NONE) {
        array_walk_recursive($json, function (&$value, $key) use ($masks) {
          if (isset($masks[$key])) {
            $value = $masks[$key];
          }
        });
        $response = $response
          ->withBody(Psr7\stream_for(json_encode((object) $json, JSON_PRETTY_PRINT)));
      }
      if ($request
        ->getMethod() === 'POST' && $request
        ->getUri()
        ->getPath() === '/oauth/token') {
        $json = json_decode((string) $response
          ->getBody(), TRUE);
        if (json_last_error() === JSON_ERROR_NONE) {
          if (isset($json['access_token'])) {
            $json['access_token'] = '***access-token***';
          }
          if (isset($json['refresh_token'])) {
            $json['refresh_token'] = '***refresh-token***';
          }
          $response = $response
            ->withBody(Psr7\stream_for(json_encode((object) $json)));
        }
      }
    }
    return $this
      ->getFormatter()
      ->formatResponse($response);
  }

  /**
   * {@inheritdoc}
   */
  public function formatStats(TransferStats $stats) : string {
    return var_export($this
      ->getTimeStatsInSeconds($stats), TRUE);
  }

  /**
   * Utility function that collects and formats times from transfer statistic.
   *
   * @param \GuzzleHttp\TransferStats $stats
   *   Transfer statistic.
   * @param int $precision
   *   Precision of rounding applied on times.
   *
   * @return array
   *   Array of measured times.
   */
  protected function getTimeStatsInSeconds(TransferStats $stats, int $precision = 3) : array {
    $time_stats = array_filter($stats
      ->getHandlerStats(), function ($key) {
      return preg_match('/_time$/', $key);
    }, ARRAY_FILTER_USE_KEY);
    return array_map(function ($stat) use ($precision) {
      return round($stat, $precision) . 's';
    }, $time_stats);
  }

}

Members

Namesort descending Modifiers Type Description Overrides
DebugMessageFormatterPluginBase::$maskOrganization protected property Whether to mask the organization in the request URI or not.
DebugMessageFormatterPluginBase::$removeCredentials protected property Whether to remove the authorization header from the request or not.
DebugMessageFormatterPluginBase::create public static function Creates an instance of the plugin. Overrides ContainerFactoryPluginInterface::create
DebugMessageFormatterPluginBase::formatRequest public function Formats a request. Overrides DebugMessageFormatterPluginInterface::formatRequest
DebugMessageFormatterPluginBase::formatResponse public function Formats a response. Overrides DebugMessageFormatterPluginInterface::formatResponse 1
DebugMessageFormatterPluginBase::formatStats public function Formats stats object. Overrides DebugMessageFormatterPluginInterface::formatStats 2
DebugMessageFormatterPluginBase::getFormatter abstract protected function Returns the wrapped message formatter. 3
DebugMessageFormatterPluginBase::getId public function Returns the ID of the debug message formatter plugin. Overrides DebugMessageFormatterPluginInterface::getId
DebugMessageFormatterPluginBase::getLabel public function Returns the label of the debug message formatter plugin. Overrides DebugMessageFormatterPluginInterface::getLabel
DebugMessageFormatterPluginBase::getTimeStatsInSeconds protected function Utility function that collects and formats times from transfer statistic.
DebugMessageFormatterPluginBase::__construct public function DebugMessageFormatterPluginBase constructor. Overrides PluginBase::__construct
DependencySerializationTrait::$_entityStorages protected property An array of entity type IDs keyed by the property name of their storages.
DependencySerializationTrait::$_serviceIds protected property An array of service IDs keyed by property name used for serialization.
DependencySerializationTrait::__sleep public function 1
DependencySerializationTrait::__wakeup public function 2
MessengerTrait::$messenger protected property The messenger. 29
MessengerTrait::messenger public function Gets the messenger. 29
MessengerTrait::setMessenger public function Sets the messenger.
PluginBase::$configuration protected property Configuration information passed into the plugin. 1
PluginBase::$pluginDefinition protected property The plugin implementation definition. 1
PluginBase::$pluginId protected property The plugin_id.
PluginBase::DERIVATIVE_SEPARATOR constant A string which is used to separate base plugin IDs from the derivative ID.
PluginBase::getBaseId public function Gets the base_plugin_id of the plugin instance. Overrides DerivativeInspectionInterface::getBaseId
PluginBase::getDerivativeId public function Gets the derivative_id of the plugin instance. Overrides DerivativeInspectionInterface::getDerivativeId
PluginBase::getPluginDefinition public function Gets the definition of the plugin implementation. Overrides PluginInspectionInterface::getPluginDefinition 3
PluginBase::getPluginId public function Gets the plugin_id of the plugin instance. Overrides PluginInspectionInterface::getPluginId
PluginBase::isConfigurable public function Determines if the plugin is configurable.
StringTranslationTrait::$stringTranslation protected property The string translation service. 1
StringTranslationTrait::formatPlural protected function Formats a string containing a count of items.
StringTranslationTrait::getNumberOfPlurals protected function Returns the number of plurals supported by a given language.
StringTranslationTrait::getStringTranslation protected function Gets the string translation service.
StringTranslationTrait::setStringTranslation public function Sets the string translation service to use. 2
StringTranslationTrait::t protected function Translates a string to the current language or to a given language.