You are here

trait LoggedStatementsTrait in Drupal 9

Same name and namespace in other branches
  1. 8 core/modules/system/tests/modules/database_statement_monitoring_test/src/LoggedStatementsTrait.php \Drupal\database_statement_monitoring_test\LoggedStatementsTrait

Trait for Connection classes that can store logged statements.

Hierarchy

3 files declare their use of LoggedStatementsTrait
Connection.php in core/modules/system/tests/modules/database_statement_monitoring_test/src/sqlite/Connection.php
Connection.php in core/modules/system/tests/modules/database_statement_monitoring_test/src/pgsql/Connection.php
Connection.php in core/modules/system/tests/modules/database_statement_monitoring_test/src/mysql/Connection.php

File

core/modules/system/tests/modules/database_statement_monitoring_test/src/LoggedStatementsTrait.php, line 8

Namespace

Drupal\database_statement_monitoring_test
View source
trait LoggedStatementsTrait {

  /**
   * Logged statements.
   *
   * @var string[]
   */
  protected $loggedStatements;

  /**
   * {@inheritdoc}
   */
  public function query($query, array $args = [], $options = []) {

    // Log the query if it is a string, can receive statement objects e.g
    // in the pgsql driver. These are hard to log as the table name has already
    // been replaced.
    if (is_string($query)) {
      $stringified_args = array_map(function ($v) {
        return is_array($v) ? implode(',', $v) : $v;
      }, $args);
      $this->loggedStatements[] = str_replace(array_keys($stringified_args), array_values($stringified_args), $query);
    }
    return parent::query($query, $args, $options);
  }

  /**
   * Resets logged statements.
   *
   * @return $this
   */
  public function resetLoggedStatements() {
    $this->loggedStatements = [];
    return $this;
  }

  /**
   * {@inheritdoc}
   */
  public function getDriverClass($class) {
    static $fixed_namespace;
    if (!$fixed_namespace) {

      // Override because we've altered the namespace in
      // \Drupal\KernelTests\Core\Cache\EndOfTransactionQueriesTest::getDatabaseConnectionInfo()
      // to use the logging Connection classes. Set to a proper database driver
      // namespace.
      $this->connectionOptions['namespace'] = (new \ReflectionClass(get_parent_class($this)))
        ->getNamespaceName();
      $fixed_namespace = TRUE;
    }
    return parent::getDriverClass($class);
  }

  /**
   * Returns the executed queries.
   *
   * @return string[]
   */
  public function getLoggedStatements() {
    return $this->loggedStatements;
  }

}

Members

Namesort descending Modifiers Type Description Overrides
LoggedStatementsTrait::$loggedStatements protected property Logged statements.
LoggedStatementsTrait::getDriverClass public function
LoggedStatementsTrait::getLoggedStatements public function Returns the executed queries.
LoggedStatementsTrait::query public function
LoggedStatementsTrait::resetLoggedStatements public function Resets logged statements.