You are here

protected function Connection::expandArguments in Drupal 8

Same name and namespace in other branches
  1. 9 core/lib/Drupal/Core/Database/Connection.php \Drupal\Core\Database\Connection::expandArguments()

Expands out shorthand placeholders.

Drupal supports an alternate syntax for doing arrays of values. We therefore need to expand them out into a full, executable query string.

Parameters

string $query: The query string to modify.

array $args: The arguments for the query.

Return value

bool TRUE if the query was modified, FALSE otherwise.

Throws

\InvalidArgumentException This exception is thrown when:

  • A placeholder that ends in [] is supplied, and the supplied value is not an array.
  • A placeholder that does not end in [] is supplied, and the supplied value is an array.
1 call to Connection::expandArguments()
Connection::query in core/lib/Drupal/Core/Database/Connection.php
Executes a query string against the database.

File

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

Class

Connection
Base Database API class.

Namespace

Drupal\Core\Database

Code

protected function expandArguments(&$query, &$args) {
  $modified = FALSE;

  // If the placeholder indicated the value to use is an array,  we need to
  // expand it out into a comma-delimited set of placeholders.
  foreach ($args as $key => $data) {
    $is_bracket_placeholder = substr($key, -2) === '[]';
    $is_array_data = is_array($data);
    if ($is_bracket_placeholder && !$is_array_data) {
      throw new \InvalidArgumentException('Placeholders with a trailing [] can only be expanded with an array of values.');
    }
    elseif (!$is_bracket_placeholder) {
      if ($is_array_data) {
        throw new \InvalidArgumentException('Placeholders must have a trailing [] if they are to be expanded with an array of values.');
      }

      // Scalar placeholder - does not need to be expanded.
      continue;
    }

    // Handle expansion of arrays.
    $key_name = str_replace('[]', '__', $key);
    $new_keys = [];

    // We require placeholders to have trailing brackets if the developer
    // intends them to be expanded to an array to make the intent explicit.
    foreach (array_values($data) as $i => $value) {

      // This assumes that there are no other placeholders that use the same
      // name.  For example, if the array placeholder is defined as :example[]
      // and there is already an :example_2 placeholder, this will generate
      // a duplicate key.  We do not account for that as the calling code
      // is already broken if that happens.
      $new_keys[$key_name . $i] = $value;
    }

    // Update the query with the new placeholders.
    $query = str_replace($key, implode(', ', array_keys($new_keys)), $query);

    // Update the args array with the new placeholders.
    unset($args[$key]);
    $args += $new_keys;
    $modified = TRUE;
  }
  return $modified;
}