*/ class ResolveDefinitionTemplatesPass implements CompilerPassInterface { protected $container; public function process(ContainerBuilder $container) { $this->container = $container; foreach (array_keys($container->getDefinitions()) as $id) { // yes, we are specifically fetching the definition from the // container to ensure we are not operating on stale data $definition = $container->getDefinition($id); if (!$definition instanceof DefinitionDecorator) { continue; } $this->resolveDefinition($id, $definition); } } protected function resolveDefinition($id, DefinitionDecorator $definition) { if (!$this->container->hasDefinition($parent = $definition->getParent())) { throw new \RuntimeException(sprintf('The parent definition "%s" defined for definition "%s" does not exist.', $parent, $id)); } $parentDef = $this->container->getDefinition($parent); if ($parentDef instanceof DefinitionDecorator) { $parentDef = $this->resolveDefinition($parent, $parentDef); } $def = new Definition(); // merge in parent definition // purposely ignored attributes: scope, abstract, tags $def->setClass($parentDef->getClass()); $def->setArguments($parentDef->getArguments()); $def->setMethodCalls($parentDef->getMethodCalls()); $def->setFactoryService($parentDef->getFactoryService()); $def->setFactoryMethod($parentDef->getFactoryMethod()); $def->setConfigurator($parentDef->getConfigurator()); $def->setFile($parentDef->getFile()); $def->setPublic($parentDef->isPublic()); // overwrite with values specified in the decorator $changes = $definition->getChanges(); if (isset($changes['class'])) { $def->setClass($definition->getClass()); } if (isset($changes['factory_method'])) { $def->setFactoryMethod($definition->getFactoryMethod()); } if (isset($changes['factory_service'])) { $def->setFactoryService($definition->getFactoryService()); } if (isset($changes['configurator'])) { $def->setConfigurator($definition->getConfigurator()); } if (isset($changes['file'])) { $def->setFile($definition->getFile()); } if (isset($changes['public'])) { $def->setPublic($definition->isPublic()); } // merge arguments foreach ($definition->getArguments() as $k => $v) { if (is_numeric($k)) { $def->addArgument($v); continue; } if (0 !== strpos($k, 'index_')) { throw new \RuntimeException(sprintf('Invalid argument key "%s" found.', $k)); } $index = (integer) substr($k, strlen('index_')); $def->setArgument($index, $v); } // append method calls if (count($calls = $definition->getMethodCalls()) > 0) { $def->setMethodCalls(array_merge($def->getMethodCalls(), $calls)); } // these attributes are always taken from the child $def->setAbstract($definition->isAbstract()); $def->setScope($definition->getScope()); $def->setTags($definition->getTags()); // set new definition on container $this->container->setDefinition($id, $def); return $def; } }