function showAssertError($file, $line, $assertion_string, $description = null) { global $errors_total; $errors_total++; // HTML блок значений каждой переменной из $assertion_string. // ========================================================== $variables_html = ''; $var_names = getVarNames($assertion_string); if (!empty($var_names)) { foreach ($var_names as $name) { $clean_name = str_replace('$', '', $name); global ${$clean_name}; if (isset(${$clean_name})) { $value = ${$clean_name}; } else { $value = 'not set (or unknown value)'; } if (empty($value)) { if (is_null($value)) { $value = 'null'; } else { $value = 'empty'; } } $variables_html .= "<p><b>{$name}</b> is <b>{$value}</b></p>"; } } // HTML блок описания. // =================== if (!empty($description)) { $description_html = "<p><i>{$description}</i></p>"; } else { $description_html = ''; } // HTML блок строки утверждения. // ============================= if (!empty($assertion_string)) { $assertion_html = "<p>Incorrect assertion: <b>{$assertion_string}</b></p>"; } else { $assertion_html = ''; } $html = "\n\t\t<hr>\n\t\t<p>{$file}:{$line}</p>\n\t\t{$description_html}\n\t\t{$assertion_html}\n\t\t{$variables_html}\n\t\t<hr>\n\t\t"; echo $html; }
<?php require_once 'string_utils.php'; $mix = '$var $var2, var $var1 var1 $1var 1var $var[0] foo($var) $var(foo) $v1ar v1ar'; $names = getVarNames($mix); assert(sizeof($names) == 7); assert($names[3] == '$var'); assert($names[6] == '$v1ar'); $comparation = '$var1 == $var2 $var1 <= $var2, $var1===$var2 $var1= $var2;'; $names = getVarNames($comparation); assert(sizeof($names) == 8); assert($names[3] == '$var2'); assert($names[7] == '$var2'); $comparation = '($var1 + $var2) == $var++;'; $names = getVarNames($comparation); assert(sizeof($names) == 3); assert($names[0] == '$var1'); assert($names[2] == '$var'); $incorrect = '$var > var2'; $names = getVarNames($incorrect); assert(sizeof($names) == 1);
<?php function getVarNames($string) { $var_name_pattern = "@[\$]{1}[A-Za-z]{1}[A-Za-z0-9_]*\\b@"; $names; $is_finded = preg_match_all($var_name_pattern, $string, $names); if ($is_finded && !empty($names)) { return $names[0]; } else { return null; } } $mix = '$var $var2, var $var1 var1 $1var 1var $var[0] foo($var) $var(foo) $v1ar v1ar'; $comparation = '$var1 == $var2 $var1 <= $var2, $var1===$var2 $var1= $var2;'; $names = getVarNames($comparation); print_r($names);
protected function expandAssertion($assertion) { if (!empty($assertion)) { $names = getVarNames($assertion); $left_operand = $names[0]; // $var1 $right_operand = $names[1]; // $var2 $left_operand = str_replace('$', '', $left_operand); // var1 $right_operand = str_replace('$', '', $right_operand); // var2 // вернуть массив. $this->assert_string = $assertion; // 3.3 $this->left_operand_value = ${$left_operand}; $this->right_operand_value = ${$right_operand}; } }