Skip to content

Instantly share code, notes, and snippets.

@pavelmaca
Created June 16, 2011 08:10
Show Gist options
  • Save pavelmaca/1028874 to your computer and use it in GitHub Desktop.
Save pavelmaca/1028874 to your computer and use it in GitHub Desktop.
<?php
/**
* Expands %placeholders% in string. Return mixed when expanding pure ^%item%$.
* @param string
* @return mixed
* @throws Nette\InvalidStateException
*/
public function expand($s)
{
if (is_string($s) && strpos($s, '%') !== FALSE) {
$pattern = '%([a-z0-9._-]*)%';
$single = FALSE;
$that = $this;
$replacer = function ($m) use ($that, $single) { // intentionally @ due PHP bug #39257
list(, $param) = $m;
if ($param === '') {
return '%';
} elseif (!is_scalar($val = Nette\Utils\Arrays::get((array) $that->params, explode('.', $param))) && $singel !== TRUE) {
throw new Nette\InvalidStateException("Parameter '$param' is not scalar.");
}
return $val;
};
if ($m = Nette\Utils\Strings::match($s, '#^$pattern$#i')) {
$single = TRUE;
return $replacer($m);
} else {
return @preg_replace_callback('#$pattern#i', $replacer, $s);
}
}
return $s;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment