Code: Select all
An error occured in {label}Code: Select all
An error occured in $this->labelCode: Select all
<?php
class A {
const TOKEN_OPEN = '{';
const TOKEN_CLOSE = '}';
public $label = '!yay!';
public $tooltip = '!yay!';
public $_numErrors = '!yay!';
public $_id = '!yay!';
/**
* Converts {variables} into the text they represent.
*
* No regular expressions because they are slow (and they are for n00bs) ;P
*
* @param string $msg
*/
public function _expandErrorVars($msg)
{
static $errorVars = array('{label}' => 'label', '{numErrors}' => '_numErrors',
'{tooltip}' => 'tooltip', '{id}' => '_id');
$replacements = array();
$token = true;
$posClose = null;
$posOpen = $i = strpos($msg, self::TOKEN_OPEN);
for ($q=0; $i !== false; $q++) {
if (!$token) {
if ($posClose) {
// open and close both found
$replacements[] = array($posOpen, $posClose);
}
// find another open
$i = $posOpen = strpos($msg, self::TOKEN_OPEN, $i);
} else {
if (@ctype_alpha($msg[$i+1])) {
// face valid, already open find a close
$i = $posClose = strpos($msg, self::TOKEN_CLOSE, $i);
} else {
// not face valid, force look for new open
$posClose = null;
$i++;
}
}
$token = !$token;
if ($q > 200000) {
throw new OF_Exception('Critical overflow', OF_Exception::MISC);
}
}
$expandedMsg = $msg;
foreach ($replacements as $r) {
list($start, $end) = $r;
$var = substr($msg, $start, $end - $start + 1);
if (isset($errorVars[$var])) {
$expandedMsg = str_replace($var, $this->{$errorVars[$var]}, $expandedMsg);
}
}
return $expandedMsg;
}
}
$a = new A();
$tests = array('These are the variables {label} {tooltip} {numErrors} {id}',
'This doesn\'t {exist}', '{{bob monkeys}', '{bob monkeys',
'{poordog {label}', '}{label}', '{label}',
'{ label}', '{Label}', '{{{{label}}}}',
'{ { { {* {a {label} }', '{label,}', '{label}{');
foreach ($tests as $testStr) {
echo $a->_expandErrorVars($testStr), "\n";
}Code: Select all
These are the variables !yay! !yay! !yay! !yay!
This doesn't {exist}
{{bob monkeys}
{bob monkeys
{poordog {label}
}!yay!
!yay!
{ label}
{Label}
{{{!yay!}}}
{ { { {* {a {label} }
{label,}
!yay!{