Friday, December 07, 2007

Drupal debugging tips

Sometims drupal throw this kind of error:

warning: urldecode() expects parameter 1 to be string, array given in E:\Websites\www\gt\modules\path\path.module on line 142.

One way to debug this issue is insert the following code into where the error is thrown

if(is_array($text)){
printArray($text);
backtrace();
exit();
}

Thi tells you which element of the form cause the error, you can also print out what is the argument in the array by setting condition to the backtrace() function. Such as

If(count($array) == 22){

$args .= printArray($array);

}

I found this very convience and useful. Better more, Make use of the following function when debugging.

//back_trace
function backtrace()
{
$output = "
\n";
$output .= "Backtrace:
\n";
$backtrace = debug_backtrace();

foreach ($backtrace as $bt) {
$args = '';
foreach ($bt['args'] as $a) {
if (!empty($args)) {
$args .= ', ';
}
switch (gettype($a)) {
case 'integer':
case 'double':
$args .= $a;
break;
case 'string':
$a = htmlspecialchars(substr($a, 0, 64)).((strlen($a) > 64) ? '...' : '');
$args .= "\"$a\"";
break;
case 'array':
$args .= 'Array('.count($a).')';
break;
case 'object':
$args .= 'Object('.get_class($a).')';
break;
case 'resource':
$args .= 'Resource('.strstr($a, '#').')';
break;
case 'boolean':
$args .= $a ? 'True' : 'False';
break;
case 'NULL':
$args .= 'Null';
break;
default:
$args .= 'Unknown';
}
}
$output .= "
\n";
$output .= "file: {$bt['line']} - {$bt['file']}
\n";
$output .= "call: {$bt['class']}{$bt['type']}{$bt['function']}($args)
\n";
}
$output .= "
\n";
print $output;
}