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\InvalidArgumentException;
15 use Symfony\Component\DependencyInjection\Exception\RuntimeException;
18 * @author Nicolas Grekas <p@tchwork.com>
20 class EnvPlaceholderParameterBag extends ParameterBag
22 private $envPlaceholders = array();
23 private $providedTypes = array();
28 public function get($name)
30 if (0 === strpos($name, 'env(') && ')' === substr($name, -1) && 'env()' !== $name) {
31 $env = substr($name, 4, -1);
33 if (isset($this->envPlaceholders[$env])) {
34 foreach ($this->envPlaceholders[$env] as $placeholder) {
35 return $placeholder; // return first result
38 if (!preg_match('/^(?:\w++:)*+\w++$/', $env)) {
39 throw new InvalidArgumentException(sprintf('Invalid %s name: only "word" characters are allowed.', $name));
42 if ($this->has($name)) {
43 $defaultValue = parent::get($name);
45 if (null !== $defaultValue && !is_scalar($defaultValue)) {
46 throw new RuntimeException(sprintf('The default value of an env() parameter must be scalar or null, but "%s" given to "%s".', \gettype($defaultValue), $name));
50 $uniqueName = md5($name.uniqid(mt_rand(), true));
51 $placeholder = sprintf('env_%s_%s', str_replace(':', '_', $env), $uniqueName);
52 $this->envPlaceholders[$env][$placeholder] = $placeholder;
57 return parent::get($name);
61 * Returns the map of env vars used in the resolved parameter values to their placeholders.
63 * @return string[][] A map of env var names to their placeholders
65 public function getEnvPlaceholders()
67 return $this->envPlaceholders;
71 * Merges the env placeholders of another EnvPlaceholderParameterBag.
73 public function mergeEnvPlaceholders(self $bag)
75 if ($newPlaceholders = $bag->getEnvPlaceholders()) {
76 $this->envPlaceholders += $newPlaceholders;
78 foreach ($newPlaceholders as $env => $placeholders) {
79 $this->envPlaceholders[$env] += $placeholders;
85 * Maps env prefixes to their corresponding PHP types.
87 public function setProvidedTypes(array $providedTypes)
89 $this->providedTypes = $providedTypes;
93 * Gets the PHP types corresponding to env() parameter prefixes.
97 public function getProvidedTypes()
99 return $this->providedTypes;
105 public function resolve()
107 if ($this->resolved) {
112 foreach ($this->envPlaceholders as $env => $placeholders) {
113 if (!$this->has($name = "env($env)")) {
116 if (is_numeric($default = $this->parameters[$name])) {
117 $this->parameters[$name] = (string) $default;
118 } elseif (null !== $default && !is_scalar($default)) {
119 throw new RuntimeException(sprintf('The default value of env parameter "%s" must be scalar or null, %s given.', $env, \gettype($default)));