Last updated 9 July 2010. Created on 12 February 2010.
Edited by solotandem. Log in to edit this page.

Example 1: Rename a function

A common change from one Drupal version to the next is the renaming of functions (often accompanied by a change in their parameters). This is very easy to do. The Grammar Parser getFunctionCalls() routine returns a list of function calls. We can loop on this list until we find the function we want to rename.

// Get the array of nodes holding function call objects.
$nodes = $reader->getFunctionCalls();
foreach ($nodes as &$node) {
  // Get the function call object.
  $item = &$node->data;
  // Make sure this function call has a simple string for its name.
  if (!is_array($item->name) || !isset($item->name['value']) {
  // Process function call.
  $name = &$item->name;
  switch ($name['value']) {
    case 'old_function_name':
      $name['value'] = 'new_function_name';

Example 2: Reorder the parameters to a function call

Building on the previous example, let's assume the first two parameters to 'old_function_name' have been flipped. If $item is the function call object, we can switch the parameters as follows:

  // Save the current parameters to local variables.
  $p0 = $item->getParameter(0);
  $p1 = $item->getParameter(1);

  // Swap the parameters.
  $item->setParameter(0, $p1);
  $item->setParameter(1, $p0);

Example 3: Set the parameters to a function call

As part of the refactoring of our module's API, the 'old_function_name' routine now has '$form' and '$form_state' as parameters (where previously it may have had none). We can set these parameters with a single line of code:

  // Set all of the parameters from an array of code strings.
  $editor->setParameters($item, array('$form', '$form_state'));

Example 4: Replace a parameter to a function call

To replace a parameter, we can write:

  // Set a single parameter from a string of code.
  $editor->setParameter($item, 0, $code);

Example 5: Insert a parameter to a function call

To insert a third parameter (where two or more may have previously existed), we can write:

  // Insert a parameter from a string of code.
  $editor->insertParameter($item, 2, '$langcode = \'en\'');

Looking for support? Visit the forums, or join #drupal-support in IRC.