Created
June 21, 2011 11:37
-
-
Save pavelmaca/1037673 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Returns array item or $default if item is not set. | |
* Example: $val = Arrays::get($arr, 'i', 123); | |
* @param mixed array | |
* @param mixed key | |
* @param mixed default value | |
* @return mixed | |
*/ | |
public static function get(array $arr, $key, $default = NULL) | |
{ | |
foreach (is_array($key) ? $key : array($key) as $k) { | |
if (is_array($arr) && array_key_exists($k, $arr)) { | |
$arr = $arr[$k]; | |
} elseif($arr instanceof Nette\ArrayHash && $arr->offsetExists($k)){ | |
$arr = $arr[$k]; | |
} else { | |
if (func_num_args() < 3) { | |
throw new Nette\InvalidArgumentException("Missing item '$k'."); | |
} | |
return $default; | |
} | |
} | |
return $arr; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Expands %placeholders% in string. | |
* @param string | |
* @return string|ArrayHash | |
* @throws Nette\InvalidStateException | |
*/ | |
public function expand($s) | |
{ | |
if (is_string($s) && strpos($s, '%') !== FALSE) { | |
$that = $this; | |
$replacer = function ($m, $single = FALSE) use ($that) { // intentionally @ due PHP bug #39257 | |
list(, $param) = $m; | |
if ($param === '') { | |
return '%'; | |
} elseif (!is_scalar($val = Nette\Utils\Arrays::get((array) $that->params, explode('.', $param))) && $single !== TRUE) { | |
throw new Nette\InvalidStateException("Parameter '$param' is not scalar."); | |
} | |
return $val; | |
}; | |
if ($m = Nette\Utils\Strings::match($s, '#^%([a-z0-9._-]*)%$#i')) { | |
return $replacer($m, TRUE); | |
} else { | |
return @preg_replace_callback('#%([a-z0-9._-]*)%#i', $replacer, $s); | |
} | |
} | |
return $s; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment