y path for which to check the existence * @param bool|string $trackContents Whether to track contents of the given resource. If a string is passed, * it will be used as pattern for tracking contents of the requested directory * * @return bool * * @final */ public function fileExists($path, $trackContents = true) { $exists = file_exists($path); if (!$this->trackResources || $this->inVendors($path)) { return $exists; } if (!$exists) { $this->addResource(new FileExistenceResource($path)); return $exists; } if (is_dir($path)) { if ($trackContents) { $this->addResource(new DirectoryResource($path, \is_string($trackContents) ? $trackContents : null)); } else { $this->addResource(new GlobResource($path, '/*', false)); } } elseif ($trackContents) { $this->addResource(new FileResource($path)); } return $exists; } /** * Loads the configuration for an extension. * * @param string $extension The extension alias or namespace * @param array $values An array of values that customizes the extension * * @return $this * * @throws BadMethodCallException When this ContainerBuilder is compiled * @throws \LogicException if the extension is not registered */ public function loadFromExtension($extension, array $values = null) { if ($this->isCompiled()) { throw new BadMethodCallException('Cannot load from an extension on a compiled container.'); } if (\func_num_args() < 2) { $values = []; } $namespace = $this->getExtension($extension)->getAlias(); $this->extensionConfigs[$namespace][] = $values; return $this; } /** * Adds a compiler pass. * * @param CompilerPassInterface $pass A compiler pass * @param string $type The type of compiler pass * @param int $priority Used to sort the passes * * @return $this */ public function addCompilerPass(CompilerPassInterface $pass, $type = PassConfig::TYPE_BEFORE_OPTIMIZATION/*, int $priority = 0*/) { if (\func_num_args() >= 3) { $priority = func_get_arg(2); } else { if (__CLASS__ !== static::class) { $r = new \ReflectionMethod($this, __FUNCTION__); if (__CLASS__ !== $r->getDeclaringClass()->getName()) { @trigger_error(sprintf('Method %s() will have a third `int $priority = 0` argument in version 4.0. Not defining it is deprecated since Symfony 3.2.', __METHOD__), \E_USER_DEPRECATED); } } $priority = 0; } $this->getCompiler()->addPass($pass, $type, $priority); $this->addObjectResource($pass); return $this; } /** * Returns the compiler pass config which can then be modified. * * @return PassConfig The compiler pass config */ public function getCompilerPassConfig() { return $this->getCompiler()->getPassConfig(); } /** * Returns the compiler. * * @return Compiler The compiler */ public function getCompiler() { if (null === $this->compiler) { $this->compiler = new Compiler(); } return $this->compiler; } /** * Sets a service. * * @param string $id The service identifier * @param object|null $service The service instance * * @throws BadMethodCallException When this ContainerBuilder is compiled */ public function set($id, $service) { $id = $this->normalizeId($id); if ($this->isCompiled() && (isset($this->definitions[$id]) && !$this->definitions[$id]->isSynthetic())) { // setting a synthetic service on a compiled container is alright throw new BadMethodCallException(sprintf('Setting service "%s" for an unknown or non-synthetic service definition on a compiled container is not allowed.', $id)); } unset($this->definitions[$id], $this->aliasDefinitions[$id], $this->removedIds[$id]); parent::set($id, $service); } /** * Removes a service definition. * * @param string $id The service identifier */ public function removeDefinition($id) { if (isset($this->definitions[$id = $this->normalizeId($id)])) { unset($this->definitions[$id]); $this->removedIds[$id] = true; } } /** * Returns true if the given service is defined. * * @param string $id The service identifier * * @return bool true if the service is defined, false otherwise */ public function has($id) { $id = $this->normalizeId($id); return isset($this->definitions[$id]) || isset($this->aliasDefinitions[$id]) || parent::has($id); } /** * Gets a service. * * @param string $id The service identifier * @param int $invalidBehavior The behavior when the service does not exist * * @return object|null The associated service * * @throws InvalidArgumentException when no definitions are available * @throws ServiceCircularReferenceException When a circular reference is detected * @throws ServiceNotFoundException When the service is not defined * @throws \Exception * * @see Reference */ public function get($id, $invalidBehavior = ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE) { if ($this->isCompiled() && isset($this->removedIds[$id = $this->normalizeId($id)])) { @trigger_error(sprintf('Fetching the "%s" private service or alias is deprecated since Symfony 3.4 and will fail in 4.0. Make it public instead.', $id), \E_USER_DEPRECATED); } return $this->doGet($id, $invalidBehavior); } private function doGet($id, $invalidBehavior = ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE, array &$inlineServices = null, $isConstructorArgument = false) { $id = $this->normalizeId($id); if (isset($inlineServices[$id])) { return $inlineServices[$id]; } if (null === $inlineServices) { $isConstructorArgument = true; $inlineServices = []; } try { if (ContainerInterface::IGNORE_ON_UNINITIALIZED_REFERENCE === $invalidBehavior) { return parent::get($id, $invalidBehavior); } if ($service = parent::get($id, ContainerInterface::NULL_ON_INVALID_REFERENCE)) { return $service; } } catch (ServiceCircularReferenceException $e) { if ($isConstructorArgument) { throw $e; } } if (!isset($this->definitions[$id]) && isset($this->aliasDefinitions[$id])) { return $this->doGet((string) $this->aliasDefinitions[$id], $invalidBehavior, $inlineServices, $isConstructorArgument); } try { $definition = $this->getDefinition($id); } catch (ServiceNotFoundException $e) { if (ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE !== $invalidBehavior) { return null; } throw $e; } if ($isConstructorArgument) { $this->loading[$id] = true; } try { return $this->createService($definition, $inlineServices, $isConstructorArgument, $id); } finally { if ($isConstructorArgument) { unset($this->loading[$id]); } } } /** * Merges a ContainerBuilder with the current ContainerBuilder configuration. * * Service definitions overrides the current defined ones. * * But for parameters, they are overridden by the current ones. It allows * the parameters passed to the container constructor to have precedence * over the loaded ones. * * $container = new ContainerBuilder(new ParameterBag(['foo' => 'bar'])); * $loader = new LoaderXXX($container); * $loader->load('resource_name'); * $container->register('foo', 'stdClass'); * * In the above example, even if the loaded resource defines a foo * parameter, the value will still be 'bar' as defined in the ContainerBuilder * constructor. * * @throws BadMethodCallException When this ContainerBuilder is compiled */ public function merge(self $container) { if ($this->isCompiled()) { throw new BadMethodCallException('Cannot merge on a compiled container.'); } $this->addDefinitions($container->getDefinitions()); $this->addAliases($container->getAliases()); $this->getParameterBag()->add($container->getParameterBag()->all()); if ($this->trackResources) { foreach ($container->getResources() as $resource) { $this->addResource($resource); } } foreach ($this->extensions as $name => $extension) { if (!isset($this->extensionConfigs[$name])) { $this->extensionConfigs[$name] = []; } $this->extensionConfigs[$name] = array_merge($this->extensionConfigs[$name], $container->getExtensionConfig($name)); } if ($this->getParameterBag() instanceof EnvPlaceholderParameterBag && $container->getParameterBag() instanceof EnvPlaceholderParameterBag) { $envPlaceholders = $container->getParameterBag()->getEnvPlaceholders(); $this->getParameterBag()->mergeEnvPlaceholders($container->getParameterBag()); } else { $envPlaceholders = []; } foreach ($container->envCounters as $env => $count) { if (!$count && !isset($envPlaceholders[$env])) { continue; } if (!isset($this->envCounters[$env])) { $this->envCounters[$env] = $count; } else { $this->envCounters[$env] += $count; } } foreach ($container->getAutoconfiguredInstanceof() as $interface => $childDefinition) { if (isset($this->autoconfiguredInstanceof[$interface])) { throw new InvalidArgumentException(sprintf('"%s" has already been autoconfigured and merge() does not support merging autoconfiguration for the same class/interface.', $interface)); } $this->autoconfiguredInstanceof[$interface] = $childDefinition; } } /** * Returns the configuration array for the given extension. * * @param string $name The name of the extension * * @return array An array of configuration */ public function getExtensionConfig($name) { if (!isset($this->extensionConfigs[$name])) { $this->extensionConfigs[$name] = []; } return $this->extensionConfigs[$name]; } /** * Prepends a config array to the configs of the given extension. * * @param string $name The name of the extension * @param array $config The config to set */ public function prependExtensionConfig($name, array $config) { if (!isset($this->extensionConfigs[$name])) { $this->extensionConfigs[$name] = []; } array_unshift($this->extensionConfigs[$name], $config); } /** * Compiles the container. * * This method passes the container to compiler * passes whose job is to manipulate and optimize * the container. * * The main compiler passes roughly do four things: * * * The extension configurations are merged; * * Parameter values are resolved; * * The parameter bag is frozen; * * Extension loading is disabled. * * @param bool $resolveEnvPlaceholders Whether %env()% parameters should be resolved using the current * env vars or be replaced by uniquely identifiable placeholders. * Set to "true" when you want to use the current ContainerBuilder * directly, keep to "false" when the container is dumped instead. */ public function compile(/*$resolveEnvPlaceholders = false*/) { if (1 <= \func_num_args()) { $resolveEnvPlaceholders = func_get_arg(0); } else { if (__CLASS__ !== static::class) { $r = new \ReflectionMethod($this, __FUNCTION__); if (__CLASS__ !== $r->getDeclaringClass()->getName() && (1 > $r->getNumberOfParameters() || 'resolveEnvPlaceholders' !== $r->getParameters()[0]->name)) { @trigger_error(sprintf('The %s::compile() method expects a first "$resolveEnvPlaceholders" argument since Symfony 3.3. It will be made mandatory in 4.0.', static::class), \E_USER_DEPRECATED); } } $resolveEnvPlaceholders = false; } $compiler = $this->getCompiler(); if ($this->trackResources) { foreach ($compiler->getPassConfig()->getPasses() as $pass) { $this->addObjectResource($pass); } } $bag = $this->getParameterBag(); if ($resolveEnvPlaceholders && $bag instanceof EnvPlaceholderParameterBag) { $compiler->addPass(new ResolveEnvPlaceholdersPass(), PassConfig::TYPE_AFTER_REMOVING, -1000); } $compiler->compile($this); foreach ($this->definitions as $id => $definition) { if ($this->trackResources && $definition->isLazy()) { $this->getReflectionClass($definition->getClass()); } } $this->extensionConfigs = []; if ($bag instanceof EnvPlaceholderParameterBag) { if ($resolveEnvPlaceholders) { $this->parameterBag = new ParameterBag($this->resolveEnvPlaceholders($bag->all(), true)); } $this->envPlaceholders = $bag->getEnvPlaceholders(); } parent::compile(); foreach ($this->definitions + $this->aliasDefinitions as $id => $definition) { if (!$definition->isPublic() || $definition->isPrivate()) { $this->removedIds[$id] = true; } } } /** * {@inheritdoc} */ public function getServiceIds() { return array_map('strval', array_unique(array_merge(array_keys($this->getDefinitions()), array_keys($this->aliasDefinitions), parent::getServiceIds()))); } /** * Gets removed service or alias ids. * * @return array */ public function getRemovedIds() { return $this->removedIds; } /** * Adds the service aliases. */ public function addAliases(array $aliases) { foreach ($aliases as $alias => $id) { $this->setAlias($alias, $id); } } /** * Sets the service aliases. */ public function setAliases(array $aliases) { $this->aliasDefinitions = []; $this->addAliases($aliases); } /** * Sets an alias for an existing service. * * @param string $alias The alias to create * @param string|Alias $id The service to alias * * @return Alias * * @throws InvalidArgumentException if the id is not a string or an Alias * @throws InvalidArgumentException if the alias is for itself */ public function setAlias($alias, $id) { $alias = $this->normalizeId($alias); if ('' === $alias || '\\' === substr($alias, -1) || \strlen($alias) !== strcspn($alias, "\0\r\n'")) { throw new InvalidArgumentException(sprintf('Invalid alias id: "%s".', $alias)); } if (\is_string($id)) { $id = new Alias($this->normalizeId($id)); } elseif (!$id instanceof Alias) { throw new InvalidArgumentException('$id must be a string, or an Alias object.'); } if ($alias === (string) $id) { throw new InvalidArgumentException(sprintf('An alias can not reference itself, got a circular reference on "%s".', $alias)); } unset($this->definitions[$alias], $this->removedIds[$alias]); return $this->aliasDefinitions[$alias] = $id; } /** * Removes an alias. * * @param string $alias The alias to remove */ public function removeAlias($alias) { if (isset($this->aliasDefinitions[$alias = $this->normalizeId($alias)])) { unset($this->aliasDefinitions[$alias]); $this->removedIds[$alias] = true; } } /** * Returns true if an alias exists under the given identifier. * * @param string $id The service identifier * * @return bool true if the alias exists, false otherwise */ public function hasAlias($id) { return isset($this->aliasDefinitions[$this->normalizeId($id)]); } /** * Gets all defined aliases. * * @return Alias[] An array of aliases */ public function getAliases() { return $this->aliasDefinitions; } /** * Gets an alias. * * @param string $id The service identifier * * @return Alias An Alias instance * * @throws InvalidArgumentException if the alias does not exist */ public function getAlias($id) { $id = $this->normalizeId($id); if (!isset($this->aliasDefinitions[$id])) { throw new InvalidArgumentException(sprintf('The service alias "%s" does not exist.', $id)); } return $this->aliasDefinitions[$id]; } /** * Registers a service definition. * * This methods allows for simple registration of service definition * with a fluid interface. * * @param string $id The service identifier * @param string|null $class The service class * * @return Definition A Definition instance */ public function register($id, $class = null) { return $this->setDefinition($id, new Definition($class)); } /** * Registers an autowired service definition. * * This method implements a shortcut for using setDefinition() with * an autowired definition. * * @param string $id The service identifier * @param string|null $class The service class * * @return Definition The created definition */ public function autowire($id, $class = null) { return $this->setDefinition($id, (new Definition($class))->setAutowired(true)); } /** * Adds the service definitions. * * @param Definition[] $definitions An array of service definitions */ public function addDefinitions(array $definitions) { foreach ($definitions as $id => $definition) { $this->setDefinition($id, $definition); } } /** * Sets the service definitions. * * @param Definition[] $definitions An array of service definitions */ public function setDefinitions(array $definitions) { $this->definitions = []; $this->addDefinitions($definitions); } /** * Gets all service definitions. * * @return Definition[] An array of Definition instances */ public function getDefinitions() { return $this->definitions; } /** * Sets a service definition. * * @param string $id The service identifier * @param Definition $definition A Definition instance * * @return Definition the service definition * * @throws BadMethodCallException When this ContainerBuilder is compiled */ public function setDefinition($id, Definition $definition) { if ($this->isCompiled()) { throw new BadMethodCallException('Adding definition to a compiled container is not allowed.'); } $id = $this->normalizeId($id); if ('' === $id || '\\' === substr($id, -1) || \strlen($id) !== strcspn($id, "\0\r\n'")) { throw new InvalidArgumentException(sprintf('Invalid service id: "%s".', $id)); } unset($this->aliasDefinitions[$id], $this->removedIds[$id]); return $this->definitions[$id] = $definition; } /** * Returns true if a service definition exists under the given identifier. * * @param string $id The service identifier * * @return bool true if the service definition exists, false otherwise */ public function hasDefinition($id) { return isset($this->definitions[$this->normalizeId($id)]); } /** * Gets a service definition. * * @param string $id The service identifier * * @return Definition A Definition instance * * @throws ServiceNotFoundException if the service definition does not exist */ public function getDefinition($id) { $id = $this->normalizeId($id); if (!isset($this->definitions[$id])) { throw new ServiceNotFoundException($id); } return $this->definitions[$id]; } /** * Gets a service definition by id or alias. * * The method "unaliases" recursively to return a Definition instance. * * @param string $id The service identifier or alias * * @return Definition A Definition instance * * @throws ServiceNotFoundException if the service definition does not exist */ public function findDefinition($id) { $id = $this->normalizeId($id); $seen = []; while (isset($this->aliasDefinitions[$id])) { $id = (string) $this->aliasDefinitions[$id]; if (isset($seen[$id])) { $seen = array_values($seen); $seen = \array_slice($seen, array_search($id, $seen)); $seen[] = $id; throw new ServiceCircularReferenceException($id, $seen); } $seen[$id] = $id; } return $this->getDefinition($id); } /** * Creates a service for a service definition. * * @param Definition $definition A service definition instance * @param string $id The service identifier * @param bool $tryProxy Whether to try proxying the service with a lazy proxy * * @return mixed The service described by the service definition * * @throws RuntimeException When the factory definition is incomplete * @throws RuntimeException When the service is a synthetic service * @throws InvalidArgumentException When configure callable is not callable */ private function createService(Definition $definition, array &$inlineServices, $isConstructorArgument = false, $id = null, $tryProxy = true) { if (null === $id && isset($inlineServices[$h = spl_object_hash($definition)])) { return $inlineServices[$h]; } if ($definition instanceof ChildDefinition) { throw new RuntimeException(sprintf('Constructing service "%s" from a parent definition is not supported at build time.', $id)); } if ($definition->isSynthetic()) { throw new RuntimeException(sprintf('You have requested a synthetic service ("%s"). The DIC does not know how to construct this service.', $id)); } if ($definition->isDeprecated()) { @trigger_error($definition->getDeprecationMessage($id), \E_USER_DEPRECATED); } if ($tryProxy && $definition->isLazy() && !$tryProxy = !($proxy = $this->proxyInstantiator) || $proxy instanceof RealServiceInstantiator) { $proxy = $proxy->instantiateProxy( $this, $definition, $id, function () use ($definition, &$inlineServices, $id) { return $this->createService($definition, $inlineServices, true, $id, false); } ); $this->shareService($definition, $proxy, $id, $inlineServices); return $proxy; } $parameterBag = $this->getParameterBag(); if (null !== $definition->getFile()) { require_once $parameterBag->resolveValue($definition->getFile()); } $arguments = $this->doResolveServices($parameterBag->unescapeValue($parameterBag->resolveValue($definition->getArguments())), $inlineServices, $isConstructorArgument); if (null !== $factory = $definition->getFactory()) { if (\is_array($factory)) { $factory = [$this->doResolveServices($parameterBag->resolveValue($factory[0]), $inlineServices, $isConstructorArgument), $factory[1]]; } elseif (!\is_string($factory)) { throw new RuntimeException(sprintf('Cannot create service "%s" because of invalid factory.', $id)); } } if (null !== $id && $definition->isShared() && isset($this->services[$id]) && ($tryProxy || !$definition->isLazy())) { return $this->services[$id]; } if (null !== $factory) { $service = \call_user_func_array($factory, $arguments); if (!$definition->isDeprecated() && \is_array($factory) && \is_string($factory[0])) { $r = new \ReflectionClass($factory[0]); if (0 < strpos($r->getDocComment(), "\n * @deprecated ")) { @trigger_error(sprintf('The "%s" service relies on the deprecated "%s" factory class. It should either be deprecated or its factory upgraded.', $id, $r->name), \E_USER_DEPRECATED); } } } else { $r = new \ReflectionClass($class = $parameterBag->resolveValue($definition->getClass())); $service = null === $r->getConstructor() ? $r->newInstance() : $r->newInstanceArgs(array_values($arguments)); // don't trigger deprecations for internal uses // @deprecated since version 3.3, to be removed in 4.0 along with the deprecated class $deprecationAllowlist = ['event_dispatcher' => ContainerAwareEventDispatcher::class]; if (!$definition->isDeprecated() && 0 < strpos($r->getDocComment(), "\n * @deprecated ") && (!isset($deprecationAllowlist[$id]) || $deprecationAllowlist[$id] !== $class)) { @trigger_error(sprintf('The "%s" service relies on the deprecated "%s" class. It should either be deprecated or its implementation upgraded.', $id, $r->name), \E_USER_DEPRECATED); } } if ($tryProxy || !$definition->isLazy()) { // share only if proxying failed, or if not a proxy $this->shareService($definition, $service, $id, $inlineServices); } $properties = $this->doResolveServices($parameterBag->unescapeValue($parameterBag->resolveValue($definition->getProperties())), $inlineServices); foreach ($properties as $name => $value) { $service->$name = $value; } foreach ($definition->getMethodCalls() as $call) { $this->callMethod($service, $call, $inlineServices); } if ($callable = $definition->getConfigurator()) { if (\is_array($callable)) { $callable[0] = $parameterBag->resolveValue($callable[0]); if ($callable[0] instanceof Reference) { $callable[0] = $this->doGet((string) $callable[0], $callable[0]->getInvalidBehavior(), $inlineServices); } elseif ($callable[0] instanceof Definition) { $callable[0] = $this->createService($callable[0], $inlineServices); } } if (!\is_callable($callable)) { throw new InvalidArgumentException(sprintf('The configure callable for class "%s" is not a callable.', \get_class($service))); } \call_user_func($callable, $service); } return $service; } /** * Replaces service references by the real service instance and evaluates expressions. * * @param mixed $value A value * * @return mixed The same value with all service references replaced by * the real service instances and all expressions evaluated */ public function resolveServices($value) { return $this->doResolveServices($value); } private function doResolveServices($value, array &$inlineServices = [], $isConstructorArgument = false) { if (\is_array($value)) { foreach ($value as $k => $v) { $value[$k] = $this->doResolveServices($v, $inlineServices, $isConstructorArgument); } } elseif ($value instanceof ServiceClosureArgument) { $reference = $value->getValues()[0]; $value = function () use ($reference) { return $this->resolveServices($reference); }; } elseif ($value instanceof IteratorArgument) { $value = new RewindableGenerator(function () use ($value) { foreach ($value->getValues() as $k => $v) { foreach (self::getServiceConditionals($v) as $s) { if (!$this->has($s)) { continue 2; } } foreach (self::getInitializedConditionals($v) as $s) { if (!$this->doGet($s, ContainerInterface::IGNORE_ON_UNINITIALIZED_REFERENCE)) { continue 2; } } yield $k => $this->resolveServices($v); } }, function () use ($value) { $count = 0; foreach ($value->getValues() as $v) { foreach (self::getServiceConditionals($v) as $s) { if (!$this->has($s)) { continue 2; } } foreach (self::getInitializedConditionals($v) as $s) { if (!$this->doGet($s, ContainerInterface::IGNORE_ON_UNINITIALIZED_REFERENCE)) { continue 2; } } ++$count; } return $count; }); } elseif ($value instanceof Reference) { $value = $this->doGet((string) $value, $value->getInvalidBehavior(), $inlineServices, $isConstructorArgument); } elseif ($value instanceof Definition) { $value = $this->createService($value, $inlineServices, $isConstructorArgument); } elseif ($value instanceof Parameter) { $value = $this->getParameter((string) $value); } elseif ($value instanceof Expression) { $value = $this->getExpressionLanguage()->evaluate($value, ['container' => $this]); } return $value; } /** * Returns service ids for a given tag. * * Example: * * $container->register('foo')->addTag('my.tag', ['hello' => 'world']); * * $serviceIds = $container->findTaggedServiceIds('my.tag'); * foreach ($serviceIds as $serviceId => $tags) { * foreach ($tags as $tag) { * echo $tag['hello']; * } * } * * @param string $name * @param bool $throwOnAbstract * * @return array An array of tags with the tagged service as key, holding a list of attribute arrays */ public function findTaggedServiceIds($name, $throwOnAbstract = false) { $this->usedTags[] = $name; $tags = []; foreach ($this->getDefinitions() as $id => $definition) { if ($definition->hasTag($name)) { if ($throwOnAbstract && $definition->isAbstract()) { throw new InvalidArgumentException(sprintf('The service "%s" tagged "%s" must not be abstract.', $id, $name)); } $tags[$id] = $definition->getTag($name); } } return $tags; } /** * Returns all tags the defined services use. * * @return array An array of tags */ public function findTags() { $tags = []; foreach ($this->getDefinitions() as $id => $definition) { $tags = array_merge(array_keys($definition->getTags()), $tags); } return array_unique($tags); } /** * Returns all tags not queried by findTaggedServiceIds. * * @return string[] An array of tags */ public function findUnusedTags() { return array_values(array_diff($this->findTags(), $this->usedTags)); } public function addExpressionLanguageProvider(ExpressionFunctionProviderInterface $provider) { $this->expressionLanguageProviders[] = $provider; } /** * @return ExpressionFunctionProviderInterface[] */ public function getExpressionLanguageProviders() { return $this->expressionLanguageProviders; } /** * Returns a ChildDefinition that will be used for autoconfiguring the interface/class. * * @param string $interface The class or interface to match * * @return ChildDefinition */ public function registerForAutoconfiguration($interface) { if (!isset($this->autoconfiguredInstanceof[$interface])) { $this->autoconfiguredInstanceof[$interface] = new ChildDefinition(''); } return $this->autoconfiguredInstanceof[$interface]; } /** * Returns an array of ChildDefinition[] keyed by interface. * * @return ChildDefinition[] */ public function getAutoconfiguredInstanceof() { return $this->autoconfiguredInstanceof; } /** * Resolves env parameter placeholders in a string or an array. * * @param mixed $value The value to resolve * @param string|true|null $format A sprintf() format returning the replacement for each env var name or * null to resolve back to the original "%env(VAR)%" format or * true to resolve to the actual values of the referenced env vars * @param array &$usedEnvs Env vars found while resolving are added to this array * * @return mixed The value with env parameters resolved if a string or an array is passed */ public function resolveEnvPlaceholders($value, $format = null, array &$usedEnvs = null) { if (null === $format) { $format = '%%env(%s)%%'; } $bag = $this->getParameterBag(); if (true === $format) { $value = $bag->resolveValue($value); } if (\is_array($value)) { $result = []; foreach ($value as $k => $v) { $result[\is_string($k) ? $this->resolveEnvPlaceholders($k, $format, $usedEnvs) : $k] = $this->resolveEnvPlaceholders($v, $format, $usedEnvs); } return $result; } if (!\is_string($value) || 38 > \strlen($value)) { return $value; } $envPlaceholders = $bag instanceof EnvPlaceholderParameterBag ? $bag->getEnvPlaceholders() : $this->envPlaceholders; $completed = false; foreach ($envPlaceholders as $env => $placeholders) { foreach ($placeholders as $placeholder) { if (false !== stripos($value, $placeholder)) { if (true === $format) { $resolved = $bag->escapeValue($this->getEnv($env)); } else { $resolved = sprintf($format, $env); } if ($placeholder === $value) { $value = $resolved; $completed = true; } else { if (!\is_string($resolved) && !is_numeric($resolved)) { throw new RuntimeException(sprintf('A string value must be composed of strings and/or numbers, but found parameter "env(%s)" of type "%s" inside string value "%s".', $env, \gettype($resolved), $this->resolveEnvPlaceholders($value))); } $value = str_ireplace($placeholder, $resolved, $value); } $usedEnvs[$env] = $env; $this->envCounters[$env] = isset($this->envCounters[$env]) ? 1 + $this->envCounters[$env] : 1; if ($completed) { break 2; } } } } return $value; } /** * Get statistics about env usage. * * @return int[] The number of time each env vars has been resolved */ public function getEnvCounters() { $bag = $this->getParameterBag(); $envPlaceholders = $bag instanceof EnvPlaceholderParameterBag ? $bag->getEnvPlaceholders() : $this->envPlaceholders; foreach ($envPlaceholders as $env => $placeholders) { if (!isset($this->envCounters[$env])) { $this->envCounters[$env] = 0; } } return $this->envCounters; } /** * @internal */ public function getNormalizedIds() { $normalizedIds = []; foreach ($this->normalizedIds as $k => $v) { if ($v !== (string) $k) { $normalizedIds[$k] = $v; } } return $normalizedIds; } /** * @final */ public function log(CompilerPassInterface $pass, $message) { $this->getCompiler()->log($pass, $this->resolveEnvPlaceholders($message)); } /** * {@inheritdoc} */ public function normalizeId($id) { if (!\is_string($id)) { $id = (string) $id; } return isset($this->definitions[$id]) || isset($this->aliasDefinitions[$id]) || isset($this->removedIds[$id]) ? $id : parent::normalizeId($id); } /** * Gets removed binding ids. * * @return array * * @internal */ public function getRemovedBindingIds() { return $this->removedBindingIds; } /** * Removes bindings for a service. * * @param string $id The service identifier * * @internal */ public function removeBindings($id) { if ($this->hasDefinition($id)) { foreach ($this->getDefinition($id)->getBindings() as $key => $binding) { list(, $bindingId) = $binding->getValues(); $this->removedBindingIds[(int) $bindingId] = true; } } } /** * Returns the Service Conditionals. * * @param mixed $value An array of conditionals to return * * @return array An array of Service conditionals * * @internal since version 3.4 */ public static function getServiceConditionals($value) { $services = []; if (\is_array($value)) { foreach ($value as $v) { $services = array_unique(array_merge($services, self::getServiceConditionals($v))); } } elseif ($value instanceof Reference && ContainerInterface::IGNORE_ON_INVALID_REFERENCE === $value->getInvalidBehavior()) { $services[] = (string) $value; } return $services; } /** * Returns the initialized conditionals. * * @param mixed $value An array of conditionals to return * * @return array An array of uninitialized conditionals * * @internal */ public static function getInitializedConditionals($value) { $services = []; if (\is_array($value)) { foreach ($value as $v) { $services = array_unique(array_merge($services, self::getInitializedConditionals($v))); } } elseif ($value instanceof Reference && ContainerInterface::IGNORE_ON_UNINITIALIZED_REFERENCE === $value->getInvalidBehavior()) { $services[] = (string) $value; } return $services; } /** * Computes a reasonably unique hash of a value. * * @param mixed $value A serializable value * * @return string */ public static function hash($value) { $hash = substr(base64_encode(hash('sha256', serialize($value), true)), 0, 7); return str_replace(['/', '+'], ['.', '_'], strtolower($hash)); } /** * {@inheritdoc} */ protected function getEnv($name) { $value = parent::getEnv($name); $bag = $this->getParameterBag(); if (!\is_string($value) || !$bag instanceof EnvPlaceholderParameterBag) { return $value; } foreach ($bag->getEnvPlaceholders() as $env => $placeholders) { if (isset($placeholders[$value])) { $bag = new ParameterBag($bag->all()); return $bag->unescapeValue($bag->get("env($name)")); } } $this->resolving["env($name)"] = true; try { return $bag->unescapeValue($this->resolveEnvPlaceholders($bag->escapeValue($value), true)); } finally { unset($this->resolving["env($name)"]); } } private function callMethod($service, $call, array &$inlineServices) { foreach (self::getServiceConditionals($call[1]) as $s) { if (!$this->has($s)) { return; } } foreach (self::getInitializedConditionals($call[1]) as $s) { if (!$this->doGet($s, ContainerInterface::IGNORE_ON_UNINITIALIZED_REFERENCE, $inlineServices)) { return; } } \call_user_func_array([$service, $call[0]], $this->doResolveServices($this->getParameterBag()->unescapeValue($this->getParameterBag()->resolveValue($call[1])), $inlineServices)); } /** * Shares a given service in the container. * * @param mixed $service * @param string|null $id */ private function shareService(Definition $definition, $service, $id, array &$inlineServices) { $inlineServices[null !== $id ? $id : spl_object_hash($definition)] = $service; if (null !== $id && $definition->isShared()) { $this->services[$id] = $service; unset($this->loading[$id]); } } private function getExpressionLanguage() { if (null === $this->expressionLanguage) { if (!class_exists('Symfony\Component\ExpressionLanguage\ExpressionLanguage')) { throw new RuntimeException('Unable to use expressions as the Symfony ExpressionLanguage component is not installed.'); } $this->expressionLanguage = new ExpressionLanguage(null, $this->expressionLanguageProviders); } return $this->expressionLanguage; } private function inVendors($path) { if (null === $this->vendors) { $resource = new ComposerResource(); $this->vendors = $resource->getVendors(); $this->addResource($resource); } $path = realpath($path) ?: $path; foreach ($this->vendors as $vendor) { if (0 === strpos($path, $vendor) && false !== strpbrk(substr($path, \strlen($vendor), 1), '/'.\DIRECTORY_SEPARATOR)) { return true; } } return false; } } * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\DependencyInjection\Dumper; use Symfony\Component\DependencyInjection\Alias; use Symfony\Component\DependencyInjection\Argument\ArgumentInterface; use Symfony\Component\DependencyInjection\Argument\IteratorArgument; use Symfony\Component\DependencyInjection\Argument\ServiceClosureArgument; use Symfony\Component\DependencyInjection\Argument\TaggedIteratorArgument; use Symfony\Component\DependencyInjection\ContainerInterface; use Symfony\Component\DependencyInjection\Definition; use Symfony\Component\DependencyInjection\Exception\RuntimeException; use Symfony\Component\DependencyInjection\Parameter; use Symfony\Component\DependencyInjection\Reference; use Symfony\Component\ExpressionLanguage\Expression; use Symfony\Component\Yaml\Dumper as YmlDumper; use Symfony\Component\Yaml\Parser; use Symfony\Component\Yaml\Tag\TaggedValue; use Symfony\Component\Yaml\Yaml; /** * YamlDumper dumps a service container as a YAML string. * * @author Fabien Potencier */ class YamlDumper extends Dumper { private $dumper; /** * Dumps the service container as an YAML string. * * @return string A YAML string representing of the service container */ public function dump(array $options = []) { if (!class_exists('Symfony\Component\Yaml\Dumper')) { throw new RuntimeException('Unable to dump the container as the Symfony Yaml Component is not installed.'); } if (null === $this->dumper) { $this->dumper = new YmlDumper(); } return $this->container->resolveEnvPlaceholders($this->addParameters()."\n".$this->addServices()); } /** * Adds a service. * * @param string $id * * @return string */ private function addService($id, Definition $definition) { $code = " $id:\n"; if ($class = $definition->getClass()) { if ('\\' === substr($class, 0, 1)) { $class = substr($class, 1); } $code .= sprintf(" class: %s\n", $this->dumper->dump($class)); } if (!$definition->isPrivate()) { $code .= sprintf(" public: %s\n", $definition->isPublic() ? 'true' : 'false'); } $tagsCode = ''; foreach ($definition->getTags() as $name => $tags) { foreach ($tags as $attributes) { $att = []; foreach ($attributes as $key => $value) { $att[] = sprintf('%s: %s', $this->dumper->dump($key), $this->dumper->dump($value)); } $att = $att ? ', '.implode(', ', $att) : ''; $tagsCode .= sprintf(" - { name: %s%s }\n", $this->dumper->dump($name), $att); } } if ($tagsCode) { $code .= " tags:\n".$tagsCode; } if ($definition->getFile()) { $code .= sprintf(" file: %s\n", $this->dumper->dump($definition->getFile())); } if ($definition->isSynthetic()) { $code .= " synthetic: true\n"; } if ($definition->isDeprecated()) { $code .= sprintf(" deprecated: %s\n", $this->dumper->dump($definition->getDeprecationMessage('%service_id%'))); } if ($definition->isAutowired()) { $code .= " autowire: true\n"; } $autowiringTypesCode = ''; foreach ($definition->getAutowiringTypes(false) as $autowiringType) { $autowiringTypesCode .= sprintf(" - %s\n", $this->dumper->dump($autowiringType)); } if ($autowiringTypesCode) { $code .= sprintf(" autowiring_types:\n%s", $autowiringTypesCode); } if ($definition->isAutoconfigured()) { $code .= " autoconfigure: true\n"; } if ($definition->isAbstract()) { $code .= " abstract: true\n"; } if ($definition->isLazy()) { $code .= " lazy: true\n"; } if ($definition->getArguments()) { $code .= sprintf(" arguments: %s\n", $this->dumper->dump($this->dumpValue($definition->getArguments()), 0)); } if ($definition->getProperties()) { $code .= sprintf(" properties: %s\n", $this->dumper->dump($this->dumpValue($definition->getProperties()), 0)); } if ($definition->getMethodCalls()) { $code .= sprintf(" calls:\n%s\n", $this->dumper->dump($this->dumpValue($definition->getMethodCalls()), 1, 12)); } if (!$definition->isShared()) { $code .= " shared: false\n"; } if (null !== $decorated = $definition->getDecoratedService()) { list($decorated, $renamedId, $priority) = $decorated; $code .= sprintf(" decorates: %s\n", $decorated); if (null !== $renamedId) { $code .= sprintf(" decoration_inner_name: %s\n", $renamedId); } if (0 !== $priority) { $code .= sprintf(" decoration_priority: %s\n", $priority); } } if ($callable = $definition->getFactory()) { $code .= sprintf(" factory: %s\n", $this->dumper->dump($this->dumpCallable($callable), 0)); } if ($callable = $definition->getConfigurator()) { $code .= sprintf(" configurator: %s\n", $this->dumper->dump($this->dumpCallable($callable), 0)); } return $code; } /** * Adds a service alias. * * @param string $alias * * @return string */ private function addServiceAlias($alias, Alias $id) { if ($id->isPrivate()) { return sprintf(" %s: '@%s'\n", $alias, $id); } return sprintf(" %s:\n alias: %s\n public: %s\n", $alias, $id, $id->isPublic() ? 'true' : 'false'); } /** * Adds services. * * @return string */ private function addServices() { if (!$this->container->getDefinitions()) { return ''; } $code = "services:\n"; foreach ($this->container->getDefinitions() as $id => $definition) { $code .= $this->addService($id, $definition); } $aliases = $this->container->getAliases(); foreach ($aliases as $alias => $id) { while (isset($aliases[(string) $id])) { $id = $aliases[(string) $id]; } $code .= $this->addServiceAlias($alias, $id); } return $code; } /** * Adds parameters. * * @return string */ private function addParameters() { if (!$this->container->getParameterBag()->all()) { return ''; } $parameters = $this->prepareParameters($this->container->getParameterBag()->all(), $this->container->isCompiled()); return $this->dumper->dump(['parameters' => $parameters], 2); } /** * Dumps callable to YAML format. * * @param mixed $callable */ private function dumpCallable($callable) { if (\is_array($callable)) { if ($callable[0] instanceof Reference) { $callable = [$this->getServiceCall((string) $callable[0], $callable[0]), $callable[1]]; } else { $callable = [$callable[0], $callable[1]]; } } return $callable; } /** * Dumps the value to YAML format. * * @param mixed $value * * @return mixed * * @throws RuntimeException When trying to dump object or resource */ private function dumpValue($value) { if ($value instanceof ServiceClosureArgument) { $value = $value->getValues()[0]; } if ($value instanceof ArgumentInterface) { if ($value instanceof TaggedIteratorArgument) { return new TaggedValue('tagged', $value->getTag()); } if ($value instanceof IteratorArgument) { $tag = 'iterator'; } else { throw new RuntimeException(sprintf('Unspecified Yaml tag for type "%s".', \get_class($value))); } return new TaggedValue($tag, $this->dumpValue($value->getValues())); } if (\is_array($value)) { $code = []; foreach ($value as $k => $v) { $code[$k] = $this->dumpValue($v); } return $code; } elseif ($value instanceof Reference) { return $this->getServiceCall((string) $value, $value); } elseif ($value instanceof Parameter) { return $this->getParameterCall((string) $value); } elseif ($value instanceof Expression) { return $this->getExpressionCall((string) $value); } elseif ($value instanceof Definition) { return new TaggedValue('service', (new Parser())->parse("_:\n".$this->addService('_', $value), Yaml::PARSE_CUSTOM_TAGS)['_']['_']); } elseif (\is_object($value) || \is_resource($value)) { throw new RuntimeException('Unable to dump a service container if a parameter is an object or a resource.'); } return $value; } /** * Gets the service call. * * @param string $id * @param Reference $reference * * @return string */ private function getServiceCall($id, Reference $reference = null) { if (null !== $reference) { switch ($reference->getInvalidBehavior()) { case ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE: break; case ContainerInterface::IGNORE_ON_UNINITIALIZED_REFERENCE: return sprintf('@!%s', $id); default: return sprintf('@?%s', $id); } } return sprintf('@%s', $id); } /** * Gets parameter call. * * @param string $id * * @return string */ private function getParameterCall($id) { return sprintf('%%%s%%', $id); } private function getExpressionCall($expression) { return sprintf('@=%s', $expression); } /** * Prepares parameters. * * @param bool $escape * * @return array */ private function prepareParameters(array $parameters, $escape = true) { $filtered = []; foreach ($parameters as $key => $value) { if (\is_array($value)) { $value = $this->prepareParameters($value, $escape); } elseif ($value instanceof Reference || \is_string($value) && 0 === strpos($value, '@')) { $value = '@'.$value; } $filtered[$key] = $value; } return $escape ? $this->escape($filtered) : $filtered; } /** * Escapes arguments. * * @return array */ private function escape(array $arguments) { $args = []; foreach ($arguments as $k => $v) { if (\is_array($v)) { $args[$k] = $this->escape($v); } elseif (\is_string($v)) { $args[$k] = str_replace('%', '%%', $v); } else { $args[$k] = $v; } } return $args; } } * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\DependencyInjection\Dumper; /** * DumperInterface is the interface implemented by service container dumper classes. * * @author Fabien Potencier */ interface DumperInterface { /** * Dumps the service container. * * @return string|array The representation of the service container */ public function dump(array $options = []); } * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\DependencyInjection\Dumper; use Symfony\Component\DependencyInjection\Alias; use Symfony\Component\DependencyInjection\Argument\IteratorArgument; use Symfony\Component\DependencyInjection\Argument\ServiceClosureArgument; use Symfony\Component\DependencyInjection\Argument\TaggedIteratorArgument; use Symfony\Component\DependencyInjection\ContainerInterface; use Symfony\Component\DependencyInjection\Definition; use Symfony\Component\DependencyInjection\Exception\RuntimeException; use Symfony\Component\DependencyInjection\Parameter; use Symfony\Component\DependencyInjection\Reference; use Symfony\Component\ExpressionLanguage\Expression; /** * XmlDumper dumps a service container as an XML string. * * @author Fabien Potencier * @author Martin HasoĊˆ */ class XmlDumper extends Dumper { /** * @var \DOMDocument */ private $document; /** * Dumps the service container as an XML string. * * @return string An xml string representing of the service container */ public function dump(array $options = []) { $this->document = new \DOMDocument('1.0', 'utf-8'); $this->document->formatOutput = true; $container = $this->document->createElementNS('http://symfony.com/schema/dic/services', 'container'); $container->setAttribute('xmlns:xsi', 'http://www.w3.org/2001/XMLSchema-instance'); $container->setAttribute('xsi:schemaLocation', 'http://symfony.com/schema/dic/services https://symfony.com/schema/dic/services/services-1.0.xsd'); $this->addParameters($container); $this->addServices($container); $this->document->appendChild($container); $xml = $this->document->saveXML(); $this->document = null; return $this->container->resolveEnvPlaceholders($xml); } private function addParameters(\DOMElement $parent) { $data = $this->container->getParameterBag()->all(); if (!$data) { return; } if ($this->container->isCompiled()) { $data = $this->escape($data); } $parameters = $this->document->createElement('parameters'); $parent->appendChild($parameters); $this->convertParameters($data, 'parameter', $parameters); } private function addMethodCalls(array $methodcalls, \DOMElement $parent) { foreach ($methodcalls as $methodcall) { $call = $this->document->createElement('call'); $call->setAttribute('method', $methodcall[0]); if (\count($methodcall[1])) { $this->convertParameters($methodcall[1], 'argument', $call); } $parent->appendChild($call); } } /** * Adds a service. * * @param Definition $definition * @param string $id */ private function addService($definition, $id, \DOMElement $parent) { $service = $this->document->createElement('service'); if (null !== $id) { $service->setAttribute('id', $id); } if ($class = $definition->getClass()) { if ('\\' === substr($class, 0, 1)) { $class = substr($class, 1); } $service->setAttribute('class', $class); } if (!$definition->isShared()) { $service->setAttribute('shared', 'false'); } if (!$definition->isPrivate()) { $service->setAttribute('public', $definition->isPublic() ? 'true' : 'false'); } if ($definition->isSynthetic()) { $service->setAttribute('synthetic', 'true'); } if ($definition->isLazy()) { $service->setAttribute('lazy', 'true'); } if (null !== $decorated = $definition->getDecoratedService()) { list($decorated, $renamedId, $priority) = $decorated; $service->setAttribute('decorates', $decorated); if (null !== $renamedId) { $service->setAttribute('decoration-inner-name', $renamedId); } if (0 !== $priority) { $service->setAttribute('decoration-priority', $priority); } } foreach ($definition->getTags() as $name => $tags) { foreach ($tags as $attributes) { $tag = $this->document->createElement('tag'); $tag->setAttribute('name', $name); foreach ($attributes as $key => $value) { $tag->setAttribute($key, $value); } $service->appendChild($tag); } } if ($definition->getFile()) { $file = $this->document->createElement('file'); $file->appendChild($this->document->createTextNode($definition->getFile())); $service->appendChild($file); } if ($parameters = $definition->getArguments()) { $this->convertParameters($parameters, 'argument', $service); } if ($parameters = $definition->getProperties()) { $this->convertParameters($parameters, 'property', $service, 'name'); } $this->addMethodCalls($definition->getMethodCalls(), $service); if ($callable = $definition->getFactory()) { $factory = $this->document->createElement('factory'); if (\is_array($callable) && $callable[0] instanceof Definition) { $this->addService($callable[0], null, $factory); $factory->setAttribute('method', $callable[1]); } elseif (\is_array($callable)) { if (null !== $callable[0]) { $factory->setAttribute($callable[0] instanceof Reference ? 'service' : 'class', $callable[0]); } $factory->setAttribute('method', $callable[1]); } else { $factory->setAttribute('function', $callable); } $service->appendChild($factory); } if ($definition->isDeprecated()) { $deprecated = $this->document->createElement('deprecated'); $deprecated->appendChild($this->document->createTextNode($definition->getDeprecationMessage('%service_id%'))); $service->appendChild($deprecated); } if ($definition->isAutowired()) { $service->setAttribute('autowire', 'true'); } foreach ($definition->getAutowiringTypes(false) as $autowiringTypeValue) { $autowiringType = $this->document->createElement('autowiring-type'); $autowiringType->appendChild($this->document->createTextNode($autowiringTypeValue)); $service->appendChild($autowiringType); } if ($definition->isAutoconfigured()) { $service->setAttribute('autoconfigure', 'true'); } if ($definition->isAbstract()) { $service->setAttribute('abstract', 'true'); } if ($callable = $definition->getConfigurator()) { $configurator = $this->document->createElement('configurator'); if (\is_array($callable) && $callable[0] instanceof Definition) { $this->addService($callable[0], null, $configurator); $configurator->setAttribute('method', $callable[1]); } elseif (\is_array($callable)) { $configurator->setAttribute($callable[0] instanceof Reference ? 'service' : 'class', $callable[0]); $configurator->setAttribute('method', $callable[1]); } else { $configurator->setAttribute('function', $callable); } $service->appendChild($configurator); } $parent->appendChild($service); } /** * Adds a service alias. * * @param string $alias */ private function addServiceAlias($alias, Alias $id, \DOMElement $parent) { $service = $this->document->createElement('service'); $service->setAttribute('id', $alias); $service->setAttribute('alias', $id); if (!$id->isPrivate()) { $service->setAttribute('public', $id->isPublic() ? 'true' : 'false'); } $parent->appendChild($service); } private function addServices(\DOMElement $parent) { $definitions = $this->container->getDefinitions(); if (!$definitions) { return; } $services = $this->document->createElement('services'); foreach ($definitions as $id => $definition) { $this->addService($definition, $id, $services); } $aliases = $this->container->getAliases(); foreach ($aliases as $alias => $id) { while (isset($aliases[(string) $id])) { $id = $aliases[(string) $id]; } $this->addServiceAlias($alias, $id, $services); } $parent->appendChild($services); } /** * Converts parameters. * * @param string $type * @param string $keyAttribute */ private function convertParameters(array $parameters, $type, \DOMElement $parent, $keyAttribute = 'key') { $withKeys = array_keys($parameters) !== range(0, \count($parameters) - 1); foreach ($parameters as $key => $value) { $element = $this->document->createElement($type); if ($withKeys) { $element->setAttribute($keyAttribute, $key); } if ($value instanceof ServiceClosureArgument) { $value = $value->getValues()[0]; } if (\is_array($value)) { $element->setAttribute('type', 'collection'); $this->convertParameters($value, $type, $element, 'key'); } elseif ($value instanceof TaggedIteratorArgument) { $element->setAttribute('type', 'tagged'); $element->setAttribute('tag', $value->getTag()); } elseif ($value instanceof IteratorArgument) { $element->setAttribute('type', 'iterator'); $this->convertParameters($value->getValues(), $type, $element, 'key'); } elseif ($value instanceof Reference) { $element->setAttribute('type', 'service'); $element->setAttribute('id', (string) $value); $behavior = $value->getInvalidBehavior(); if (ContainerInterface::NULL_ON_INVALID_REFERENCE == $behavior) { $element->setAttribute('on-invalid', 'null'); } elseif (ContainerInterface::IGNORE_ON_INVALID_REFERENCE == $behavior) { $element->setAttribute('on-invalid', 'ignore'); } elseif (ContainerInterface::IGNORE_ON_UNINITIALIZED_REFERENCE == $behavior) { $element->setAttribute('on-invalid', 'ignore_uninitialized'); } } elseif ($value instanceof Definition) { $element->setAttribute('type', 'service'); $this->addService($value, null, $element); } elseif ($value instanceof Expression) { $element->setAttribute('type', 'expression'); $text = $this->document->createTextNode(self::phpToXml((string) $value)); $element->appendChild($text); } else { if (\in_array($value, ['null', 'true', 'false'], true)) { $element->setAttribute('type', 'string'); } if (\is_string($value) && (is_numeric($value) || preg_match('/^0b[01]*$/', $value) || preg_match('/^0x[0-9a-f]++$/i', $value))) { $element->setAttribute('type', 'string'); } $text = $this->document->createTextNode(self::phpToXml($value)); $element->appendChild($text); } $parent->appendChild($element); } } /** * Escapes arguments. * * @return array */ private function escape(array $arguments) { $args = []; foreach ($arguments as $k => $v) { if (\is_array($v)) { $args[$k] = $this->escape($v); } elseif (\is_string($v)) { $args[$k] = str_replace('%', '%%', $v); } else { $args[$k] = $v; } } return $args; } /** * Converts php types to xml types. * * @param mixed $value Value to convert * * @return string * * @throws RuntimeException When trying to dump object or resource */ public static function phpToXml($value) { switch (true) { case null === $value: return 'null'; case true === $value: return 'true'; case false === $value: return 'false'; case $value instanceof Parameter: return '%'.$value.'%'; case \is_object($value) || \is_resource($value): throw new RuntimeException('Unable to dump a service container if a parameter is an object or a resource.'); default: return (string) $value; } } } * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\DependencyInjection\Dumper; use Symfony\Component\DependencyInjection\ContainerBuilder; /** * Dumper is the abstract class for all built-in dumpers. * * @author Fabien Potencier */ abstract class Dumper implements DumperInterface { protected $container; public function __construct(ContainerBuilder $container) { $this->container = $container; } } * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\DependencyInjection\Dumper; use Symfony\Component\DependencyInjection\Argument\ArgumentInterface; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Definition; use Symfony\Component\DependencyInjection\Exception\ParameterNotFoundException; use Symfony\Component\DependencyInjection\Parameter; use Symfony\Component\DependencyInjection\ParameterBag\ParameterBag; use Symfony\Component\DependencyInjection\Reference; /** * GraphvizDumper dumps a service container as a graphviz file. * * You can convert the generated dot file with the dot utility (http://www.graphviz.org/): * * dot -Tpng container.dot > foo.png * * @author Fabien Potencier */ class GraphvizDumper extends Dumper { private $nodes; private $edges; // All values should be strings private $options = [ 'graph' => ['ratio' => 'compress'], 'node' => ['fontsize' => '11', 'fontname' => 'Arial', 'shape' => 'record'], 'edge' => ['fontsize' => '9', 'fontname' => 'Arial', 'color' => 'grey', 'arrowhead' => 'open', 'arrowsize' => '0.5'], 'node.instance' => ['fillcolor' => '#9999ff', 'style' => 'filled'], 'node.definition' => ['fillcolor' => '#eeeeee'], 'node.missing' => ['fillcolor' => '#ff9999', 'style' => 'filled'], ]; /** * Dumps the service container as a graphviz graph. * * Available options: * * * graph: The default options for the whole graph * * node: The default options for nodes * * edge: The default options for edges * * node.instance: The default options for services that are defined directly by object instances * * node.definition: The default options for services that are defined via service definition instances * * node.missing: The default options for missing services * * @return string The dot representation of the service container */ public function dump(array $options = []) { foreach (['graph', 'node', 'edge', 'node.instance', 'node.definition', 'node.missing'] as $key) { if (isset($options[$key])) { $this->options[$key] = array_merge($this->options[$key], $options[$key]); } } $this->nodes = $this->findNodes(); $this->edges = []; foreach ($this->container->getDefinitions() as $id => $definition) { $this->edges[$id] = array_merge( $this->findEdges($id, $definition->getArguments(), true, ''), $this->findEdges($id, $definition->getProperties(), false, '') ); foreach ($definition->getMethodCalls() as $call) { $this->edges[$id] = array_merge( $this->edges[$id], $this->findEdges($id, $call[1], false, $call[0].'()') ); } } return $this->container->resolveEnvPlaceholders($this->startDot().$this->addNodes().$this->addEdges().$this->endDot(), '__ENV_%s__'); } /** * Returns all nodes. * * @return string A string representation of all nodes */ private function addNodes() { $code = ''; foreach ($this->nodes as $id => $node) { $aliases = $this->getAliases($id); $code .= sprintf(" node_%s [label=\"%s\\n%s\\n\", shape=%s%s];\n", $this->dotize($id), $id.($aliases ? ' ('.implode(', ', $aliases).')' : ''), $node['class'], $this->options['node']['shape'], $this->addAttributes($node['attributes'])); } return $code; } /** * Returns all edges. * * @return string A string representation of all edges */ private function addEdges() { $code = ''; foreach ($this->edges as $id => $edges) { foreach ($edges as $edge) { $code .= sprintf(" node_%s -> node_%s [label=\"%s\" style=\"%s\"%s];\n", $this->dotize($id), $this->dotize($edge['to']), $edge['name'], $edge['required'] ? 'filled' : 'dashed', $edge['lazy'] ? ' color="#9999ff"' : ''); } } return $code; } /** * Finds all edges belonging to a specific service id. * * @param string $id The service id used to find edges * @param array $arguments An array of arguments * @param bool $required * @param string $name * * @return array An array of edges */ private function findEdges($id, array $arguments, $required, $name, $lazy = false) { $edges = []; foreach ($arguments as $argument) { if ($argument instanceof Parameter) { $argument = $this->container->hasParameter($argument) ? $this->container->getParameter($argument) : null; } elseif (\is_string($argument) && preg_match('/^%([^%]+)%$/', $argument, $match)) { $argument = $this->container->hasParameter($match[1]) ? $this->container->getParameter($match[1]) : null; } if ($argument instanceof Reference) { $lazyEdge = $lazy; if (!$this->container->has((string) $argument)) { $this->nodes[(string) $argument] = ['name' => $name, 'required' => $required, 'class' => '', 'attributes' => $this->options['node.missing']]; } elseif ('service_container' !== (string) $argument) { $lazyEdge = $lazy || $this->container->getDefinition((string) $argument)->isLazy(); } $edges[] = ['name' => $name, 'required' => $required, 'to' => $argument, 'lazy' => $lazyEdge]; } elseif ($argument instanceof ArgumentInterface) { $edges = array_merge($edges, $this->findEdges($id, $argument->getValues(), $required, $name, true)); } elseif ($argument instanceof Definition) { $edges = array_merge($edges, $this->findEdges($id, $argument->getArguments(), $required, ''), $this->findEdges($id, $argument->getProperties(), false, '') ); foreach ($argument->getMethodCalls() as $call) { $edges = array_merge($edges, $this->findEdges($id, $call[1], false, $call[0].'()')); } } elseif (\is_array($argument)) { $edges = array_merge($edges, $this->findEdges($id, $argument, $required, $name, $lazy)); } } return $edges; } /** * Finds all nodes. * * @return array An array of all nodes */ private function findNodes() { $nodes = []; $container = $this->cloneContainer(); foreach ($container->getDefinitions() as $id => $definition) { $class = $definition->getClass(); if ('\\' === substr($class, 0, 1)) { $class = substr($class, 1); } try { $class = $this->container->getParameterBag()->resolveValue($class); } catch (ParameterNotFoundException $e) { } $nodes[$id] = ['class' => str_replace('\\', '\\\\', $class), 'attributes' => array_merge($this->options['node.definition'], ['style' => $definition->isShared() ? 'filled' : 'dotted'])]; $container->setDefinition($id, new Definition('stdClass')); } foreach ($container->getServiceIds() as $id) { if (\array_key_exists($id, $container->getAliases())) { continue; } if (!$container->hasDefinition($id)) { $nodes[$id] = ['class' => str_replace('\\', '\\\\', \get_class($container->get($id))), 'attributes' => $this->options['node.instance']]; } } return $nodes; } private function cloneContainer() { $parameterBag = new ParameterBag($this->container->getParameterBag()->all()); $container = new ContainerBuilder($parameterBag); $container->setDefinitions($this->container->getDefinitions()); $container->setAliases($this->container->getAliases()); $container->setResources($this->container->getResources()); foreach ($this->container->getExtensions() as $extension) { $container->registerExtension($extension); } return $container; } /** * Returns the start dot. * * @return string The string representation of a start dot */ private function startDot() { return sprintf("digraph sc {\n %s\n node [%s];\n edge [%s];\n\n", $this->addOptions($this->options['graph']), $this->addOptions($this->options['node']), $this->addOptions($this->options['edge']) ); } /** * Returns the end dot. * * @return string */ private function endDot() { return "}\n"; } /** * Adds attributes. * * @param array $attributes An array of attributes * * @return string A comma separated list of attributes */ private function addAttributes(array $attributes) { $code = []; foreach ($attributes as $k => $v) { $code[] = sprintf('%s="%s"', $k, $v); } return $code ? ', '.implode(', ', $code) : ''; } /** * Adds options. * * @param array $options An array of options * * @return string A space separated list of options */ private function addOptions(array $options) { $code = []; foreach ($options as $k => $v) { $code[] = sprintf('%s="%s"', $k, $v); } return implode(' ', $code); } /** * Dotizes an identifier. * * @param string $id The identifier to dotize * * @return string A dotized string */ private function dotize($id) { return strtolower(preg_replace('/\W/i', '_', $id)); } /** * Compiles an array of aliases for a specified service id. * * @param string $id A service id * * @return array An array of aliases */ private function getAliases($id) { $aliases = []; foreach ($this->container->getAliases() as $alias => $origin) { if ($id == $origin) { $aliases[] = $alias; } } return $aliases; } } * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\DependencyInjection; /** * Reference represents a service reference. * * @author Fabien Potencier */ class Reference { private $id; private $invalidBehavior; /** * @param string $id The service identifier * @param int $invalidBehavior The behavior when the service does not exist * * @see Container */ public function __construct($id, $invalidBehavior = ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE) { $this->id = (string) $id; $this->invalidBehavior = $invalidBehavior; } /** * @return string The service identifier */ public function __toString() { return $this->id; } /** * Returns the behavior to be used when the service does not exist. * * @return int */ public function getInvalidBehavior() { return $this->invalidBehavior; } } * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\DependencyInjection\ParameterBag; use Symfony\Component\DependencyInjection\Exception\LogicException; /** * Holds read-only parameters. * * @author Fabien Potencier */ class FrozenParameterBag extends ParameterBag { /** * For performance reasons, the constructor assumes that * all keys are already lowercased. * * This is always the case when used internally. * * @param array $parameters An array of parameters */ public function __construct(array $parameters = []) { $this->parameters = $parameters; $this->resolved = true; } /** * {@inheritdoc} */ public function clear() { throw new LogicException('Impossible to call clear() on a frozen ParameterBag.'); } /** * {@inheritdoc} */ public function add(array $parameters) { throw new LogicException('Impossible to call add() on a frozen ParameterBag.'); } /** * {@inheritdoc} */ public function set($name, $value) { throw new LogicException('Impossible to call set() on a frozen ParameterBag.'); } /** * {@inheritdoc} */ public function remove($name) { throw new LogicException('Impossible to call remove() on a frozen ParameterBag.'); } } * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\DependencyInjection\ParameterBag; use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException; use Symfony\Component\DependencyInjection\Exception\RuntimeException; /** * @author Nicolas Grekas */ class EnvPlaceholderParameterBag extends ParameterBag { private $envPlaceholders = []; private $providedTypes = []; /** * {@inheritdoc} */ public function get($name) { if (0 === strpos($name, 'env(') && ')' === substr($name, -1) && 'env()' !== $name) { $env = substr($name, 4, -1); if (isset($this->envPlaceholders[$env])) { foreach ($this->envPlaceholders[$env] as $placeholder) { return $placeholder; // return first result } } if (!preg_match('/^(?:\w++:)*+\w++$/', $env)) { throw new InvalidArgumentException(sprintf('Invalid "%s" name: only "word" characters are allowed.', $name)); } if ($this->has($name)) { $defaultValue = parent::get($name); if (null !== $defaultValue && !is_scalar($defaultValue)) { throw new RuntimeException(sprintf('The default value of an env() parameter must be scalar or null, but "%s" given to "%s".', \gettype($defaultValue), $name)); } } $uniqueName = md5($name.uniqid(mt_rand(), true)); $placeholder = sprintf('env_%s_%s', str_replace(':', '_', $env), $uniqueName); $this->envPlaceholders[$env][$placeholder] = $placeholder; return $placeholder; } return parent::get($name); } /** * Returns the map of env vars used in the resolved parameter values to their placeholders. * * @return string[][] A map of env var names to their placeholders */ public function getEnvPlaceholders() { return $this->envPlaceholders; } /** * Merges the env placeholders of another EnvPlaceholderParameterBag. */ public function mergeEnvPlaceholders(self $bag) { if ($newPlaceholders = $bag->getEnvPlaceholders()) { $this->envPlaceholders += $newPlaceholders; foreach ($newPlaceholders as $env => $placeholders) { $this->envPlaceholders[$env] += $placeholders; } } } /** * Maps env prefixes to their corresponding PHP types. */ public function setProvidedTypes(array $providedTypes) { $this->providedTypes = $providedTypes; } /** * Gets the PHP types corresponding to env() parameter prefixes. * * @return string[][] */ public function getProvidedTypes() { return $this->providedTypes; } /** * {@inheritdoc} */ public function resolve() { if ($this->resolved) { return; } parent::resolve(); foreach ($this->envPlaceholders as $env => $placeholders) { if (!$this->has($name = "env($env)")) { continue; } if (is_numeric($default = $this->parameters[$name])) { $this->parameters[$name] = (string) $default; } elseif (null !== $default && !is_scalar($default)) { throw new RuntimeException(sprintf('The default value of env parameter "%s" must be scalar or null, "%s" given.', $env, \gettype($default))); } } } } * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\DependencyInjection\ParameterBag; use Symfony\Component\DependencyInjection\Exception\ParameterCircularReferenceException; use Symfony\Component\DependencyInjection\Exception\ParameterNotFoundException; use Symfony\Component\DependencyInjection\Exception\RuntimeException; /** * Holds parameters. * * @author Fabien Potencier */ class ParameterBag implements ParameterBagInterface { protected $parameters = []; protected $resolved = false; private $normalizedNames = []; /** * @param array $parameters An array of parameters */ public function __construct(array $parameters = []) { $this->add($parameters); } /** * Clears all parameters. */ public function clear() { $this->parameters = []; } /** * Adds parameters to the service container parameters. * * @param array $parameters An array of parameters */ public function add(array $parameters) { foreach ($parameters as $key => $value) { $this->set($key, $value); } } /** * {@inheritdoc} */ public function all() { return $this->parameters; } /** * {@inheritdoc} */ public function get($name) { $name = $this->normalizeName($name); if (!\array_key_exists($name, $this->parameters)) { if (!$name) { throw new ParameterNotFoundException($name); } $alternatives = []; foreach ($this->parameters as $key => $parameterValue) { $lev = levenshtein($name, $key); if ($lev <= \strlen($name) / 3 || false !== strpos($key, $name)) { $alternatives[] = $key; } } $nonNestedAlternative = null; if (!\count($alternatives) && false !== strpos($name, '.')) { $namePartsLength = array_map('strlen', explode('.', $name)); $key = substr($name, 0, -1 * (1 + array_pop($namePartsLength))); while (\count($namePartsLength)) { if ($this->has($key)) { if (\is_array($this->get($key))) { $nonNestedAlternative = $key; } break; } $key = substr($key, 0, -1 * (1 + array_pop($namePartsLength))); } } throw new ParameterNotFoundException($name, null, null, null, $alte