protected function Connection::expandArguments

protected Connection::expandArguments(&$query, &$args)

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.

File

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

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 = array();
    // 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;
}

© 2001–2016 by the original authors
Licensed under the GNU General Public License, version 2 and later.
Drupal is a registered trademark of Dries Buytaert.
https://api.drupal.org/api/drupal/core!lib!Drupal!Core!Database!Connection.php/function/Connection::expandArguments/8.1.x