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\Compiler;
14 use Symfony\Component\DependencyInjection\Argument\ServiceClosureArgument;
15 use Symfony\Component\DependencyInjection\ContainerBuilder;
16 use Symfony\Component\DependencyInjection\EnvVarProcessor;
17 use Symfony\Component\DependencyInjection\EnvVarProcessorInterface;
18 use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException;
19 use Symfony\Component\DependencyInjection\ParameterBag\EnvPlaceholderParameterBag;
20 use Symfony\Component\DependencyInjection\ServiceLocator;
21 use Symfony\Component\DependencyInjection\Reference;
24 * Creates the container.env_var_processors_locator service.
26 * @author Nicolas Grekas <p@tchwork.com>
28 class RegisterEnvVarProcessorsPass implements CompilerPassInterface
30 private static $allowedTypes = array('array', 'bool', 'float', 'int', 'string');
32 public function process(ContainerBuilder $container)
34 $bag = $container->getParameterBag();
36 $processors = array();
37 foreach ($container->findTaggedServiceIds('container.env_var_processor') as $id => $tags) {
38 if (!$r = $container->getReflectionClass($class = $container->getDefinition($id)->getClass())) {
39 throw new InvalidArgumentException(sprintf('Class "%s" used for service "%s" cannot be found.', $class, $id));
40 } elseif (!$r->isSubclassOf(EnvVarProcessorInterface::class)) {
41 throw new InvalidArgumentException(sprintf('Service "%s" must implement interface "%s".', $id, EnvVarProcessorInterface::class));
43 foreach ($class::getProvidedTypes() as $prefix => $type) {
44 $processors[$prefix] = new ServiceClosureArgument(new Reference($id));
45 $types[$prefix] = self::validateProvidedTypes($type, $class);
49 if ($bag instanceof EnvPlaceholderParameterBag) {
50 foreach (EnvVarProcessor::getProvidedTypes() as $prefix => $type) {
51 if (!isset($types[$prefix])) {
52 $types[$prefix] = self::validateProvidedTypes($type, EnvVarProcessor::class);
55 $bag->setProvidedTypes($types);
59 $container->register('container.env_var_processors_locator', ServiceLocator::class)
61 ->setArguments(array($processors))
66 private static function validateProvidedTypes($types, $class)
68 $types = explode('|', $types);
70 foreach ($types as $type) {
71 if (!in_array($type, self::$allowedTypes)) {
72 throw new InvalidArgumentException(sprintf('Invalid type "%s" returned by "%s::getProvidedTypes()", expected one of "%s".', $type, $class, implode('", "', self::$allowedTypes)));