Skip to content

Commit

Permalink
DI\Container: added expand()
Browse files Browse the repository at this point in the history
  • Loading branch information
dg committed May 10, 2011
1 parent 94e8b8d commit 05411c5
Show file tree
Hide file tree
Showing 2 changed files with 61 additions and 0 deletions.
24 changes: 24 additions & 0 deletions Nette/DI/Container.php
Expand Up @@ -263,6 +263,30 @@ public function getParam($key, $default = NULL)



/**
* Expands %placeholders% in string.
* @param string
* @return string
* @throws Nette\InvalidStateException
*/
public function expand($s)
{
if (is_string($s) && strpos($s, '%') !== FALSE) {
$that = $this;
return @preg_replace_callback('#%([a-z0-9._-]*)%#i', function ($m) use ($that) { // intentionally @ due PHP bug #39257
list(, $param) = $m;
$val = $param === '' ? '%' : $that->getParam($param);
if (!is_scalar($val)) {
throw new Nette\InvalidStateException("Parameter '$param' is not scalar.");
}
return $val;
}, $s);
}
return $s;
}



/********************* shortcuts ****************d*g**/


Expand Down
37 changes: 37 additions & 0 deletions tests/Nette/DI/Container.expand.phpt
@@ -0,0 +1,37 @@
<?php

/**
* Test: Nette\DI\Container expand.
*
* @author David Grudl
* @package Nette
* @subpackage UnitTests
*/

use Nette\DI\Container;



require __DIR__ . '/../bootstrap.php';



$container = new Container;
$container->params['appDir'] = '/myApp';

Assert::same( '/myApp/test', $container->expand('%appDir%/test') );

try {
$container->expand('%bar%');
Assert::fail('Expected exception');
} catch (Exception $e) {
Assert::exception('Nette\InvalidStateException', "Missing parameter 'bar'.", $e );
}

try {
$container->params['bar'] = array();
$container->expand('%bar%');
Assert::fail('Expected exception');
} catch (Exception $e) {
Assert::exception('Nette\InvalidStateException', "Parameter 'bar' is not scalar.", $e );
}

0 comments on commit 05411c5

Please sign in to comment.