function Connection::findCallerFromDebugBacktrace

Same name in other branches
  1. 11.x core/lib/Drupal/Core/Database/Connection.php \Drupal\Core\Database\Connection::findCallerFromDebugBacktrace()

Determine the last non-database method that called the database API.

Traversing the call stack from the very first call made during the request, we define "the routine that called this query" as the last entry in the call stack that is not any method called from the namespace of the database driver, is not inside the Drupal\Core\Database namespace and does have a file (which excludes call_user_func_array(), anonymous functions and similar). That makes the climbing logic very simple, and handles the variable stack depth caused by the query builders.

See the debug_backtrace() function.

Return value

array This method returns a stack trace entry similar to that generated by debug_backtrace(). However, it flattens the trace entry and the trace entry before it so that we get the function and args of the function that called into the database system, not the function and args of the database call itself.

File

core/lib/Drupal/Core/Database/Connection.php, line 2176

Class

Connection
Base Database API class.

Namespace

Drupal\Core\Database

Code

public function findCallerFromDebugBacktrace() : array {
    $stack = $this->removeDatabaseEntriesFromDebugBacktrace($this->getDebugBacktrace(), $this->getConnectionOptions()['namespace']);
    // Return the first function call whose stack entry has a 'file' key, that
    // is, it is not a callback or a closure.
    for ($i = 0; $i < count($stack); $i++) {
        if (!empty($stack[$i]['file'])) {
            return [
                'file' => $stack[$i]['file'],
                'line' => $stack[$i]['line'],
                'function' => $stack[$i + 1]['function'],
                'class' => $stack[$i + 1]['class'] ?? NULL,
                'type' => $stack[$i + 1]['type'] ?? NULL,
                'args' => $stack[$i + 1]['args'] ?? [],
            ];
        }
    }
    return [];
}

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.