Does That Bug Match a Pattern?

If you find an error in your codebase, consider if the cause can be matched with a regular expression.

For example, consider a function that takes a variable as a reference, but is called with another function directly in it.

print drupal_render(drupal_get_form('awesome_form'));

drupal_render is defined as `drupal_render(&$elements){}`, which will throw PHP Strict errors since a variable needs to be passed.

There is a pattern that can be defined to find other instances of this issue, before it is found by a client or end user and reported.

I use The Silver Searcher to search by codebase. It's fast and prints the output to the terminal nicely. The command is `ag`.

You could create a pattern that looks for "render(" and where the next character is not a dollar sign.

ag 'render\(\s*[^$]'

Or, maybe a match for "render(" with alphanumeric characters and underlines before another "("

ag 'render\([A-z0-9_]*\('

This is actually an example of a bug that came in today. I was able to find 2 more offending calls to drupal_render() without them being reported.

Pro-actively identifying patterns like this is an easy win for everyone.

Here's one more I have in the toolkit.

When a function is defined with a reference variable (see render above), it can be easy for a developer to just copy the function declaration with all the arguments, then forget to remove the '&' before the variable name.

$elements = drupal_get_form('awesome_form');
drupal_render(&$elements); // Oops, I left the '&' in there!

This will cause an error.

The following matches lines with an opening parenthesis, which also contain a '&' after the opening, but excludes lines that start with function, foreach, and array.

ag -i '^(?!.*(function|foreach|array|\*|\/\/)).*\(.*&\$'