Last updated July 9, 2010. Created by solotandem on February 12, 2010.
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.

<?php
// 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']) {
    continue;
  }
 
// Process function call.
 
$name = &$item->name;
  switch (
$name['value']) {
    case
'old_function_name':
     
$name['value'] = 'new_function_name';
      break;
  }
}
?>

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:

<?php
 
// 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:

<?php
 
// 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:

<?php
 
// 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:

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

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