4 * This file is part of the Symfony package.
6 * (c) Fabien Potencier <fabien@symfony.com>
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
12 namespace Symfony\Component\DependencyInjection\ParameterBag;
14 use Symfony\Component\DependencyInjection\Exception\RuntimeException;
15 use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException;
18 * @author Nicolas Grekas <p@tchwork.com>
20 class EnvPlaceholderParameterBag extends ParameterBag
22 private $envPlaceholders = array();
27 public function get($name)
29 if (0 === strpos($name, 'env(') && ')' === substr($name, -1) && 'env()' !== $name) {
30 $env = substr($name, 4, -1);
32 if (isset($this->envPlaceholders[$env])) {
33 foreach ($this->envPlaceholders[$env] as $placeholder) {
34 return $placeholder; // return first result
37 if (preg_match('/\W/', $env)) {
38 throw new InvalidArgumentException(sprintf('Invalid %s name: only "word" characters are allowed.', $name));
41 if ($this->has($name)) {
42 $defaultValue = parent::get($name);
44 if (null !== $defaultValue && !is_scalar($defaultValue)) {
45 throw new RuntimeException(sprintf('The default value of an env() parameter must be scalar or null, but "%s" given to "%s".', gettype($defaultValue), $name));
49 $uniqueName = md5($name.uniqid(mt_rand(), true));
50 $placeholder = sprintf('env_%s_%s', $env, $uniqueName);
51 $this->envPlaceholders[$env][$placeholder] = $placeholder;
56 return parent::get($name);
60 * Returns the map of env vars used in the resolved parameter values to their placeholders.
62 * @return string[][] A map of env var names to their placeholders
64 public function getEnvPlaceholders()
66 return $this->envPlaceholders;
70 * Merges the env placeholders of another EnvPlaceholderParameterBag.
72 public function mergeEnvPlaceholders(self $bag)
74 if ($newPlaceholders = $bag->getEnvPlaceholders()) {
75 $this->envPlaceholders += $newPlaceholders;
77 foreach ($newPlaceholders as $env => $placeholders) {
78 $this->envPlaceholders[$env] += $placeholders;
86 public function resolve()
88 if ($this->resolved) {
93 foreach ($this->envPlaceholders as $env => $placeholders) {
94 if (!isset($this->parameters[$name = strtolower("env($env)")])) {
97 if (is_numeric($default = $this->parameters[$name])) {
98 $this->parameters[$name] = (string) $default;
99 } elseif (null !== $default && !is_scalar($default)) {
100 throw new RuntimeException(sprintf('The default value of env parameter "%s" must be scalar or null, %s given.', $env, gettype($default)));