diff --git a/Alias.php b/Alias.php index 55e385f67..24484de16 100644 --- a/Alias.php +++ b/Alias.php @@ -21,7 +21,7 @@ public function __construct(string $id, bool $public = true) { $this->id = $id; $this->public = $public; - $this->private = 2 > func_num_args(); + $this->private = 2 > \func_num_args(); } /** diff --git a/Argument/BoundArgument.php b/Argument/BoundArgument.php index f72f21107..a20698440 100644 --- a/Argument/BoundArgument.php +++ b/Argument/BoundArgument.php @@ -33,7 +33,7 @@ public function __construct($value) */ public function getValues() { - return array($this->value, $this->identifier, $this->used); + return [$this->value, $this->identifier, $this->used]; } /** diff --git a/Argument/IteratorArgument.php b/Argument/IteratorArgument.php index ab3a87900..2d796d2d8 100644 --- a/Argument/IteratorArgument.php +++ b/Argument/IteratorArgument.php @@ -46,7 +46,7 @@ public function setValues(array $values) { foreach ($values as $k => $v) { if (null !== $v && !$v instanceof Reference) { - throw new InvalidArgumentException(sprintf('An IteratorArgument must hold only Reference instances, "%s" given.', is_object($v) ? get_class($v) : gettype($v))); + throw new InvalidArgumentException(sprintf('An IteratorArgument must hold only Reference instances, "%s" given.', \is_object($v) ? \get_class($v) : \gettype($v))); } } diff --git a/Argument/RewindableGenerator.php b/Argument/RewindableGenerator.php index e162a7c34..f8f771d62 100644 --- a/Argument/RewindableGenerator.php +++ b/Argument/RewindableGenerator.php @@ -38,7 +38,7 @@ public function getIterator() public function count() { - if (is_callable($count = $this->count)) { + if (\is_callable($count = $this->count)) { $this->count = $count(); } diff --git a/Argument/ServiceClosureArgument.php b/Argument/ServiceClosureArgument.php index 2fec5d26d..6331affa4 100644 --- a/Argument/ServiceClosureArgument.php +++ b/Argument/ServiceClosureArgument.php @@ -25,7 +25,7 @@ class ServiceClosureArgument implements ArgumentInterface public function __construct(Reference $reference) { - $this->values = array($reference); + $this->values = [$reference]; } /** @@ -41,7 +41,7 @@ public function getValues() */ public function setValues(array $values) { - if (array(0) !== array_keys($values) || !($values[0] instanceof Reference || null === $values[0])) { + if ([0] !== array_keys($values) || !($values[0] instanceof Reference || null === $values[0])) { throw new InvalidArgumentException('A ServiceClosureArgument must hold one and only one Reference.'); } diff --git a/Argument/TaggedIteratorArgument.php b/Argument/TaggedIteratorArgument.php index 3a6fab8b9..f3b3621d8 100644 --- a/Argument/TaggedIteratorArgument.php +++ b/Argument/TaggedIteratorArgument.php @@ -22,7 +22,7 @@ class TaggedIteratorArgument extends IteratorArgument public function __construct(string $tag) { - parent::__construct(array()); + parent::__construct([]); $this->tag = $tag; } diff --git a/ChildDefinition.php b/ChildDefinition.php index 0f67e960d..095beaec7 100644 --- a/ChildDefinition.php +++ b/ChildDefinition.php @@ -95,7 +95,7 @@ public function getArgument($index) */ public function replaceArgument($index, $value) { - if (is_int($index)) { + if (\is_int($index)) { $this->arguments['index_'.$index] = $value; } elseif (0 === strpos($index, '$')) { $this->arguments[$index] = $value; diff --git a/Compiler/AbstractRecursivePass.php b/Compiler/AbstractRecursivePass.php index 901dc06ff..cff09d57d 100644 --- a/Compiler/AbstractRecursivePass.php +++ b/Compiler/AbstractRecursivePass.php @@ -90,8 +90,8 @@ protected function processValue($value, $isRoot = false) */ protected function getConstructor(Definition $definition, $required) { - if (is_string($factory = $definition->getFactory())) { - if (!function_exists($factory)) { + if (\is_string($factory = $definition->getFactory())) { + if (!\function_exists($factory)) { throw new RuntimeException(sprintf('Invalid service "%s": function "%s" does not exist.', $this->currentId, $factory)); } $r = new \ReflectionFunction($factory); diff --git a/Compiler/AnalyzeServiceReferencesPass.php b/Compiler/AnalyzeServiceReferencesPass.php index a67d9b044..a9fb0758e 100644 --- a/Compiler/AnalyzeServiceReferencesPass.php +++ b/Compiler/AnalyzeServiceReferencesPass.php @@ -12,12 +12,12 @@ namespace Symfony\Component\DependencyInjection\Compiler; use Symfony\Component\DependencyInjection\Argument\ArgumentInterface; +use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\ContainerInterface; use Symfony\Component\DependencyInjection\Definition; use Symfony\Component\DependencyInjection\Exception\RuntimeException; use Symfony\Component\DependencyInjection\ExpressionLanguage; use Symfony\Component\DependencyInjection\Reference; -use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\ExpressionLanguage\Expression; /** @@ -34,15 +34,18 @@ class AnalyzeServiceReferencesPass extends AbstractRecursivePass implements Repe private $graph; private $currentDefinition; private $onlyConstructorArguments; + private $hasProxyDumper; private $lazy; private $expressionLanguage; + private $byConstructor; /** * @param bool $onlyConstructorArguments Sets this Service Reference pass to ignore method calls */ - public function __construct(bool $onlyConstructorArguments = false) + public function __construct(bool $onlyConstructorArguments = false, bool $hasProxyDumper = true) { $this->onlyConstructorArguments = $onlyConstructorArguments; + $this->hasProxyDumper = $hasProxyDumper; } /** @@ -62,6 +65,7 @@ public function process(ContainerBuilder $container) $this->graph = $container->getCompiler()->getServiceReferenceGraph(); $this->graph->clear(); $this->lazy = false; + $this->byConstructor = false; foreach ($container->getAliases() as $id => $alias) { $targetId = $this->getDefinitionId((string) $alias); @@ -83,7 +87,7 @@ protected function processValue($value, $isRoot = false) return $value; } if ($value instanceof Expression) { - $this->getExpressionLanguage()->compile((string) $value, array('this' => 'container')); + $this->getExpressionLanguage()->compile((string) $value, ['this' => 'container']); return $value; } @@ -97,8 +101,9 @@ protected function processValue($value, $isRoot = false) $targetId, $targetDefinition, $value, - $this->lazy || ($targetDefinition && $targetDefinition->isLazy()), - ContainerInterface::IGNORE_ON_UNINITIALIZED_REFERENCE === $value->getInvalidBehavior() + $this->lazy || ($this->hasProxyDumper && $targetDefinition && $targetDefinition->isLazy()), + ContainerInterface::IGNORE_ON_UNINITIALIZED_REFERENCE === $value->getInvalidBehavior(), + $this->byConstructor ); return $value; @@ -111,11 +116,16 @@ protected function processValue($value, $isRoot = false) return $value; } $this->currentDefinition = $value; + } elseif ($this->currentDefinition === $value) { + return $value; } $this->lazy = false; + $byConstructor = $this->byConstructor; + $this->byConstructor = true; $this->processValue($value->getFactory()); $this->processValue($value->getArguments()); + $this->byConstructor = $byConstructor; if (!$this->onlyConstructorArguments) { $this->processValue($value->getProperties()); diff --git a/Compiler/AutowirePass.php b/Compiler/AutowirePass.php index 0fece9802..4f44855d3 100644 --- a/Compiler/AutowirePass.php +++ b/Compiler/AutowirePass.php @@ -117,7 +117,7 @@ private function doProcessValue($value, $isRoot = false) } if ($constructor) { - array_unshift($this->methodCalls, array($constructor, $value->getArguments())); + array_unshift($this->methodCalls, [$constructor, $value->getArguments()]); } $this->methodCalls = $this->autowireCalls($reflectionClass, $isRoot); @@ -144,11 +144,12 @@ private function doProcessValue($value, $isRoot = false) */ private function autowireCalls(\ReflectionClass $reflectionClass, bool $isRoot): array { + $this->decoratedId = null; + $this->decoratedClass = null; + $this->getPreviousValue = null; + if ($isRoot && ($definition = $this->container->getDefinition($this->currentId)) && $this->container->has($this->decoratedId = $definition->innerServiceId)) { $this->decoratedClass = $this->container->findDefinition($this->decoratedId)->getClass(); - } else { - $this->decoratedId = null; - $this->decoratedClass = null; } foreach ($this->methodCalls as $i => $call) { @@ -290,8 +291,8 @@ private function getAutowiredReference(TypedReference $reference) */ private function populateAvailableTypes() { - $this->types = array(); - $this->ambiguousServiceTypes = array(); + $this->types = []; + $this->ambiguousServiceTypes = []; foreach ($this->container->getDefinitions() as $id => $definition) { $this->populateAvailableType($id, $definition); @@ -342,7 +343,7 @@ private function set(string $type, string $id) // keep an array of all services matching this type if (!isset($this->ambiguousServiceTypes[$type])) { - $this->ambiguousServiceTypes[$type] = array($this->types[$type]); + $this->ambiguousServiceTypes[$type] = [$this->types[$type]]; unset($this->types[$type]); } $this->ambiguousServiceTypes[$type][] = $id; @@ -350,7 +351,17 @@ private function set(string $type, string $id) private function createTypeNotFoundMessage(TypedReference $reference, $label) { - if (!$r = $this->container->getReflectionClass($type = $reference->getType(), false)) { + $trackResources = $this->container->isTrackingResources(); + $this->container->setResourceTracking(false); + try { + if ($r = $this->container->getReflectionClass($type = $reference->getType(), false)) { + $alternatives = $this->createTypeAlternatives($reference); + } + } finally { + $this->container->setResourceTracking($trackResources); + } + + if (!$r) { // either $type does not exist or a parent class does not exist try { $resource = new ClassExistenceResource($type, false); @@ -363,7 +374,6 @@ private function createTypeNotFoundMessage(TypedReference $reference, $label) $message = sprintf('has type "%s" but this class %s.', $type, $parentMsg ? sprintf('is missing a parent class (%s)', $parentMsg) : 'was not found'); } else { - $alternatives = $this->createTypeAlternatives($reference); $message = $this->container->has($type) ? 'this service is abstract' : 'no such service exists'; $message = sprintf('references %s "%s" but %s.%s', $r->isInterface() ? 'interface' : 'class', $type, $message, $alternatives); @@ -408,7 +418,7 @@ private function createTypeAlternatives(TypedReference $reference) private function getAliasesSuggestionForType($type, $extraContext = null) { - $aliases = array(); + $aliases = []; foreach (class_parents($type) + class_implements($type) as $parent) { if ($this->container->has($parent) && !$this->container->findDefinition($parent)->isAbstract()) { $aliases[] = $parent; @@ -416,7 +426,7 @@ private function getAliasesSuggestionForType($type, $extraContext = null) } $extraContext = $extraContext ? ' '.$extraContext : ''; - if (1 < $len = count($aliases)) { + if (1 < $len = \count($aliases)) { $message = sprintf('Try changing the type-hint%s to one of its parents: ', $extraContext); for ($i = 0, --$len; $i < $len; ++$i) { $message .= sprintf('%s "%s", ', class_exists($aliases[$i], false) ? 'class' : 'interface', $aliases[$i]); diff --git a/Compiler/AutowireRequiredMethodsPass.php b/Compiler/AutowireRequiredMethodsPass.php index 6c744f88f..efb9df7b9 100644 --- a/Compiler/AutowireRequiredMethodsPass.php +++ b/Compiler/AutowireRequiredMethodsPass.php @@ -34,7 +34,7 @@ protected function processValue($value, $isRoot = false) return $value; } - $alreadyCalledMethods = array(); + $alreadyCalledMethods = []; foreach ($value->getMethodCalls() as list($method)) { $alreadyCalledMethods[strtolower($method)] = true; diff --git a/Compiler/CheckArgumentsValidityPass.php b/Compiler/CheckArgumentsValidityPass.php index 6e5e9042c..e76e94005 100644 --- a/Compiler/CheckArgumentsValidityPass.php +++ b/Compiler/CheckArgumentsValidityPass.php @@ -41,7 +41,7 @@ protected function processValue($value, $isRoot = false) $i = 0; foreach ($value->getArguments() as $k => $v) { if ($k !== $i++) { - if (!is_int($k)) { + if (!\is_int($k)) { $msg = sprintf('Invalid constructor argument for service "%s": integer expected but found string "%s". Check your service definition.', $this->currentId, $k); $value->addError($msg); if ($this->throwExceptions) { @@ -63,7 +63,7 @@ protected function processValue($value, $isRoot = false) $i = 0; foreach ($methodCall[1] as $k => $v) { if ($k !== $i++) { - if (!is_int($k)) { + if (!\is_int($k)) { $msg = sprintf('Invalid argument for method call "%s" of service "%s": integer expected but found string "%s". Check your service definition.', $methodCall[0], $this->currentId, $k); $value->addError($msg); if ($this->throwExceptions) { diff --git a/Compiler/CheckCircularReferencesPass.php b/Compiler/CheckCircularReferencesPass.php index 6191893e0..55d911c4f 100644 --- a/Compiler/CheckCircularReferencesPass.php +++ b/Compiler/CheckCircularReferencesPass.php @@ -11,8 +11,8 @@ namespace Symfony\Component\DependencyInjection\Compiler; -use Symfony\Component\DependencyInjection\Exception\ServiceCircularReferenceException; use Symfony\Component\DependencyInjection\ContainerBuilder; +use Symfony\Component\DependencyInjection\Exception\ServiceCircularReferenceException; /** * Checks your services for circular references. @@ -36,9 +36,9 @@ public function process(ContainerBuilder $container) { $graph = $container->getCompiler()->getServiceReferenceGraph(); - $this->checkedNodes = array(); + $this->checkedNodes = []; foreach ($graph->getNodes() as $id => $node) { - $this->currentPath = array($id); + $this->currentPath = [$id]; $this->checkOutEdges($node->getOutEdges()); } @@ -64,7 +64,7 @@ private function checkOutEdges(array $edges) $this->currentPath[] = $id; if (false !== $searchKey) { - throw new ServiceCircularReferenceException($id, array_slice($this->currentPath, $searchKey)); + throw new ServiceCircularReferenceException($id, \array_slice($this->currentPath, $searchKey)); } $this->checkOutEdges($node->getOutEdges()); diff --git a/Compiler/CheckDefinitionValidityPass.php b/Compiler/CheckDefinitionValidityPass.php index ba6356f4a..39b183fe6 100644 --- a/Compiler/CheckDefinitionValidityPass.php +++ b/Compiler/CheckDefinitionValidityPass.php @@ -48,6 +48,15 @@ public function process(ContainerBuilder $container) throw new RuntimeException(sprintf('Please add the class to service "%s" even if it is constructed by a factory since we might need to add method calls based on compile-time checks.', $id)); } if (class_exists($id) || interface_exists($id, false)) { + if (0 === strpos($id, '\\') && 1 < substr_count($id, '\\')) { + throw new RuntimeException(sprintf( + 'The definition for "%s" has no class attribute, and appears to reference a class or interface. ' + .'Please specify the class attribute explicitly or remove the leading backslash by renaming ' + .'the service to "%s" to get rid of this error.', + $id, substr($id, 1) + )); + } + throw new RuntimeException(sprintf( 'The definition for "%s" has no class attribute, and appears to reference a ' .'class or interface in the global namespace. Leaving out the "class" attribute ' @@ -57,13 +66,7 @@ public function process(ContainerBuilder $container) )); } - throw new RuntimeException(sprintf( - 'The definition for "%s" has no class. If you intend to inject ' - .'this service dynamically at runtime, please mark it as synthetic=true. ' - .'If this is an abstract definition solely used by child definitions, ' - .'please add abstract=true, otherwise specify a class to get rid of this error.', - $id - )); + throw new RuntimeException(sprintf('The definition for "%s" has no class. If you intend to inject this service dynamically at runtime, please mark it as synthetic=true. If this is an abstract definition solely used by child definitions, please add abstract=true, otherwise specify a class to get rid of this error.', $id)); } // tag attribute values must be scalars @@ -80,7 +83,7 @@ public function process(ContainerBuilder $container) if ($definition->isPublic() && !$definition->isPrivate()) { $resolvedId = $container->resolveEnvPlaceholders($id, null, $usedEnvs); if (null !== $usedEnvs) { - throw new EnvParameterException(array($resolvedId), null, 'A service name ("%s") cannot contain dynamic values.'); + throw new EnvParameterException([$resolvedId], null, 'A service name ("%s") cannot contain dynamic values.'); } } } @@ -89,7 +92,7 @@ public function process(ContainerBuilder $container) if ($alias->isPublic() && !$alias->isPrivate()) { $resolvedId = $container->resolveEnvPlaceholders($id, null, $usedEnvs); if (null !== $usedEnvs) { - throw new EnvParameterException(array($resolvedId), null, 'An alias name ("%s") cannot contain dynamic values.'); + throw new EnvParameterException([$resolvedId], null, 'An alias name ("%s") cannot contain dynamic values.'); } } } diff --git a/Compiler/CheckExceptionOnInvalidReferenceBehaviorPass.php b/Compiler/CheckExceptionOnInvalidReferenceBehaviorPass.php index b13f2bdc5..1ce18f651 100644 --- a/Compiler/CheckExceptionOnInvalidReferenceBehaviorPass.php +++ b/Compiler/CheckExceptionOnInvalidReferenceBehaviorPass.php @@ -11,8 +11,8 @@ namespace Symfony\Component\DependencyInjection\Compiler; -use Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException; use Symfony\Component\DependencyInjection\ContainerInterface; +use Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException; use Symfony\Component\DependencyInjection\Reference; /** diff --git a/Compiler/CheckReferenceValidityPass.php b/Compiler/CheckReferenceValidityPass.php index 72c7dd165..8f2a3bdf7 100644 --- a/Compiler/CheckReferenceValidityPass.php +++ b/Compiler/CheckReferenceValidityPass.php @@ -12,8 +12,8 @@ namespace Symfony\Component\DependencyInjection\Compiler; use Symfony\Component\DependencyInjection\Definition; -use Symfony\Component\DependencyInjection\Reference; use Symfony\Component\DependencyInjection\Exception\RuntimeException; +use Symfony\Component\DependencyInjection\Reference; /** * Checks the validity of references. @@ -34,12 +34,7 @@ protected function processValue($value, $isRoot = false) $targetDefinition = $this->container->getDefinition((string) $value); if ($targetDefinition->isAbstract()) { - throw new RuntimeException(sprintf( - 'The definition "%s" has a reference to an abstract definition "%s". ' - .'Abstract definitions cannot be the target of references.', - $this->currentId, - $value - )); + throw new RuntimeException(sprintf('The definition "%s" has a reference to an abstract definition "%s". Abstract definitions cannot be the target of references.', $this->currentId, $value)); } } diff --git a/Compiler/Compiler.php b/Compiler/Compiler.php index 7c797a92b..58c6e81a0 100644 --- a/Compiler/Compiler.php +++ b/Compiler/Compiler.php @@ -22,7 +22,7 @@ class Compiler { private $passConfig; - private $log = array(); + private $log = []; private $serviceReferenceGraph; public function __construct() @@ -69,10 +69,10 @@ public function addPass(CompilerPassInterface $pass, $type = PassConfig::TYPE_BE public function log(CompilerPassInterface $pass, string $message) { if (false !== strpos($message, "\n")) { - $message = str_replace("\n", "\n".get_class($pass).': ', trim($message)); + $message = str_replace("\n", "\n".\get_class($pass).': ', trim($message)); } - $this->log[] = get_class($pass).': '.$message; + $this->log[] = \get_class($pass).': '.$message; } /** @@ -95,7 +95,7 @@ public function compile(ContainerBuilder $container) $pass->process($container); } } catch (\Exception $e) { - $usedEnvs = array(); + $usedEnvs = []; $prev = $e; do { diff --git a/Compiler/DecoratorServicePass.php b/Compiler/DecoratorServicePass.php index c9cde471b..f49e8cf94 100644 --- a/Compiler/DecoratorServicePass.php +++ b/Compiler/DecoratorServicePass.php @@ -11,8 +11,8 @@ namespace Symfony\Component\DependencyInjection\Compiler; -use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Alias; +use Symfony\Component\DependencyInjection\ContainerBuilder; /** * Overwrites a service but keeps the overridden one. @@ -32,8 +32,9 @@ public function process(ContainerBuilder $container) if (!$decorated = $definition->getDecoratedService()) { continue; } - $definitions->insert(array($id, $definition), array($decorated[2], --$order)); + $definitions->insert([$id, $definition], [$decorated[2], --$order]); } + $decoratingDefinitions = []; foreach ($definitions as list($id, $definition)) { list($inner, $renamedId) = $definition->getDecoratedService(); @@ -54,12 +55,18 @@ public function process(ContainerBuilder $container) $container->setAlias($renamedId, new Alias((string) $alias, false)); } else { $decoratedDefinition = $container->getDefinition($inner); - $definition->setTags(array_merge($decoratedDefinition->getTags(), $definition->getTags())); $public = $decoratedDefinition->isPublic(); $private = $decoratedDefinition->isPrivate(); $decoratedDefinition->setPublic(false); - $decoratedDefinition->setTags(array()); $container->setDefinition($renamedId, $decoratedDefinition); + $decoratingDefinitions[$inner] = $decoratedDefinition; + } + + if (isset($decoratingDefinitions[$inner])) { + $decoratingDefinition = $decoratingDefinitions[$inner]; + $definition->setTags(array_merge($decoratingDefinition->getTags(), $definition->getTags())); + $decoratingDefinition->setTags([]); + $decoratingDefinitions[$inner] = $definition; } $container->setAlias($inner, $id)->setPublic($public)->setPrivate($private); diff --git a/Compiler/InlineServiceDefinitionsPass.php b/Compiler/InlineServiceDefinitionsPass.php index 12b679880..cac12648a 100644 --- a/Compiler/InlineServiceDefinitionsPass.php +++ b/Compiler/InlineServiceDefinitionsPass.php @@ -23,7 +23,7 @@ */ class InlineServiceDefinitionsPass extends AbstractRecursivePass implements RepeatablePassInterface { - private $cloningIds = array(); + private $cloningIds = []; /** * {@inheritdoc} @@ -70,7 +70,7 @@ protected function processValue($value, $isRoot = false) $ids = array_keys($this->cloningIds); $ids[] = $id; - throw new ServiceCircularReferenceException($id, array_slice($ids, array_search($id, $ids))); + throw new ServiceCircularReferenceException($id, \array_slice($ids, array_search($id, $ids))); } $this->cloningIds[$id] = true; @@ -93,8 +93,12 @@ private function isInlineableDefinition($id, Definition $definition, ServiceRefe } if (!$definition->isShared()) { + if (!$graph->hasNode($id)) { + return true; + } + foreach ($graph->getNode($id)->getInEdges() as $edge) { - if ($edge->isWeak()) { + if ($edge->isWeak() || $edge->isLazy()) { return false; } } @@ -114,22 +118,32 @@ private function isInlineableDefinition($id, Definition $definition, ServiceRefe return false; } - $ids = array(); + $ids = []; + $isReferencedByConstructor = false; foreach ($graph->getNode($id)->getInEdges() as $edge) { - if ($edge->isWeak()) { + $isReferencedByConstructor = $isReferencedByConstructor || $edge->isReferencedByConstructor(); + if ($edge->isWeak() || $edge->isLazy()) { return false; } $ids[] = $edge->getSourceNode()->getId(); } - if (count(array_unique($ids)) > 1) { + if (!$ids) { + return true; + } + + if (\count(array_unique($ids)) > 1) { + return false; + } + + if (\count($ids) > 1 && \is_array($factory = $definition->getFactory()) && ($factory[0] instanceof Reference || $factory[0] instanceof Definition)) { return false; } - if (count($ids) > 1 && is_array($factory = $definition->getFactory()) && ($factory[0] instanceof Reference || $factory[0] instanceof Definition)) { + if ($isReferencedByConstructor && $this->container->getDefinition($ids[0])->isLazy() && ($definition->getProperties() || $definition->getMethodCalls() || $definition->getConfigurator())) { return false; } - return !$ids || $this->container->getDefinition($ids[0])->isShared(); + return $this->container->getDefinition($ids[0])->isShared(); } } diff --git a/Compiler/MergeExtensionConfigurationPass.php b/Compiler/MergeExtensionConfigurationPass.php index 5312b4d46..822dfe795 100644 --- a/Compiler/MergeExtensionConfigurationPass.php +++ b/Compiler/MergeExtensionConfigurationPass.php @@ -119,7 +119,7 @@ public function freezeAfterProcessing(Extension $extension, ContainerBuilder $co // Extension::processConfiguration() wasn't called, we cannot know how configs were merged return; } - $this->processedEnvPlaceholders = array(); + $this->processedEnvPlaceholders = []; // serialize config and container to catch env vars nested in object graphs $config = serialize($config).serialize($container->getDefinitions()).serialize($container->getAliases()).serialize($container->getParameterBag()->all()); @@ -144,7 +144,7 @@ public function getEnvPlaceholders() public function getUnusedEnvPlaceholders(): array { - return null === $this->processedEnvPlaceholders ? array() : array_diff_key(parent::getEnvPlaceholders(), $this->processedEnvPlaceholders); + return null === $this->processedEnvPlaceholders ? [] : array_diff_key(parent::getEnvPlaceholders(), $this->processedEnvPlaceholders); } } @@ -161,7 +161,7 @@ public function __construct(ExtensionInterface $extension, ParameterBagInterface { parent::__construct($parameterBag); - $this->extensionClass = get_class($extension); + $this->extensionClass = \get_class($extension); } /** @@ -169,7 +169,7 @@ public function __construct(ExtensionInterface $extension, ParameterBagInterface */ public function addCompilerPass(CompilerPassInterface $pass, $type = PassConfig::TYPE_BEFORE_OPTIMIZATION, int $priority = 0) { - throw new LogicException(sprintf('You cannot add compiler pass "%s" from extension "%s". Compiler passes must be registered before the container is compiled.', get_class($pass), $this->extensionClass)); + throw new LogicException(sprintf('You cannot add compiler pass "%s" from extension "%s". Compiler passes must be registered before the container is compiled.', \get_class($pass), $this->extensionClass)); } /** @@ -177,7 +177,7 @@ public function addCompilerPass(CompilerPassInterface $pass, $type = PassConfig: */ public function registerExtension(ExtensionInterface $extension) { - throw new LogicException(sprintf('You cannot register extension "%s" from "%s". Extensions must be registered before the container is compiled.', get_class($extension), $this->extensionClass)); + throw new LogicException(sprintf('You cannot register extension "%s" from "%s". Extensions must be registered before the container is compiled.', \get_class($extension), $this->extensionClass)); } /** diff --git a/Compiler/PassConfig.php b/Compiler/PassConfig.php index 170a0edc8..76c864b05 100644 --- a/Compiler/PassConfig.php +++ b/Compiler/PassConfig.php @@ -29,9 +29,9 @@ class PassConfig const TYPE_REMOVE = 'removing'; private $mergePass; - private $afterRemovingPasses = array(); - private $beforeOptimizationPasses = array(); - private $beforeRemovingPasses = array(); + private $afterRemovingPasses = []; + private $beforeOptimizationPasses = []; + private $beforeRemovingPasses = []; private $optimizationPasses; private $removingPasses; @@ -39,24 +39,24 @@ public function __construct() { $this->mergePass = new MergeExtensionConfigurationPass(); - $this->beforeOptimizationPasses = array( - 100 => array( + $this->beforeOptimizationPasses = [ + 100 => [ new ResolveClassPass(), new ResolveInstanceofConditionalsPass(), new RegisterEnvVarProcessorsPass(), - ), - -1000 => array(new ExtensionCompilerPass()), - ); + ], + -1000 => [new ExtensionCompilerPass()], + ]; - $this->optimizationPasses = array(array( + $this->optimizationPasses = [[ new ValidateEnvPlaceholdersPass(), new ResolveChildDefinitionsPass(), new ServiceLocatorTagPass(), + new RegisterServiceSubscribersPass(), new DecoratorServicePass(), new ResolveParameterPlaceHoldersPass(false), new ResolveFactoryClassPass(), new CheckDefinitionValidityPass(), - new RegisterServiceSubscribersPass(), new ResolveNamedArgumentsPass(), new AutowireRequiredMethodsPass(), new ResolveBindingsPass(), @@ -69,28 +69,28 @@ public function __construct() new CheckCircularReferencesPass(), new CheckReferenceValidityPass(), new CheckArgumentsValidityPass(false), - )); + ]]; - $this->beforeRemovingPasses = array( - -100 => array( + $this->beforeRemovingPasses = [ + -100 => [ new ResolvePrivatesPass(), - ), - ); + ], + ]; - $this->removingPasses = array(array( + $this->removingPasses = [[ new RemovePrivateAliasesPass(), new ReplaceAliasByActualDefinitionPass(), new RemoveAbstractDefinitionsPass(), - new RepeatedPass(array( + new RepeatedPass([ new AnalyzeServiceReferencesPass(), new InlineServiceDefinitionsPass(), new AnalyzeServiceReferencesPass(), new RemoveUnusedDefinitionsPass(), - )), + ]), new DefinitionErrorExceptionPass(), new CheckExceptionOnInvalidReferenceBehaviorPass(), new ResolveHotPathPass(), - )); + ]]; } /** @@ -101,7 +101,7 @@ public function __construct() public function getPasses() { return array_merge( - array($this->mergePass), + [$this->mergePass], $this->getBeforeOptimizationPasses(), $this->getOptimizationPasses(), $this->getBeforeRemovingPasses(), @@ -129,7 +129,7 @@ public function addPass(CompilerPassInterface $pass, $type = self::TYPE_BEFORE_O $passes = &$this->$property; if (!isset($passes[$priority])) { - $passes[$priority] = array(); + $passes[$priority] = []; } $passes[$priority][] = $pass; } @@ -206,7 +206,7 @@ public function setMergePass(CompilerPassInterface $pass) */ public function setAfterRemovingPasses(array $passes) { - $this->afterRemovingPasses = array($passes); + $this->afterRemovingPasses = [$passes]; } /** @@ -216,7 +216,7 @@ public function setAfterRemovingPasses(array $passes) */ public function setBeforeOptimizationPasses(array $passes) { - $this->beforeOptimizationPasses = array($passes); + $this->beforeOptimizationPasses = [$passes]; } /** @@ -226,7 +226,7 @@ public function setBeforeOptimizationPasses(array $passes) */ public function setBeforeRemovingPasses(array $passes) { - $this->beforeRemovingPasses = array($passes); + $this->beforeRemovingPasses = [$passes]; } /** @@ -236,7 +236,7 @@ public function setBeforeRemovingPasses(array $passes) */ public function setOptimizationPasses(array $passes) { - $this->optimizationPasses = array($passes); + $this->optimizationPasses = [$passes]; } /** @@ -246,7 +246,7 @@ public function setOptimizationPasses(array $passes) */ public function setRemovingPasses(array $passes) { - $this->removingPasses = array($passes); + $this->removingPasses = [$passes]; } /** @@ -259,7 +259,7 @@ public function setRemovingPasses(array $passes) private function sortPasses(array $passes) { if (0 === \count($passes)) { - return array(); + return []; } krsort($passes); diff --git a/Compiler/PriorityTaggedServiceTrait.php b/Compiler/PriorityTaggedServiceTrait.php index 4f440af7f..adb99f0d5 100644 --- a/Compiler/PriorityTaggedServiceTrait.php +++ b/Compiler/PriorityTaggedServiceTrait.php @@ -38,7 +38,7 @@ trait PriorityTaggedServiceTrait */ private function findAndSortTaggedServices($tagName, ContainerBuilder $container) { - $services = array(); + $services = []; foreach ($container->findTaggedServiceIds($tagName, true) as $serviceId => $attributes) { $priority = isset($attributes[0]['priority']) ? $attributes[0]['priority'] : 0; diff --git a/Compiler/RegisterEnvVarProcessorsPass.php b/Compiler/RegisterEnvVarProcessorsPass.php index b99c252fe..b4d0d0550 100644 --- a/Compiler/RegisterEnvVarProcessorsPass.php +++ b/Compiler/RegisterEnvVarProcessorsPass.php @@ -17,8 +17,8 @@ use Symfony\Component\DependencyInjection\EnvVarProcessorInterface; use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException; use Symfony\Component\DependencyInjection\ParameterBag\EnvPlaceholderParameterBag; -use Symfony\Component\DependencyInjection\ServiceLocator; use Symfony\Component\DependencyInjection\Reference; +use Symfony\Component\DependencyInjection\ServiceLocator; /** * Creates the container.env_var_processors_locator service. @@ -27,13 +27,13 @@ */ class RegisterEnvVarProcessorsPass implements CompilerPassInterface { - private static $allowedTypes = array('array', 'bool', 'float', 'int', 'string'); + private static $allowedTypes = ['array', 'bool', 'float', 'int', 'string']; public function process(ContainerBuilder $container) { $bag = $container->getParameterBag(); - $types = array(); - $processors = array(); + $types = []; + $processors = []; foreach ($container->findTaggedServiceIds('container.env_var_processor') as $id => $tags) { if (!$r = $container->getReflectionClass($class = $container->getDefinition($id)->getClass())) { throw new InvalidArgumentException(sprintf('Class "%s" used for service "%s" cannot be found.', $class, $id)); @@ -58,7 +58,7 @@ public function process(ContainerBuilder $container) if ($processors) { $container->register('container.env_var_processors_locator', ServiceLocator::class) ->setPublic(true) - ->setArguments(array($processors)) + ->setArguments([$processors]) ; } } @@ -68,7 +68,7 @@ private static function validateProvidedTypes($types, $class) $types = explode('|', $types); foreach ($types as $type) { - if (!in_array($type, self::$allowedTypes)) { + if (!\in_array($type, self::$allowedTypes)) { throw new InvalidArgumentException(sprintf('Invalid type "%s" returned by "%s::getProvidedTypes()", expected one of "%s".', $type, $class, implode('", "', self::$allowedTypes))); } } diff --git a/Compiler/RegisterServiceSubscribersPass.php b/Compiler/RegisterServiceSubscribersPass.php index 87b4eac16..150952ca5 100644 --- a/Compiler/RegisterServiceSubscribersPass.php +++ b/Compiler/RegisterServiceSubscribersPass.php @@ -31,7 +31,7 @@ protected function processValue($value, $isRoot = false) return parent::processValue($value, $isRoot); } - $serviceMap = array(); + $serviceMap = []; $autowire = $value->isAutowired(); foreach ($value->getTag('container.service_subscriber') as $attributes) { @@ -40,7 +40,7 @@ protected function processValue($value, $isRoot = false) continue; } ksort($attributes); - if (array() !== array_diff(array_keys($attributes), array('id', 'key'))) { + if ([] !== array_diff(array_keys($attributes), ['id', 'key'])) { throw new InvalidArgumentException(sprintf('The "container.service_subscriber" tag accepts only the "key" and "id" attributes, "%s" given for service "%s".', implode('", "', array_keys($attributes)), $this->currentId)); } if (!array_key_exists('id', $attributes)) { @@ -64,17 +64,17 @@ protected function processValue($value, $isRoot = false) } $class = $r->name; - $subscriberMap = array(); + $subscriberMap = []; foreach ($class::getSubscribedServices() as $key => $type) { - if (!is_string($type) || !preg_match('/^\??[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*+(?:\\\\[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*+)*+$/', $type)) { - throw new InvalidArgumentException(sprintf('"%s::getSubscribedServices()" must return valid PHP types for service "%s" key "%s", "%s" returned.', $class, $this->currentId, $key, is_string($type) ? $type : gettype($type))); + if (!\is_string($type) || !preg_match('/^\??[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*+(?:\\\\[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*+)*+$/', $type)) { + throw new InvalidArgumentException(sprintf('"%s::getSubscribedServices()" must return valid PHP types for service "%s" key "%s", "%s" returned.', $class, $this->currentId, $key, \is_string($type) ? $type : \gettype($type))); } if ($optionalBehavior = '?' === $type[0]) { $type = substr($type, 1); $optionalBehavior = ContainerInterface::IGNORE_ON_INVALID_REFERENCE; } - if (is_int($key)) { + if (\is_int($key)) { $key = $type; } if (!isset($serviceMap[$key])) { @@ -89,11 +89,11 @@ protected function processValue($value, $isRoot = false) } if ($serviceMap = array_keys($serviceMap)) { - $message = sprintf(1 < count($serviceMap) ? 'keys "%s" do' : 'key "%s" does', str_replace('%', '%%', implode('", "', $serviceMap))); + $message = sprintf(1 < \count($serviceMap) ? 'keys "%s" do' : 'key "%s" does', str_replace('%', '%%', implode('", "', $serviceMap))); throw new InvalidArgumentException(sprintf('Service %s not exist in the map returned by "%s::getSubscribedServices()" for service "%s".', $message, $class, $this->currentId)); } - $value->addTag('container.service_subscriber.locator', array('id' => (string) ServiceLocatorTagPass::register($this->container, $subscriberMap, $this->currentId))); + $value->addTag('container.service_subscriber.locator', ['id' => (string) ServiceLocatorTagPass::register($this->container, $subscriberMap, $this->currentId)]); return parent::processValue($value); } diff --git a/Compiler/RemoveUnusedDefinitionsPass.php b/Compiler/RemoveUnusedDefinitionsPass.php index ec2eed27e..9cb2d0090 100644 --- a/Compiler/RemoveUnusedDefinitionsPass.php +++ b/Compiler/RemoveUnusedDefinitionsPass.php @@ -45,8 +45,8 @@ public function process(ContainerBuilder $container) if ($graph->hasNode($id)) { $edges = $graph->getNode($id)->getInEdges(); - $referencingAliases = array(); - $sourceIds = array(); + $referencingAliases = []; + $sourceIds = []; foreach ($edges as $edge) { if ($edge->isWeak()) { continue; @@ -58,19 +58,19 @@ public function process(ContainerBuilder $container) $referencingAliases[] = $node->getValue(); } } - $isReferenced = (count(array_unique($sourceIds)) - count($referencingAliases)) > 0; + $isReferenced = (\count(array_unique($sourceIds)) - \count($referencingAliases)) > 0; } else { - $referencingAliases = array(); + $referencingAliases = []; $isReferenced = false; } - if (1 === count($referencingAliases) && false === $isReferenced) { + if (1 === \count($referencingAliases) && false === $isReferenced) { $container->setDefinition((string) reset($referencingAliases), $definition); $definition->setPublic(!$definition->isPrivate()); $definition->setPrivate(reset($referencingAliases)->isPrivate()); $container->removeDefinition($id); $container->log($this, sprintf('Removed service "%s"; reason: replaces alias %s.', $id, reset($referencingAliases))); - } elseif (0 === count($referencingAliases) && false === $isReferenced) { + } elseif (0 === \count($referencingAliases) && false === $isReferenced) { $container->removeDefinition($id); $container->resolveEnvPlaceholders(serialize($definition)); $container->log($this, sprintf('Removed service "%s"; reason: unused.', $id)); diff --git a/Compiler/ReplaceAliasByActualDefinitionPass.php b/Compiler/ReplaceAliasByActualDefinitionPass.php index 9a27b371b..d599e11ed 100644 --- a/Compiler/ReplaceAliasByActualDefinitionPass.php +++ b/Compiler/ReplaceAliasByActualDefinitionPass.php @@ -33,8 +33,8 @@ class ReplaceAliasByActualDefinitionPass extends AbstractRecursivePass public function process(ContainerBuilder $container) { // First collect all alias targets that need to be replaced - $seenAliasTargets = array(); - $replacements = array(); + $seenAliasTargets = []; + $replacements = []; foreach ($container->getAliases() as $definitionId => $target) { $targetId = (string) $target; // Special case: leave this target alone @@ -69,7 +69,7 @@ public function process(ContainerBuilder $container) $this->replacements = $replacements; parent::process($container); - $this->replacements = array(); + $this->replacements = []; } /** diff --git a/Compiler/ResolveBindingsPass.php b/Compiler/ResolveBindingsPass.php index 0051fb5ac..6023ad4bd 100644 --- a/Compiler/ResolveBindingsPass.php +++ b/Compiler/ResolveBindingsPass.php @@ -17,17 +17,17 @@ use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException; use Symfony\Component\DependencyInjection\Exception\RuntimeException; use Symfony\Component\DependencyInjection\LazyProxy\ProxyHelper; -use Symfony\Component\DependencyInjection\TypedReference; use Symfony\Component\DependencyInjection\Reference; +use Symfony\Component\DependencyInjection\TypedReference; /** * @author Guilhem Niot */ class ResolveBindingsPass extends AbstractRecursivePass { - private $usedBindings = array(); - private $unusedBindings = array(); - private $errorMessages = array(); + private $usedBindings = []; + private $unusedBindings = []; + private $errorMessages = []; /** * {@inheritdoc} @@ -48,9 +48,9 @@ public function process(ContainerBuilder $container) throw new InvalidArgumentException($message); } } finally { - $this->usedBindings = array(); - $this->unusedBindings = array(); - $this->errorMessages = array(); + $this->usedBindings = []; + $this->unusedBindings = []; + $this->errorMessages = []; } } @@ -80,7 +80,7 @@ protected function processValue($value, $isRoot = false) $this->usedBindings[$bindingId] = true; unset($this->unusedBindings[$bindingId]); } elseif (!isset($this->usedBindings[$bindingId])) { - $this->unusedBindings[$bindingId] = array($key, $this->currentId); + $this->unusedBindings[$bindingId] = [$key, $this->currentId]; } if (isset($key[0]) && '$' === $key[0]) { @@ -88,7 +88,7 @@ protected function processValue($value, $isRoot = false) } if (null !== $bindingValue && !$bindingValue instanceof Reference && !$bindingValue instanceof Definition) { - throw new InvalidArgumentException(sprintf('Invalid value for binding key "%s" for service "%s": expected null, an instance of %s or an instance of %s, %s given.', $key, $this->currentId, Reference::class, Definition::class, gettype($bindingValue))); + throw new InvalidArgumentException(sprintf('Invalid value for binding key "%s" for service "%s": expected null, an instance of %s or an instance of %s, %s given.', $key, $this->currentId, Reference::class, Definition::class, \gettype($bindingValue))); } } @@ -100,7 +100,7 @@ protected function processValue($value, $isRoot = false) try { if ($constructor = $this->getConstructor($value, false)) { - $calls[] = array($constructor, $value->getArguments()); + $calls[] = [$constructor, $value->getArguments()]; } } catch (RuntimeException $e) { $this->errorMessages[] = $e->getMessage(); diff --git a/Compiler/ResolveChildDefinitionsPass.php b/Compiler/ResolveChildDefinitionsPass.php index 5dd766b3f..52a729993 100644 --- a/Compiler/ResolveChildDefinitionsPass.php +++ b/Compiler/ResolveChildDefinitionsPass.php @@ -15,6 +15,7 @@ use Symfony\Component\DependencyInjection\Definition; use Symfony\Component\DependencyInjection\Exception\ExceptionInterface; use Symfony\Component\DependencyInjection\Exception\RuntimeException; +use Symfony\Component\DependencyInjection\Exception\ServiceCircularReferenceException; /** * This replaces all ChildDefinition instances with their equivalent fully @@ -25,6 +26,8 @@ */ class ResolveChildDefinitionsPass extends AbstractRecursivePass { + private $currentPath; + protected function processValue($value, $isRoot = false) { if (!$value instanceof Definition) { @@ -36,6 +39,7 @@ protected function processValue($value, $isRoot = false) $value = $this->container->getDefinition($this->currentId); } if ($value instanceof ChildDefinition) { + $this->currentPath = []; $value = $this->resolveDefinition($value); if ($isRoot) { $this->container->setDefinition($this->currentId, $value); @@ -56,6 +60,8 @@ private function resolveDefinition(ChildDefinition $definition) { try { return $this->doResolveDefinition($definition); + } catch (ServiceCircularReferenceException $e) { + throw $e; } catch (ExceptionInterface $e) { $r = new \ReflectionProperty($e, 'message'); $r->setAccessible(true); @@ -71,6 +77,13 @@ private function doResolveDefinition(ChildDefinition $definition) throw new RuntimeException(sprintf('Parent definition "%s" does not exist.', $parent)); } + $searchKey = array_search($parent, $this->currentPath); + $this->currentPath[] = $parent; + + if (false !== $searchKey) { + throw new ServiceCircularReferenceException($parent, \array_slice($this->currentPath, $searchKey)); + } + $parentDef = $this->container->findDefinition($parent); if ($parentDef instanceof ChildDefinition) { $id = $this->currentId; @@ -147,7 +160,7 @@ private function doResolveDefinition(ChildDefinition $definition) if (is_numeric($k)) { $def->addArgument($v); } elseif (0 === strpos($k, 'index_')) { - $def->replaceArgument((int) substr($k, strlen('index_')), $v); + $def->replaceArgument((int) substr($k, \strlen('index_')), $v); } else { $def->setArgument($k, $v); } diff --git a/Compiler/ResolveClassPass.php b/Compiler/ResolveClassPass.php index 0235e5abb..5932472ec 100644 --- a/Compiler/ResolveClassPass.php +++ b/Compiler/ResolveClassPass.php @@ -11,8 +11,8 @@ namespace Symfony\Component\DependencyInjection\Compiler; -use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\ChildDefinition; +use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException; /** diff --git a/Compiler/ResolveEnvPlaceholdersPass.php b/Compiler/ResolveEnvPlaceholdersPass.php index f42107c6f..9e1edd4d3 100644 --- a/Compiler/ResolveEnvPlaceholdersPass.php +++ b/Compiler/ResolveEnvPlaceholdersPass.php @@ -20,7 +20,7 @@ class ResolveEnvPlaceholdersPass extends AbstractRecursivePass { protected function processValue($value, $isRoot = false) { - if (is_string($value)) { + if (\is_string($value)) { return $this->container->resolveEnvPlaceholders($value, true); } if ($value instanceof Definition) { @@ -35,7 +35,7 @@ protected function processValue($value, $isRoot = false) $value = parent::processValue($value, $isRoot); - if ($value && is_array($value) && !$isRoot) { + if ($value && \is_array($value) && !$isRoot) { $value = array_combine($this->container->resolveEnvPlaceholders(array_keys($value), true), $value); } diff --git a/Compiler/ResolveFactoryClassPass.php b/Compiler/ResolveFactoryClassPass.php index c41cf973f..848da7f2b 100644 --- a/Compiler/ResolveFactoryClassPass.php +++ b/Compiler/ResolveFactoryClassPass.php @@ -24,7 +24,7 @@ class ResolveFactoryClassPass extends AbstractRecursivePass */ protected function processValue($value, $isRoot = false) { - if ($value instanceof Definition && is_array($factory = $value->getFactory()) && null === $factory[0]) { + if ($value instanceof Definition && \is_array($factory = $value->getFactory()) && null === $factory[0]) { if (null === $class = $value->getClass()) { throw new RuntimeException(sprintf('The "%s" service is defined to be created by a factory, but is missing the factory class. Did you forget to define the factory or service class?', $this->currentId)); } diff --git a/Compiler/ResolveHotPathPass.php b/Compiler/ResolveHotPathPass.php index 38e96d06f..5def58058 100644 --- a/Compiler/ResolveHotPathPass.php +++ b/Compiler/ResolveHotPathPass.php @@ -24,7 +24,7 @@ class ResolveHotPathPass extends AbstractRecursivePass { private $tagName; - private $resolvedIds = array(); + private $resolvedIds = []; public function __construct($tagName = 'container.hot_path') { @@ -40,7 +40,7 @@ public function process(ContainerBuilder $container) parent::process($container); $container->getDefinition('service_container')->clearTag($this->tagName); } finally { - $this->resolvedIds = array(); + $this->resolvedIds = []; } } diff --git a/Compiler/ResolveInstanceofConditionalsPass.php b/Compiler/ResolveInstanceofConditionalsPass.php index 500de64bc..3b38557ae 100644 --- a/Compiler/ResolveInstanceofConditionalsPass.php +++ b/Compiler/ResolveInstanceofConditionalsPass.php @@ -14,8 +14,8 @@ use Symfony\Component\DependencyInjection\ChildDefinition; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Definition; -use Symfony\Component\DependencyInjection\Exception\RuntimeException; use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException; +use Symfony\Component\DependencyInjection\Exception\RuntimeException; /** * Applies instanceof conditionals to definitions. @@ -47,7 +47,7 @@ public function process(ContainerBuilder $container) private function processDefinition(ContainerBuilder $container, $id, Definition $definition) { $instanceofConditionals = $definition->getInstanceofConditionals(); - $autoconfiguredInstanceof = $definition->isAutoconfigured() ? $container->getAutoconfiguredInstanceof() : array(); + $autoconfiguredInstanceof = $definition->isAutoconfigured() ? $container->getAutoconfiguredInstanceof() : []; if (!$instanceofConditionals && !$autoconfiguredInstanceof) { return $definition; } @@ -58,10 +58,10 @@ private function processDefinition(ContainerBuilder $container, $id, Definition $conditionals = $this->mergeConditionals($autoconfiguredInstanceof, $instanceofConditionals, $container); - $definition->setInstanceofConditionals(array()); + $definition->setInstanceofConditionals([]); $parent = $shared = null; - $instanceofTags = array(); - $instanceofCalls = array(); + $instanceofTags = []; + $instanceofCalls = []; foreach ($conditionals as $interface => $instanceofDefs) { if ($interface !== $class && (!$container->getReflectionClass($class, false))) { @@ -84,8 +84,8 @@ private function processDefinition(ContainerBuilder $container, $id, Definition $instanceofCalls[] = $methodCall; } - $instanceofDef->setTags(array()); - $instanceofDef->setMethodCalls(array()); + $instanceofDef->setTags([]); + $instanceofDef->setMethodCalls([]); if (isset($instanceofDef->getChanges()['shared'])) { $shared = $instanceofDef->isShared(); @@ -98,7 +98,7 @@ private function processDefinition(ContainerBuilder $container, $id, Definition $abstract = $container->setDefinition('.abstract.instanceof.'.$id, $definition); // cast Definition to ChildDefinition - $definition->setBindings(array()); + $definition->setBindings([]); $definition = serialize($definition); $definition = substr_replace($definition, '53', 2, 2); $definition = substr_replace($definition, 'Child', 44, 0); @@ -110,11 +110,11 @@ private function processDefinition(ContainerBuilder $container, $id, Definition $definition->setShared($shared); } - $i = count($instanceofTags); + $i = \count($instanceofTags); while (0 <= --$i) { foreach ($instanceofTags[$i] as $k => $v) { foreach ($v as $v) { - if ($definition->hasTag($k) && in_array($v, $definition->getTag($k))) { + if ($definition->hasTag($k) && \in_array($v, $definition->getTag($k))) { continue; } $definition->addTag($k, $v); @@ -123,14 +123,15 @@ private function processDefinition(ContainerBuilder $container, $id, Definition } $definition->setMethodCalls(array_merge($instanceofCalls, $definition->getMethodCalls())); + $definition->setBindings($bindings); // reset fields with "merge" behavior $abstract - ->setBindings($bindings) - ->setArguments(array()) - ->setMethodCalls(array()) + ->setBindings([]) + ->setArguments([]) + ->setMethodCalls([]) ->setDecoratedService(null) - ->setTags(array()) + ->setTags([]) ->setAbstract(true); } @@ -140,7 +141,7 @@ private function processDefinition(ContainerBuilder $container, $id, Definition private function mergeConditionals(array $autoconfiguredInstanceof, array $instanceofConditionals, ContainerBuilder $container) { // make each value an array of ChildDefinition - $conditionals = array_map(function ($childDef) { return array($childDef); }, $autoconfiguredInstanceof); + $conditionals = array_map(function ($childDef) { return [$childDef]; }, $autoconfiguredInstanceof); foreach ($instanceofConditionals as $interface => $instanceofDef) { // make sure the interface/class exists (but don't validate automaticInstanceofConditionals) @@ -149,7 +150,7 @@ private function mergeConditionals(array $autoconfiguredInstanceof, array $insta } if (!isset($autoconfiguredInstanceof[$interface])) { - $conditionals[$interface] = array(); + $conditionals[$interface] = []; } $conditionals[$interface][] = $instanceofDef; diff --git a/Compiler/ResolveInvalidReferencesPass.php b/Compiler/ResolveInvalidReferencesPass.php index 97f4c1978..ec4b6eec6 100644 --- a/Compiler/ResolveInvalidReferencesPass.php +++ b/Compiler/ResolveInvalidReferencesPass.php @@ -13,13 +13,13 @@ use Symfony\Component\DependencyInjection\Argument\ArgumentInterface; use Symfony\Component\DependencyInjection\Argument\ServiceClosureArgument; +use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\ContainerInterface; use Symfony\Component\DependencyInjection\Definition; +use Symfony\Component\DependencyInjection\Exception\RuntimeException; use Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException; use Symfony\Component\DependencyInjection\Reference; use Symfony\Component\DependencyInjection\TypedReference; -use Symfony\Component\DependencyInjection\ContainerBuilder; -use Symfony\Component\DependencyInjection\Exception\RuntimeException; /** * Emulates the invalid behavior if the reference is not found within the @@ -66,7 +66,7 @@ private function processValue($value, $rootLevel = 0, $level = 0) $value->setArguments($this->processValue($value->getArguments(), 0)); $value->setProperties($this->processValue($value->getProperties(), 1)); $value->setMethodCalls($this->processValue($value->getMethodCalls(), 2)); - } elseif (is_array($value)) { + } elseif (\is_array($value)) { $i = 0; foreach ($value as $k => $v) { diff --git a/Compiler/ResolveNamedArgumentsPass.php b/Compiler/ResolveNamedArgumentsPass.php index 2dc53da89..70f2556df 100644 --- a/Compiler/ResolveNamedArgumentsPass.php +++ b/Compiler/ResolveNamedArgumentsPass.php @@ -33,15 +33,15 @@ protected function processValue($value, $isRoot = false) } $calls = $value->getMethodCalls(); - $calls[] = array('__construct', $value->getArguments()); + $calls[] = ['__construct', $value->getArguments()]; foreach ($calls as $i => $call) { list($method, $arguments) = $call; $parameters = null; - $resolvedArguments = array(); + $resolvedArguments = []; foreach ($arguments as $key => $argument) { - if (is_int($key)) { + if (\is_int($key)) { $resolvedArguments[$key] = $argument; continue; } @@ -49,6 +49,7 @@ protected function processValue($value, $isRoot = false) if (null === $parameters) { $r = $this->getReflectionMethod($value, $method); $class = $r instanceof \ReflectionMethod ? $r->class : $this->currentId; + $method = $r->getName(); $parameters = $r->getParameters(); } @@ -71,7 +72,7 @@ protected function processValue($value, $isRoot = false) } if (null !== $argument && !$argument instanceof Reference && !$argument instanceof Definition) { - throw new InvalidArgumentException(sprintf('Invalid service "%s": the value of argument "%s" of method "%s()" must be null, an instance of %s or an instance of %s, %s given.', $this->currentId, $key, $class !== $this->currentId ? $class.'::'.$method : $method, Reference::class, Definition::class, gettype($argument))); + throw new InvalidArgumentException(sprintf('Invalid service "%s": the value of argument "%s" of method "%s()" must be null, an instance of %s or an instance of %s, %s given.', $this->currentId, $key, $class !== $this->currentId ? $class.'::'.$method : $method, Reference::class, Definition::class, \gettype($argument))); } $typeFound = false; diff --git a/Compiler/ResolveParameterPlaceHoldersPass.php b/Compiler/ResolveParameterPlaceHoldersPass.php index 3988f6dc2..2dec13f15 100644 --- a/Compiler/ResolveParameterPlaceHoldersPass.php +++ b/Compiler/ResolveParameterPlaceHoldersPass.php @@ -42,7 +42,7 @@ public function process(ContainerBuilder $container) try { parent::process($container); - $aliases = array(); + $aliases = []; foreach ($container->getAliases() as $name => $target) { $this->currentId = $name; $aliases[$this->bag->resolveValue($name)] = $target; @@ -60,10 +60,10 @@ public function process(ContainerBuilder $container) protected function processValue($value, $isRoot = false) { - if (is_string($value)) { + if (\is_string($value)) { $v = $this->bag->resolveValue($value); - return $this->resolveArrays || !$v || !is_array($v) ? $v : $value; + return $this->resolveArrays || !$v || !\is_array($v) ? $v : $value; } if ($value instanceof Definition) { $value->setBindings($this->processValue($value->getBindings())); @@ -78,7 +78,7 @@ protected function processValue($value, $isRoot = false) $value = parent::processValue($value, $isRoot); - if ($value && is_array($value)) { + if ($value && \is_array($value)) { $value = array_combine($this->bag->resolveValue(array_keys($value)), $value); } diff --git a/Compiler/ResolveReferencesToAliasesPass.php b/Compiler/ResolveReferencesToAliasesPass.php index 83677a0dd..7777243da 100644 --- a/Compiler/ResolveReferencesToAliasesPass.php +++ b/Compiler/ResolveReferencesToAliasesPass.php @@ -11,9 +11,9 @@ namespace Symfony\Component\DependencyInjection\Compiler; +use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Exception\ServiceCircularReferenceException; use Symfony\Component\DependencyInjection\Reference; -use Symfony\Component\DependencyInjection\ContainerBuilder; /** * Replaces all references to aliases with references to the actual service. @@ -55,10 +55,10 @@ protected function processValue($value, $isRoot = false) private function getDefinitionId(string $id, ContainerBuilder $container): string { - $seen = array(); + $seen = []; while ($container->hasAlias($id)) { if (isset($seen[$id])) { - throw new ServiceCircularReferenceException($id, array_keys($seen)); + throw new ServiceCircularReferenceException($id, array_merge(array_keys($seen), [$id])); } $seen[$id] = true; $id = (string) $container->getAlias($id); diff --git a/Compiler/ServiceLocatorTagPass.php b/Compiler/ServiceLocatorTagPass.php index 3969c74fc..43c823dbc 100644 --- a/Compiler/ServiceLocatorTagPass.php +++ b/Compiler/ServiceLocatorTagPass.php @@ -37,7 +37,7 @@ protected function processValue($value, $isRoot = false) } $arguments = $value->getArguments(); - if (!isset($arguments[0]) || !is_array($arguments[0])) { + if (!isset($arguments[0]) || !\is_array($arguments[0])) { throw new InvalidArgumentException(sprintf('Invalid definition for service "%s": an array of references is expected as first argument when the "container.service_locator" tag is set.', $this->currentId)); } @@ -46,7 +46,7 @@ protected function processValue($value, $isRoot = false) continue; } if (!$v instanceof Reference) { - throw new InvalidArgumentException(sprintf('Invalid definition for service "%s": an array of references is expected as first argument when the "container.service_locator" tag is set, "%s" found for key "%s".', $this->currentId, is_object($v) ? get_class($v) : gettype($v), $k)); + throw new InvalidArgumentException(sprintf('Invalid definition for service "%s": an array of references is expected as first argument when the "container.service_locator" tag is set, "%s" found for key "%s".', $this->currentId, \is_object($v) ? \get_class($v) : \gettype($v), $k)); } $arguments[0][$k] = new ServiceClosureArgument($v); } @@ -80,7 +80,7 @@ public static function register(ContainerBuilder $container, array $refMap, $cal { foreach ($refMap as $id => $ref) { if (!$ref instanceof Reference) { - throw new InvalidArgumentException(sprintf('Invalid service locator definition: only services can be referenced, "%s" found for key "%s". Inject parameter values using constructors instead.', is_object($ref) ? get_class($ref) : gettype($ref), $id)); + throw new InvalidArgumentException(sprintf('Invalid service locator definition: only services can be referenced, "%s" found for key "%s". Inject parameter values using constructors instead.', \is_object($ref) ? \get_class($ref) : \gettype($ref), $id)); } $refMap[$id] = new ServiceClosureArgument($ref); } @@ -102,7 +102,7 @@ public static function register(ContainerBuilder $container, array $refMap, $cal // to derivate customized instances from the prototype one. $container->register($id .= '.'.$callerId, ServiceLocator::class) ->setPublic(false) - ->setFactory(array(new Reference($locatorId), 'withContext')) + ->setFactory([new Reference($locatorId), 'withContext']) ->addArgument($callerId) ->addArgument(new Reference('service_container')); } diff --git a/Compiler/ServiceReferenceGraph.php b/Compiler/ServiceReferenceGraph.php index 721e87568..308abc656 100644 --- a/Compiler/ServiceReferenceGraph.php +++ b/Compiler/ServiceReferenceGraph.php @@ -28,7 +28,7 @@ class ServiceReferenceGraph /** * @var ServiceReferenceGraphNode[] */ - private $nodes = array(); + private $nodes = []; public function hasNode(string $id): bool { @@ -67,13 +67,13 @@ public function clear() foreach ($this->nodes as $node) { $node->clear(); } - $this->nodes = array(); + $this->nodes = []; } /** * Connects 2 nodes together in the Graph. */ - public function connect(?string $sourceId, $sourceValue, ?string $destId, $destValue = null, $reference = null, bool $lazy = false, bool $weak = false) + public function connect(?string $sourceId, $sourceValue, ?string $destId, $destValue = null, $reference = null, bool $lazy = false, bool $weak = false, bool $byConstructor = false) { if (null === $sourceId || null === $destId) { return; @@ -81,7 +81,7 @@ public function connect(?string $sourceId, $sourceValue, ?string $destId, $destV $sourceNode = $this->createNode($sourceId, $sourceValue); $destNode = $this->createNode($destId, $destValue); - $edge = new ServiceReferenceGraphEdge($sourceNode, $destNode, $reference, $lazy, $weak); + $edge = new ServiceReferenceGraphEdge($sourceNode, $destNode, $reference, $lazy, $weak, $byConstructor); $sourceNode->addOutEdge($edge); $destNode->addInEdge($edge); diff --git a/Compiler/ServiceReferenceGraphEdge.php b/Compiler/ServiceReferenceGraphEdge.php index 3e5b9c92c..986145606 100644 --- a/Compiler/ServiceReferenceGraphEdge.php +++ b/Compiler/ServiceReferenceGraphEdge.php @@ -25,14 +25,16 @@ class ServiceReferenceGraphEdge private $value; private $lazy; private $weak; + private $byConstructor; - public function __construct(ServiceReferenceGraphNode $sourceNode, ServiceReferenceGraphNode $destNode, $value = null, bool $lazy = false, bool $weak = false) + public function __construct(ServiceReferenceGraphNode $sourceNode, ServiceReferenceGraphNode $destNode, $value = null, bool $lazy = false, bool $weak = false, bool $byConstructor = false) { $this->sourceNode = $sourceNode; $this->destNode = $destNode; $this->value = $value; $this->lazy = $lazy; $this->weak = $weak; + $this->byConstructor = $byConstructor; } /** @@ -84,4 +86,14 @@ public function isWeak() { return $this->weak; } + + /** + * Returns true if the edge links with a constructor argument. + * + * @return bool + */ + public function isReferencedByConstructor() + { + return $this->byConstructor; + } } diff --git a/Compiler/ServiceReferenceGraphNode.php b/Compiler/ServiceReferenceGraphNode.php index b7274c425..f0b9bcfe2 100644 --- a/Compiler/ServiceReferenceGraphNode.php +++ b/Compiler/ServiceReferenceGraphNode.php @@ -11,8 +11,8 @@ namespace Symfony\Component\DependencyInjection\Compiler; -use Symfony\Component\DependencyInjection\Definition; use Symfony\Component\DependencyInjection\Alias; +use Symfony\Component\DependencyInjection\Definition; /** * Represents a node in your service graph. @@ -24,8 +24,8 @@ class ServiceReferenceGraphNode { private $id; - private $inEdges = array(); - private $outEdges = array(); + private $inEdges = []; + private $outEdges = []; private $value; /** @@ -113,6 +113,6 @@ public function getValue() */ public function clear() { - $this->inEdges = $this->outEdges = array(); + $this->inEdges = $this->outEdges = []; } } diff --git a/Compiler/ValidateEnvPlaceholdersPass.php b/Compiler/ValidateEnvPlaceholdersPass.php index 402aca637..1848ec4db 100644 --- a/Compiler/ValidateEnvPlaceholdersPass.php +++ b/Compiler/ValidateEnvPlaceholdersPass.php @@ -26,7 +26,7 @@ */ class ValidateEnvPlaceholdersPass implements CompilerPassInterface { - private static $typeFixtures = array('array' => array(), 'bool' => false, 'float' => 0.0, 'int' => 0, 'string' => ''); + private static $typeFixtures = ['array' => [], 'bool' => false, 'float' => 0.0, 'int' => 0, 'string' => '']; /** * {@inheritdoc} @@ -46,14 +46,14 @@ public function process(ContainerBuilder $container) $envTypes = $resolvingBag->getProvidedTypes(); try { foreach ($resolvingBag->getEnvPlaceholders() + $resolvingBag->getUnusedEnvPlaceholders() as $env => $placeholders) { - $values = array(); + $values = []; if (false === $i = strpos($env, ':')) { - $default = $defaultBag->has("env($env)") ? $defaultBag->get("env($env)") : null; + $default = $defaultBag->has("env($env)") ? $defaultBag->get("env($env)") : self::$typeFixtures['string']; $defaultType = null !== $default ? self::getType($default) : 'string'; $values[$defaultType] = $default; } else { $prefix = substr($env, 0, $i); - foreach ($envTypes[$prefix] ?? array('string') as $type) { + foreach ($envTypes[$prefix] ?? ['string'] as $type) { $values[$type] = self::$typeFixtures[$type] ?? null; } } @@ -65,7 +65,7 @@ public function process(ContainerBuilder $container) $processor = new Processor(); foreach ($extensions as $name => $extension) { - if (!$extension instanceof ConfigurationExtensionInterface || !$config = $container->getExtensionConfig($name)) { + if (!$extension instanceof ConfigurationExtensionInterface || !$config = array_filter($container->getExtensionConfig($name))) { // this extension has no semantic configuration or was not called continue; } diff --git a/Container.php b/Container.php index 2b3ab61e4..d800acb10 100644 --- a/Container.php +++ b/Container.php @@ -14,11 +14,11 @@ use Symfony\Component\DependencyInjection\Exception\EnvNotFoundException; use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException; use Symfony\Component\DependencyInjection\Exception\ParameterCircularReferenceException; -use Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException; use Symfony\Component\DependencyInjection\Exception\ServiceCircularReferenceException; -use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface; +use Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException; use Symfony\Component\DependencyInjection\ParameterBag\EnvPlaceholderParameterBag; use Symfony\Component\DependencyInjection\ParameterBag\FrozenParameterBag; +use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface; /** * Container is a dependency injection container. @@ -40,16 +40,16 @@ class Container implements ResettableContainerInterface { protected $parameterBag; - protected $services = array(); - protected $fileMap = array(); - protected $methodMap = array(); - protected $factories = array(); - protected $aliases = array(); - protected $loading = array(); - protected $resolving = array(); - protected $syntheticIds = array(); - - private $envCache = array(); + protected $services = []; + protected $fileMap = []; + protected $methodMap = []; + protected $factories = []; + protected $aliases = []; + protected $loading = []; + protected $resolving = []; + protected $syntheticIds = []; + + private $envCache = []; private $compiled = false; private $getEnv; @@ -219,7 +219,7 @@ public function get($id, $invalidBehavior = /* self::EXCEPTION_ON_INVALID_REFERE { return $this->services[$id] ?? $this->services[$id = $this->aliases[$id] ?? $id] - ?? ('service_container' === $id ? $this : ($this->factories[$id] ?? array($this, 'make'))($id, $invalidBehavior)); + ?? ('service_container' === $id ? $this : ($this->factories[$id] ?? [$this, 'make'])($id, $invalidBehavior)); } /** @@ -230,7 +230,7 @@ public function get($id, $invalidBehavior = /* self::EXCEPTION_ON_INVALID_REFERE private function make(string $id, int $invalidBehavior) { if (isset($this->loading[$id])) { - throw new ServiceCircularReferenceException($id, array_keys($this->loading)); + throw new ServiceCircularReferenceException($id, array_merge(array_keys($this->loading), [$id])); } $this->loading[$id] = true; @@ -254,19 +254,19 @@ private function make(string $id, int $invalidBehavior) throw new ServiceNotFoundException($id); } if (isset($this->syntheticIds[$id])) { - throw new ServiceNotFoundException($id, null, null, array(), sprintf('The "%s" service is synthetic, it needs to be set at boot time before it can be used.', $id)); + throw new ServiceNotFoundException($id, null, null, [], sprintf('The "%s" service is synthetic, it needs to be set at boot time before it can be used.', $id)); } if (isset($this->getRemovedIds()[$id])) { - throw new ServiceNotFoundException($id, null, null, array(), sprintf('The "%s" service or alias has been removed or inlined when the container was compiled. You should either make it public, or stop using the container directly and use dependency injection instead.', $id)); + throw new ServiceNotFoundException($id, null, null, [], sprintf('The "%s" service or alias has been removed or inlined when the container was compiled. You should either make it public, or stop using the container directly and use dependency injection instead.', $id)); } - $alternatives = array(); + $alternatives = []; foreach ($this->getServiceIds() as $knownId) { if ('' === $knownId || '.' === $knownId[0]) { continue; } $lev = levenshtein($id, $knownId); - if ($lev <= strlen($id) / 3 || false !== strpos($knownId, $id)) { + if ($lev <= \strlen($id) / 3 || false !== strpos($knownId, $id)) { $alternatives[] = $knownId; } } @@ -300,7 +300,7 @@ public function initialized($id) */ public function reset() { - $this->services = $this->factories = array(); + $this->services = $this->factories = []; } /** @@ -310,7 +310,7 @@ public function reset() */ public function getServiceIds() { - return array_unique(array_merge(array('service_container'), array_keys($this->fileMap), array_keys($this->methodMap), array_keys($this->services))); + return array_unique(array_merge(['service_container'], array_keys($this->fileMap), array_keys($this->methodMap), array_keys($this->services))); } /** @@ -320,7 +320,7 @@ public function getServiceIds() */ public function getRemovedIds() { - return array(); + return []; } /** @@ -332,7 +332,7 @@ public function getRemovedIds() */ public static function camelize($id) { - return strtr(ucwords(strtr($id, array('_' => ' ', '.' => '_ ', '\\' => '_ '))), array(' ' => '')); + return strtr(ucwords(strtr($id, ['_' => ' ', '.' => '_ ', '\\' => '_ '])), [' ' => '']); } /** @@ -344,7 +344,7 @@ public static function camelize($id) */ public static function underscore($id) { - return strtolower(preg_replace(array('/([A-Z]+)([A-Z][a-z])/', '/([a-z\d])([A-Z])/'), array('\\1_\\2', '\\1_\\2'), str_replace('_', '.', $id))); + return strtolower(preg_replace(['/([A-Z]+)([A-Z][a-z])/', '/([a-z\d])([A-Z])/'], ['\\1_\\2', '\\1_\\2'], str_replace('_', '.', $id))); } /** @@ -375,7 +375,7 @@ protected function getEnv($name) return $this->envCache[$name]; } if (!$this->has($id = 'container.env_var_processors_locator')) { - $this->set($id, new ServiceLocator(array())); + $this->set($id, new ServiceLocator([])); } if (!$this->getEnv) { $this->getEnv = new \ReflectionMethod($this, __FUNCTION__); diff --git a/ContainerAwareInterface.php b/ContainerAwareInterface.php index d78491bb9..e7b9d575e 100644 --- a/ContainerAwareInterface.php +++ b/ContainerAwareInterface.php @@ -18,5 +18,8 @@ */ interface ContainerAwareInterface { + /** + * Sets the container. + */ public function setContainer(ContainerInterface $container = null); } diff --git a/ContainerBuilder.php b/ContainerBuilder.php index 1c2c23986..90ac34943 100644 --- a/ContainerBuilder.php +++ b/ContainerBuilder.php @@ -12,6 +12,14 @@ namespace Symfony\Component\DependencyInjection; use Psr\Container\ContainerInterface as PsrContainerInterface; +use Symfony\Component\Config\Resource\ClassExistenceResource; +use Symfony\Component\Config\Resource\ComposerResource; +use Symfony\Component\Config\Resource\DirectoryResource; +use Symfony\Component\Config\Resource\FileExistenceResource; +use Symfony\Component\Config\Resource\FileResource; +use Symfony\Component\Config\Resource\GlobResource; +use Symfony\Component\Config\Resource\ReflectionClassResource; +use Symfony\Component\Config\Resource\ResourceInterface; use Symfony\Component\DependencyInjection\Argument\IteratorArgument; use Symfony\Component\DependencyInjection\Argument\RewindableGenerator; use Symfony\Component\DependencyInjection\Argument\ServiceClosureArgument; @@ -26,18 +34,10 @@ use Symfony\Component\DependencyInjection\Exception\ServiceCircularReferenceException; use Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException; use Symfony\Component\DependencyInjection\Extension\ExtensionInterface; -use Symfony\Component\DependencyInjection\ParameterBag\EnvPlaceholderParameterBag; -use Symfony\Component\DependencyInjection\ParameterBag\ParameterBag; -use Symfony\Component\Config\Resource\ClassExistenceResource; -use Symfony\Component\Config\Resource\ComposerResource; -use Symfony\Component\Config\Resource\DirectoryResource; -use Symfony\Component\Config\Resource\FileExistenceResource; -use Symfony\Component\Config\Resource\FileResource; -use Symfony\Component\Config\Resource\GlobResource; -use Symfony\Component\Config\Resource\ReflectionClassResource; -use Symfony\Component\Config\Resource\ResourceInterface; use Symfony\Component\DependencyInjection\LazyProxy\Instantiator\InstantiatorInterface; use Symfony\Component\DependencyInjection\LazyProxy\Instantiator\RealServiceInstantiator; +use Symfony\Component\DependencyInjection\ParameterBag\EnvPlaceholderParameterBag; +use Symfony\Component\DependencyInjection\ParameterBag\ParameterBag; use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface; use Symfony\Component\ExpressionLanguage\Expression; use Symfony\Component\ExpressionLanguage\ExpressionFunctionProviderInterface; @@ -52,29 +52,29 @@ class ContainerBuilder extends Container implements TaggedContainerInterface /** * @var ExtensionInterface[] */ - private $extensions = array(); + private $extensions = []; /** * @var ExtensionInterface[] */ - private $extensionsByNs = array(); + private $extensionsByNs = []; /** * @var Definition[] */ - private $definitions = array(); + private $definitions = []; /** * @var Alias[] */ - private $aliasDefinitions = array(); + private $aliasDefinitions = []; /** * @var ResourceInterface[] */ - private $resources = array(); + private $resources = []; - private $extensionConfigs = array(); + private $extensionConfigs = []; /** * @var Compiler @@ -96,34 +96,33 @@ class ContainerBuilder extends Container implements TaggedContainerInterface /** * @var ExpressionFunctionProviderInterface[] */ - private $expressionLanguageProviders = array(); + private $expressionLanguageProviders = []; /** * @var string[] with tag names used by findTaggedServiceIds */ - private $usedTags = array(); + private $usedTags = []; /** * @var string[][] a map of env var names to their placeholders */ - private $envPlaceholders = array(); + private $envPlaceholders = []; /** * @var int[] a map of env vars to their resolution counter */ - private $envCounters = array(); + private $envCounters = []; /** * @var string[] the list of vendor directories */ private $vendors; - private $autoconfiguredInstanceof = array(); + private $autoconfiguredInstanceof = []; - private $removedIds = array(); - private $alreadyLoading = array(); + private $removedIds = []; - private static $internalTypes = array( + private static $internalTypes = [ 'int' => true, 'float' => true, 'string' => true, @@ -135,7 +134,7 @@ class ContainerBuilder extends Container implements TaggedContainerInterface 'callable' => true, 'iterable' => true, 'mixed' => true, - ); + ]; public function __construct(ParameterBagInterface $parameterBag = null) { @@ -292,8 +291,8 @@ public function setResources(array $resources) public function addObjectResource($object) { if ($this->trackResources) { - if (is_object($object)) { - $object = get_class($object); + if (\is_object($object)) { + $object = \get_class($object); } if (!isset($this->classReflectors[$object])) { $this->classReflectors[$object] = new \ReflectionClass($object); @@ -345,11 +344,11 @@ public function getReflectionClass(?string $class, bool $throw = true): ?\Reflec try { if (isset($this->classReflectors[$class])) { $classReflector = $this->classReflectors[$class]; - } elseif ($this->trackResources) { + } elseif (class_exists(ClassExistenceResource::class)) { $resource = new ClassExistenceResource($class, false); $classReflector = $resource->isFresh(0) ? false : new \ReflectionClass($class); } else { - $classReflector = new \ReflectionClass($class); + $classReflector = class_exists($class) ? new \ReflectionClass($class) : false; } } catch (\ReflectionException $e) { if ($throw) { @@ -401,7 +400,7 @@ public function fileExists(string $path, $trackContents = true): bool if (is_dir($path)) { if ($trackContents) { - $this->addResource(new DirectoryResource($path, is_string($trackContents) ? $trackContents : null)); + $this->addResource(new DirectoryResource($path, \is_string($trackContents) ? $trackContents : null)); } else { $this->addResource(new GlobResource($path, '/*', false)); } @@ -429,8 +428,8 @@ public function loadFromExtension($extension, array $values = null) throw new BadMethodCallException('Cannot load from an extension on a compiled container.'); } - if (func_num_args() < 2) { - $values = array(); + if (\func_num_args() < 2) { + $values = []; } $namespace = $this->getExtension($extension)->getAlias(); @@ -555,20 +554,30 @@ public function get($id, $invalidBehavior = ContainerInterface::EXCEPTION_ON_INV return $this->doGet($id, $invalidBehavior); } - private function doGet($id, $invalidBehavior = ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE, array &$inlineServices = array()) + private function doGet($id, $invalidBehavior = ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE, array &$inlineServices = null, $isConstructorArgument = false) { if (isset($inlineServices[$id])) { return $inlineServices[$id]; } - if (ContainerInterface::IGNORE_ON_UNINITIALIZED_REFERENCE === $invalidBehavior) { - return parent::get($id, $invalidBehavior); + if (null === $inlineServices) { + $isConstructorArgument = true; + $inlineServices = []; } - if ($service = parent::get($id, ContainerInterface::NULL_ON_INVALID_REFERENCE)) { - return $service; + 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); + return $this->doGet((string) $this->aliasDefinitions[$id], $invalidBehavior, $inlineServices, $isConstructorArgument); } try { @@ -585,16 +594,17 @@ private function doGet($id, $invalidBehavior = ContainerInterface::EXCEPTION_ON_ throw new RuntimeException(reset($e)); } - $loading = isset($this->alreadyLoading[$id]) ? 'loading' : 'alreadyLoading'; - $this->{$loading}[$id] = true; + if ($isConstructorArgument) { + $this->loading[$id] = true; + } try { - $service = $this->createService($definition, $inlineServices, $id); + return $this->createService($definition, $inlineServices, $isConstructorArgument, $id); } finally { - unset($this->{$loading}[$id]); + if ($isConstructorArgument) { + unset($this->loading[$id]); + } } - - return $service; } /** @@ -606,10 +616,10 @@ private function doGet($id, $invalidBehavior = ContainerInterface::EXCEPTION_ON_ * the parameters passed to the container constructor to have precedence * over the loaded ones. * - * $container = new ContainerBuilder(array('foo' => 'bar')); - * $loader = new LoaderXXX($container); - * $loader->load('resource_name'); - * $container->register('foo', new stdClass()); + * $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 @@ -635,7 +645,7 @@ public function merge(self $container) foreach ($this->extensions as $name => $extension) { if (!isset($this->extensionConfigs[$name])) { - $this->extensionConfigs[$name] = array(); + $this->extensionConfigs[$name] = []; } $this->extensionConfigs[$name] = array_merge($this->extensionConfigs[$name], $container->getExtensionConfig($name)); @@ -645,7 +655,7 @@ public function merge(self $container) $envPlaceholders = $container->getParameterBag()->getEnvPlaceholders(); $this->getParameterBag()->mergeEnvPlaceholders($container->getParameterBag()); } else { - $envPlaceholders = array(); + $envPlaceholders = []; } foreach ($container->envCounters as $env => $count) { @@ -678,7 +688,7 @@ public function merge(self $container) public function getExtensionConfig($name) { if (!isset($this->extensionConfigs[$name])) { - $this->extensionConfigs[$name] = array(); + $this->extensionConfigs[$name] = []; } return $this->extensionConfigs[$name]; @@ -693,7 +703,7 @@ public function getExtensionConfig($name) public function prependExtensionConfig($name, array $config) { if (!isset($this->extensionConfigs[$name])) { - $this->extensionConfigs[$name] = array(); + $this->extensionConfigs[$name] = []; } array_unshift($this->extensionConfigs[$name], $config); @@ -741,7 +751,7 @@ public function compile(bool $resolveEnvPlaceholders = false) } } - $this->extensionConfigs = array(); + $this->extensionConfigs = []; if ($bag instanceof EnvPlaceholderParameterBag) { if ($resolveEnvPlaceholders) { @@ -795,7 +805,7 @@ public function addAliases(array $aliases) */ public function setAliases(array $aliases) { - $this->aliasDefinitions = array(); + $this->aliasDefinitions = []; $this->addAliases($aliases); } @@ -814,7 +824,11 @@ public function setAlias($alias, $id) { $alias = (string) $alias; - if (is_string($id)) { + if ('' === $alias || '\\' === $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($id); } elseif (!$id instanceof Alias) { throw new InvalidArgumentException('$id must be a string, or an Alias object.'); @@ -907,7 +921,7 @@ public function register($id, $class = null) * an autowired definition. * * @param string $id The service identifier - * @param null|string $class The service class + * @param string|null $class The service class * * @return Definition The created definition */ @@ -935,7 +949,7 @@ public function addDefinitions(array $definitions) */ public function setDefinitions(array $definitions) { - $this->definitions = array(); + $this->definitions = []; $this->addDefinitions($definitions); } @@ -967,6 +981,10 @@ public function setDefinition($id, Definition $definition) $id = (string) $id; + if ('' === $id || '\\' === $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; @@ -1019,13 +1037,13 @@ public function findDefinition($id) { $id = (string) $id; - $seen = array(); + $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 = \array_slice($seen, array_search($id, $seen)); $seen[] = $id; throw new ServiceCircularReferenceException($id, $seen); @@ -1050,7 +1068,7 @@ public function findDefinition($id) * @throws RuntimeException When the service is a synthetic service * @throws InvalidArgumentException When configure callable is not callable */ - private function createService(Definition $definition, array &$inlineServices, $id = null, $tryProxy = true) + 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]; @@ -1068,16 +1086,14 @@ private function createService(Definition $definition, array &$inlineServices, $ @trigger_error($definition->getDeprecationMessage($id), E_USER_DEPRECATED); } - if ($tryProxy && $definition->isLazy()) { - $proxy = $this - ->getProxyInstantiator() - ->instantiateProxy( - $this, - $definition, - $id, function () use ($definition, &$inlineServices, $id) { - return $this->createService($definition, $inlineServices, $id, false); - } - ); + 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; @@ -1089,22 +1105,24 @@ private function createService(Definition $definition, array &$inlineServices, $ require_once $parameterBag->resolveValue($definition->getFile()); } - $arguments = $this->doResolveServices($parameterBag->unescapeValue($parameterBag->resolveValue($definition->getArguments())), $inlineServices); - - if (null !== $id && $definition->isShared() && isset($this->services[$id]) && ($tryProxy || !$definition->isLazy())) { - return $this->services[$id]; - } + $arguments = $this->doResolveServices($parameterBag->unescapeValue($parameterBag->resolveValue($definition->getArguments())), $inlineServices, $isConstructorArgument); if (null !== $factory = $definition->getFactory()) { - if (is_array($factory)) { - $factory = array($this->doResolveServices($parameterBag->resolveValue($factory[0]), $inlineServices), $factory[1]); - } elseif (!is_string($factory)) { + 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)); } + } - $service = call_user_func_array($factory, $arguments); + if (null !== $id && $definition->isShared() && isset($this->services[$id]) && ($tryProxy || !$definition->isLazy())) { + return $this->services[$id]; + } - if (!$definition->isDeprecated() && is_array($factory) && is_string($factory[0])) { + 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 ")) { @@ -1112,7 +1130,7 @@ private function createService(Definition $definition, array &$inlineServices, $ } } } else { - $r = new \ReflectionClass($class = $parameterBag->resolveValue($definition->getClass())); + $r = new \ReflectionClass($parameterBag->resolveValue($definition->getClass())); $service = null === $r->getConstructor() ? $r->newInstance() : $r->newInstanceArgs($arguments); @@ -1136,7 +1154,7 @@ private function createService(Definition $definition, array &$inlineServices, $ } if ($callable = $definition->getConfigurator()) { - if (is_array($callable)) { + if (\is_array($callable)) { $callable[0] = $parameterBag->resolveValue($callable[0]); if ($callable[0] instanceof Reference) { @@ -1146,11 +1164,11 @@ private function createService(Definition $definition, array &$inlineServices, $ } } - if (!is_callable($callable)) { - throw new InvalidArgumentException(sprintf('The configure callable for class "%s" is not a callable.', get_class($service))); + 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); + $callable($service); } return $service; @@ -1169,11 +1187,11 @@ public function resolveServices($value) return $this->doResolveServices($value); } - private function doResolveServices($value, array &$inlineServices = array()) + private function doResolveServices($value, array &$inlineServices = [], $isConstructorArgument = false) { - if (is_array($value)) { + if (\is_array($value)) { foreach ($value as $k => $v) { - $value[$k] = $this->doResolveServices($v, $inlineServices); + $value[$k] = $this->doResolveServices($v, $inlineServices, $isConstructorArgument); } } elseif ($value instanceof ServiceClosureArgument) { $reference = $value->getValues()[0]; @@ -1216,13 +1234,13 @@ private function doResolveServices($value, array &$inlineServices = array()) return $count; }); } elseif ($value instanceof Reference) { - $value = $this->doGet((string) $value, $value->getInvalidBehavior(), $inlineServices); + $value = $this->doGet((string) $value, $value->getInvalidBehavior(), $inlineServices, $isConstructorArgument); } elseif ($value instanceof Definition) { - $value = $this->createService($value, $inlineServices); + $value = $this->createService($value, $inlineServices, $isConstructorArgument); } elseif ($value instanceof Parameter) { $value = $this->getParameter((string) $value); } elseif ($value instanceof Expression) { - $value = $this->getExpressionLanguage()->evaluate($value, array('container' => $this)); + $value = $this->getExpressionLanguage()->evaluate($value, ['container' => $this]); } return $value; @@ -1233,14 +1251,14 @@ private function doResolveServices($value, array &$inlineServices = array()) * * Example: * - * $container->register('foo')->addTag('my.tag', array('hello' => 'world')); + * $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']; + * $serviceIds = $container->findTaggedServiceIds('my.tag'); + * foreach ($serviceIds as $serviceId => $tags) { + * foreach ($tags as $tag) { + * echo $tag['hello']; + * } * } - * } * * @param string $name * @param bool $throwOnAbstract @@ -1250,7 +1268,7 @@ private function doResolveServices($value, array &$inlineServices = array()) public function findTaggedServiceIds($name, $throwOnAbstract = false) { $this->usedTags[] = $name; - $tags = array(); + $tags = []; foreach ($this->getDefinitions() as $id => $definition) { if ($definition->hasTag($name)) { if ($throwOnAbstract && $definition->isAbstract()) { @@ -1270,7 +1288,7 @@ public function findTaggedServiceIds($name, $throwOnAbstract = false) */ public function findTags() { - $tags = array(); + $tags = []; foreach ($this->getDefinitions() as $id => $definition) { $tags = array_merge(array_keys($definition->getTags()), $tags); } @@ -1350,7 +1368,7 @@ public function resolveEnvPlaceholders($value, $format = null, array &$usedEnvs } if (\is_array($value)) { - $result = array(); + $result = []; foreach ($value as $k => $v) { $result[\is_string($k) ? $this->resolveEnvPlaceholders($k, $format, $usedEnvs) : $k] = $this->resolveEnvPlaceholders($v, $format, $usedEnvs); } @@ -1376,8 +1394,8 @@ public function resolveEnvPlaceholders($value, $format = null, array &$usedEnvs $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))); + 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); } @@ -1432,9 +1450,9 @@ public function log(CompilerPassInterface $pass, string $message) */ public static function getServiceConditionals($value) { - $services = array(); + $services = []; - if (is_array($value)) { + if (\is_array($value)) { foreach ($value as $v) { $services = array_unique(array_merge($services, self::getServiceConditionals($v))); } @@ -1456,9 +1474,9 @@ public static function getServiceConditionals($value) */ public static function getInitializedConditionals($value) { - $services = array(); + $services = []; - if (is_array($value)) { + if (\is_array($value)) { foreach ($value as $v) { $services = array_unique(array_merge($services, self::getInitializedConditionals($v))); } @@ -1480,7 +1498,7 @@ public static function hash($value) { $hash = substr(base64_encode(hash('sha256', serialize($value), true)), 0, 7); - return str_replace(array('/', '+'), array('.', '_'), $hash); + return str_replace(['/', '+'], ['.', '_'], $hash); } /** @@ -1491,7 +1509,7 @@ protected function getEnv($name) $value = parent::getEnv($name); $bag = $this->getParameterBag(); - if (!is_string($value) || !$bag instanceof EnvPlaceholderParameterBag) { + if (!\is_string($value) || !$bag instanceof EnvPlaceholderParameterBag) { return $value; } @@ -1511,18 +1529,6 @@ protected function getEnv($name) } } - /** - * Retrieves the currently set proxy instantiator or instantiates one. - */ - private function getProxyInstantiator(): InstantiatorInterface - { - if (!$this->proxyInstantiator) { - $this->proxyInstantiator = new RealServiceInstantiator(); - } - - return $this->proxyInstantiator; - } - private function callMethod($service, $call, array &$inlineServices) { foreach (self::getServiceConditionals($call[1]) as $s) { @@ -1536,7 +1542,7 @@ private function callMethod($service, $call, array &$inlineServices) } } - call_user_func_array(array($service, $call[0]), $this->doResolveServices($this->getParameterBag()->unescapeValue($this->getParameterBag()->resolveValue($call[1])), $inlineServices)); + \call_user_func_array([$service, $call[0]], $this->doResolveServices($this->getParameterBag()->unescapeValue($this->getParameterBag()->resolveValue($call[1])), $inlineServices)); } /** @@ -1552,7 +1558,7 @@ private function shareService(Definition $definition, $service, $id, array &$inl if (null !== $id && $definition->isShared()) { $this->services[$id] = $service; - unset($this->loading[$id], $this->alreadyLoading[$id]); + unset($this->loading[$id]); } } @@ -1578,7 +1584,7 @@ private function inVendors($path) $path = realpath($path) ?: $path; foreach ($this->vendors as $vendor) { - if (0 === strpos($path, $vendor) && false !== strpbrk(substr($path, strlen($vendor), 1), '/'.DIRECTORY_SEPARATOR)) { + if (0 === strpos($path, $vendor) && false !== strpbrk(substr($path, \strlen($vendor), 1), '/'.\DIRECTORY_SEPARATOR)) { return true; } } diff --git a/Definition.php b/Definition.php index b6ddff186..a3dd3f16e 100644 --- a/Definition.php +++ b/Definition.php @@ -28,12 +28,12 @@ class Definition private $shared = true; private $deprecated = false; private $deprecationTemplate; - private $properties = array(); - private $calls = array(); - private $instanceof = array(); + private $properties = []; + private $calls = []; + private $instanceof = []; private $autoconfigured = false; private $configurator; - private $tags = array(); + private $tags = []; private $public = true; private $private = true; private $synthetic = false; @@ -41,11 +41,11 @@ class Definition private $lazy = false; private $decoratedService; private $autowired = false; - private $changes = array(); - private $bindings = array(); - private $errors = array(); + private $changes = []; + private $bindings = []; + private $errors = []; - protected $arguments = array(); + protected $arguments = []; private static $defaultDeprecationTemplate = 'The "%service_id%" service is deprecated. You should stop using it, as it will soon be removed.'; @@ -60,7 +60,7 @@ class Definition * @param string|null $class The service class * @param array $arguments An array of arguments to pass to the service constructor */ - public function __construct($class = null, array $arguments = array()) + public function __construct($class = null, array $arguments = []) { if (null !== $class) { $this->setClass($class); @@ -103,7 +103,7 @@ public function setFactory($factory) { $this->changes['factory'] = true; - if (is_string($factory) && false !== strpos($factory, '::')) { + if (\is_string($factory) && false !== strpos($factory, '::')) { $factory = explode('::', $factory, 2); } @@ -115,7 +115,7 @@ public function setFactory($factory) /** * Gets the factory. * - * @return string|array The PHP function or an array containing a class/Reference and a method to call + * @return string|array|null The PHP function or an array containing a class/Reference and a method to call */ public function getFactory() { @@ -125,8 +125,8 @@ public function getFactory() /** * Sets the service that this service is decorating. * - * @param null|string $id The decorated service id, use null to remove decoration - * @param null|string $renamedId The new decorated service id + * @param string|null $id The decorated service id, use null to remove decoration + * @param string|null $renamedId The new decorated service id * @param int $priority The priority of decoration * * @return $this @@ -144,7 +144,7 @@ public function setDecoratedService($id, $renamedId = null, $priority = 0) if (null === $id) { $this->decoratedService = null; } else { - $this->decoratedService = array($id, $renamedId, (int) $priority); + $this->decoratedService = [$id, $renamedId, (int) $priority]; } return $this; @@ -153,7 +153,7 @@ public function setDecoratedService($id, $renamedId = null, $priority = 0) /** * Gets the service that this service is decorating. * - * @return null|array An array composed of the decorated service id, the new id for it and the priority of decoration, null if no service is decorated + * @return array|null An array composed of the decorated service id, the new id for it and the priority of decoration, null if no service is decorated */ public function getDecoratedService() { @@ -261,12 +261,12 @@ public function addArgument($argument) */ public function replaceArgument($index, $argument) { - if (0 === count($this->arguments)) { + if (0 === \count($this->arguments)) { throw new OutOfBoundsException('Cannot replace arguments if none have been configured yet.'); } - if (is_int($index) && ($index < 0 || $index > count($this->arguments) - 1)) { - throw new OutOfBoundsException(sprintf('The index "%d" is not in the range [0, %d].', $index, count($this->arguments) - 1)); + if (\is_int($index) && ($index < 0 || $index > \count($this->arguments) - 1)) { + throw new OutOfBoundsException(sprintf('The index "%d" is not in the range [0, %d].', $index, \count($this->arguments) - 1)); } if (!array_key_exists($index, $this->arguments)) { @@ -326,9 +326,9 @@ public function getArgument($index) * * @return $this */ - public function setMethodCalls(array $calls = array()) + public function setMethodCalls(array $calls = []) { - $this->calls = array(); + $this->calls = []; foreach ($calls as $call) { $this->addMethodCall($call[0], $call[1]); } @@ -346,12 +346,12 @@ public function setMethodCalls(array $calls = array()) * * @throws InvalidArgumentException on empty $method param */ - public function addMethodCall($method, array $arguments = array()) + public function addMethodCall($method, array $arguments = []) { if (empty($method)) { throw new InvalidArgumentException('Method name cannot be empty.'); } - $this->calls[] = array($method, $arguments); + $this->calls[] = [$method, $arguments]; return $this; } @@ -406,7 +406,7 @@ public function getMethodCalls() /** * Sets the definition templates to conditionally apply on the current definition, keyed by parent interface/class. * - * @param $instanceof ChildDefinition[] + * @param ChildDefinition[] $instanceof * * @return $this */ @@ -482,7 +482,7 @@ public function getTags() */ public function getTag($name) { - return isset($this->tags[$name]) ? $this->tags[$name] : array(); + return isset($this->tags[$name]) ? $this->tags[$name] : []; } /** @@ -493,7 +493,7 @@ public function getTag($name) * * @return $this */ - public function addTag($name, array $attributes = array()) + public function addTag($name, array $attributes = []) { $this->tags[$name][] = $attributes; @@ -533,7 +533,7 @@ public function clearTag($name) */ public function clearTags() { - $this->tags = array(); + $this->tags = []; return $this; } @@ -790,7 +790,7 @@ public function setConfigurator($configurator) { $this->changes['configurator'] = true; - if (is_string($configurator) && false !== strpos($configurator, '::')) { + if (\is_string($configurator) && false !== strpos($configurator, '::')) { $configurator = explode('::', $configurator, 2); } diff --git a/Dumper/DumperInterface.php b/Dumper/DumperInterface.php index dd001e4ed..1ea775ddf 100644 --- a/Dumper/DumperInterface.php +++ b/Dumper/DumperInterface.php @@ -25,5 +25,5 @@ interface DumperInterface * * @return string The representation of the service container */ - public function dump(array $options = array()); + public function dump(array $options = []); } diff --git a/Dumper/GraphvizDumper.php b/Dumper/GraphvizDumper.php index 84cc1f59a..b1a9016b0 100644 --- a/Dumper/GraphvizDumper.php +++ b/Dumper/GraphvizDumper.php @@ -12,12 +12,12 @@ 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\Reference; use Symfony\Component\DependencyInjection\Parameter; -use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\ParameterBag\ParameterBag; +use Symfony\Component\DependencyInjection\Reference; /** * GraphvizDumper dumps a service container as a graphviz file. @@ -32,14 +32,14 @@ class GraphvizDumper extends Dumper { private $nodes; private $edges; - private $options = array( - 'graph' => array('ratio' => 'compress'), - 'node' => array('fontsize' => 11, 'fontname' => 'Arial', 'shape' => 'record'), - 'edge' => array('fontsize' => 9, 'fontname' => 'Arial', 'color' => 'grey', 'arrowhead' => 'open', 'arrowsize' => 0.5), - 'node.instance' => array('fillcolor' => '#9999ff', 'style' => 'filled'), - 'node.definition' => array('fillcolor' => '#eeeeee'), - 'node.missing' => array('fillcolor' => '#ff9999', 'style' => 'filled'), - ); + 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. @@ -55,9 +55,9 @@ class GraphvizDumper extends Dumper * * @return string The dot representation of the service container */ - public function dump(array $options = array()) + public function dump(array $options = []) { - foreach (array('graph', 'node', 'edge', 'node.instance', 'node.definition', 'node.missing') as $key) { + 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]); } @@ -65,7 +65,7 @@ public function dump(array $options = array()) $this->nodes = $this->findNodes(); - $this->edges = array(); + $this->edges = []; foreach ($this->container->getDefinitions() as $id => $definition) { $this->edges[$id] = array_merge( $this->findEdges($id, $definition->getArguments(), true, ''), @@ -112,11 +112,11 @@ private function addEdges(): string */ private function findEdges(string $id, array $arguments, bool $required, string $name, bool $lazy = false): array { - $edges = array(); + $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)) { + } elseif (\is_string($argument) && preg_match('/^%([^%]+)%$/', $argument, $match)) { $argument = $this->container->hasParameter($match[1]) ? $this->container->getParameter($match[1]) : null; } @@ -124,15 +124,23 @@ private function findEdges(string $id, array $arguments, bool $required, string $lazyEdge = $lazy; if (!$this->container->has((string) $argument)) { - $this->nodes[(string) $argument] = array('name' => $name, 'required' => $required, 'class' => '', 'attributes' => $this->options['node.missing']); + $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[] = array('name' => $name, 'required' => $required, 'to' => $argument, 'lazy' => $lazyEdge); + $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 (is_array($argument)) { + } 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)); } } @@ -142,7 +150,7 @@ private function findEdges(string $id, array $arguments, bool $required, string private function findNodes(): array { - $nodes = array(); + $nodes = []; $container = $this->cloneContainer(); @@ -158,7 +166,7 @@ private function findNodes(): array } catch (ParameterNotFoundException $e) { } - $nodes[$id] = array('class' => str_replace('\\', '\\\\', $class), 'attributes' => array_merge($this->options['node.definition'], array('style' => $definition->isShared() ? 'filled' : 'dotted'))); + $nodes[$id] = ['class' => str_replace('\\', '\\\\', $class), 'attributes' => array_merge($this->options['node.definition'], ['style' => $definition->isShared() ? 'filled' : 'dotted'])]; $container->setDefinition($id, new Definition('stdClass')); } @@ -168,7 +176,7 @@ private function findNodes(): array } if (!$container->hasDefinition($id)) { - $nodes[$id] = array('class' => str_replace('\\', '\\\\', get_class($container->get($id))), 'attributes' => $this->options['node.instance']); + $nodes[$id] = ['class' => str_replace('\\', '\\\\', \get_class($container->get($id))), 'attributes' => $this->options['node.instance']]; } } @@ -206,7 +214,7 @@ private function endDot(): string private function addAttributes(array $attributes): string { - $code = array(); + $code = []; foreach ($attributes as $k => $v) { $code[] = sprintf('%s="%s"', $k, $v); } @@ -216,7 +224,7 @@ private function addAttributes(array $attributes): string private function addOptions(array $options): string { - $code = array(); + $code = []; foreach ($options as $k => $v) { $code[] = sprintf('%s="%s"', $k, $v); } @@ -231,7 +239,7 @@ private function dotize(string $id): string private function getAliases(string $id): array { - $aliases = array(); + $aliases = []; foreach ($this->container->getAliases() as $alias => $origin) { if ($id == $origin) { $aliases[] = $alias; diff --git a/Dumper/PhpDumper.php b/Dumper/PhpDumper.php index d790aff7d..23b4ad811 100644 --- a/Dumper/PhpDumper.php +++ b/Dumper/PhpDumper.php @@ -14,23 +14,24 @@ use Symfony\Component\DependencyInjection\Argument\ArgumentInterface; use Symfony\Component\DependencyInjection\Argument\IteratorArgument; use Symfony\Component\DependencyInjection\Argument\ServiceClosureArgument; -use Symfony\Component\DependencyInjection\Variable; -use Symfony\Component\DependencyInjection\Definition; use Symfony\Component\DependencyInjection\Compiler\AnalyzeServiceReferencesPass; -use Symfony\Component\DependencyInjection\ContainerBuilder; +use Symfony\Component\DependencyInjection\Compiler\CheckCircularReferencesPass; use Symfony\Component\DependencyInjection\Container; +use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\ContainerInterface; -use Symfony\Component\DependencyInjection\Reference; -use Symfony\Component\DependencyInjection\TypedReference; -use Symfony\Component\DependencyInjection\Parameter; +use Symfony\Component\DependencyInjection\Definition; use Symfony\Component\DependencyInjection\Exception\EnvParameterException; use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException; use Symfony\Component\DependencyInjection\Exception\LogicException; use Symfony\Component\DependencyInjection\Exception\RuntimeException; use Symfony\Component\DependencyInjection\Exception\ServiceCircularReferenceException; +use Symfony\Component\DependencyInjection\ExpressionLanguage; use Symfony\Component\DependencyInjection\LazyProxy\PhpDumper\DumperInterface as ProxyDumper; use Symfony\Component\DependencyInjection\LazyProxy\PhpDumper\NullDumper; -use Symfony\Component\DependencyInjection\ExpressionLanguage; +use Symfony\Component\DependencyInjection\Parameter; +use Symfony\Component\DependencyInjection\Reference; +use Symfony\Component\DependencyInjection\TypedReference; +use Symfony\Component\DependencyInjection\Variable; use Symfony\Component\ExpressionLanguage\Expression; use Symfony\Component\HttpKernel\Kernel; @@ -55,7 +56,9 @@ class PhpDumper extends Dumper private $definitionVariables; private $referenceVariables; private $variableCount; - private $reservedVariables = array('instance', 'class'); + private $inlinedDefinitions; + private $serviceCalls; + private $reservedVariables = ['instance', 'class', 'this']; private $expressionLanguage; private $targetDirRegex; private $targetDirMaxMatches; @@ -66,8 +69,8 @@ class PhpDumper extends Dumper private $asFiles; private $hotPathTag; private $inlineRequires; - private $inlinedRequires = array(); - private $circularReferences = array(); + private $inlinedRequires = []; + private $circularReferences = []; /** * @var ProxyDumper @@ -108,11 +111,11 @@ public function setProxyDumper(ProxyDumper $proxyDumper) * * @throws EnvParameterException When an env var exists but has not been dumped */ - public function dump(array $options = array()) + public function dump(array $options = []) { $this->targetDirRegex = null; - $this->inlinedRequires = array(); - $options = array_merge(array( + $this->inlinedRequires = []; + $options = array_merge([ 'class' => 'ProjectServiceContainer', 'base_class' => 'Container', 'namespace' => '', @@ -121,7 +124,7 @@ public function dump(array $options = array()) 'hot_path_tag' => 'container.hot_path', 'inline_class_loader_parameter' => 'container.dumper.inline_class_loader', 'build_time' => time(), - ), $options); + ], $options); $this->namespace = $options['namespace']; $this->asFiles = $options['as_files']; @@ -139,24 +142,42 @@ public function dump(array $options = array()) $this->initializeMethodNamesMap('Container' === $baseClass ? Container::class : $baseClass); - (new AnalyzeServiceReferencesPass())->process($this->container); - $this->circularReferences = array(); - $checkedNodes = array(); + if ($this->getProxyDumper() instanceof NullDumper) { + (new AnalyzeServiceReferencesPass(true, false))->process($this->container); + try { + (new CheckCircularReferencesPass())->process($this->container); + } catch (ServiceCircularReferenceException $e) { + $path = $e->getPath(); + end($path); + $path[key($path)] .= '". Try running "composer require symfony/proxy-manager-bridge'; + + throw new ServiceCircularReferenceException($e->getServiceId(), $path); + } + } + + (new AnalyzeServiceReferencesPass(false, !$this->getProxyDumper() instanceof NullDumper))->process($this->container); + $checkedNodes = []; + $this->circularReferences = []; foreach ($this->container->getCompiler()->getServiceReferenceGraph()->getNodes() as $id => $node) { - $currentPath = array($id => $id); - $this->analyzeCircularReferences($node->getOutEdges(), $checkedNodes, $currentPath); + if (!$node->getValue() instanceof Definition) { + continue; + } + if (!isset($checkedNodes[$id])) { + $this->analyzeCircularReferences($id, $node->getOutEdges(), $checkedNodes); + } } $this->container->getCompiler()->getServiceReferenceGraph()->clear(); + $checkedNodes = []; $this->docStar = $options['debug'] ? '*' : ''; - if (!empty($options['file']) && is_dir($dir = dirname($options['file']))) { + if (!empty($options['file']) && is_dir($dir = \dirname($options['file']))) { // Build a regexp where the first root dirs are mandatory, // but every other sub-dir is optional up to the full path in $dir // Mandate at least 2 root dirs and not more that 5 optional dirs. - $dir = explode(DIRECTORY_SEPARATOR, realpath($dir)); - $i = count($dir); + $dir = explode(\DIRECTORY_SEPARATOR, realpath($dir)); + $i = \count($dir); if (3 <= $i) { $regex = ''; @@ -164,11 +185,11 @@ public function dump(array $options = array()) $this->targetDirMaxMatches = $i - $lastOptionalDir; while (--$i >= $lastOptionalDir) { - $regex = sprintf('(%s%s)?', preg_quote(DIRECTORY_SEPARATOR.$dir[$i], '#'), $regex); + $regex = sprintf('(%s%s)?', preg_quote(\DIRECTORY_SEPARATOR.$dir[$i], '#'), $regex); } do { - $regex = preg_quote(DIRECTORY_SEPARATOR.$dir[$i], '#').$regex; + $regex = preg_quote(\DIRECTORY_SEPARATOR.$dir[$i], '#').$regex; } while (0 < --$i); $this->targetDirRegex = '#'.preg_quote($dir[0], '#').$regex.'#'; @@ -192,7 +213,7 @@ public function dump(array $options = array()) // This file has been auto-generated by the Symfony Dependency Injection Component for internal use. EOF; - $files = array(); + $files = []; $ids = $this->container->getRemovedIds(); foreach ($this->container->getDefinitions() as $id => $definition) { @@ -202,11 +223,11 @@ public function dump(array $options = array()) } if ($ids = array_keys($ids)) { sort($ids); - $c = "doExport($id)." => true,\n"; } - $files['removed-ids.php'] = $c .= ");\n"; + $files['removed-ids.php'] = $c .= "];\n"; } foreach ($this->generateServiceFiles() as $file => $c) { @@ -217,7 +238,7 @@ public function dump(array $options = array()) } $files[$options['class'].'.php'] = $code; $hash = ucfirst(strtr(ContainerBuilder::hash($files), '._', 'xx')); - $code = array(); + $code = []; foreach ($files as $file => $c) { $code["Container{$hash}/{$file}"] = $c; @@ -245,11 +266,11 @@ public function dump(array $options = array()) \\class_alias(\\Container{$hash}\\{$options['class']}::class, {$options['class']}::class, false); } -return new \\Container{$hash}\\{$options['class']}(array( +return new \\Container{$hash}\\{$options['class']}([ 'container.build_hash' => '$hash', 'container.build_id' => '$id', 'container.build_time' => $time, -), __DIR__.\\DIRECTORY_SEPARATOR.'Container{$hash}'); +], __DIR__.\\DIRECTORY_SEPARATOR.'Container{$hash}'); EOF; } else { @@ -259,10 +280,10 @@ public function dump(array $options = array()) } $this->targetDirRegex = null; - $this->inlinedRequires = array(); - $this->circularReferences = array(); + $this->inlinedRequires = []; + $this->circularReferences = []; - $unusedEnvs = array(); + $unusedEnvs = []; foreach ($this->container->getEnvCounters() as $env => $use) { if (!$use) { $unusedEnvs[] = $env; @@ -287,82 +308,56 @@ private function getProxyDumper(): ProxyDumper return $this->proxyDumper; } - private function addServiceLocalTempVariables(string $cId, Definition $definition, \SplObjectStorage $inlinedDefinitions, \SplObjectStorage $allInlinedDefinitions): string + private function analyzeCircularReferences($sourceId, array $edges, &$checkedNodes, &$currentPath = []) { - $allCalls = $calls = $behavior = array(); + $checkedNodes[$sourceId] = true; + $currentPath[$sourceId] = $sourceId; - foreach ($allInlinedDefinitions as $def) { - $arguments = array($def->getArguments(), $def->getFactory(), $def->getProperties(), $def->getMethodCalls(), $def->getConfigurator()); - $this->getServiceCallsFromArguments($arguments, $allCalls, false, $cId, $behavior, $allInlinedDefinitions[$def]); - } - - $isPreInstance = isset($inlinedDefinitions[$definition]) && isset($this->circularReferences[$cId]) && !$this->getProxyDumper()->isProxyCandidate($definition) && $definition->isShared(); - foreach ($inlinedDefinitions as $def) { - $this->getServiceCallsFromArguments(array($def->getArguments(), $def->getFactory()), $calls, $isPreInstance, $cId); - if ($def !== $definition) { - $arguments = array($def->getProperties(), $def->getMethodCalls(), $def->getConfigurator()); - $this->getServiceCallsFromArguments($arguments, $calls, $isPreInstance && !$this->hasReference($cId, $arguments, true), $cId); - } - } - if (!isset($inlinedDefinitions[$definition])) { - $arguments = array($definition->getProperties(), $definition->getMethodCalls(), $definition->getConfigurator()); - $this->getServiceCallsFromArguments($arguments, $calls, false, $cId); - } - - $code = ''; - foreach ($calls as $id => $callCount) { - if ('service_container' === $id || $id === $cId || isset($this->referenceVariables[$id])) { - continue; - } - if ($callCount <= 1 && $allCalls[$id] <= 1) { - continue; - } - - $name = $this->getNextVariableName(); - $this->referenceVariables[$id] = new Variable($name); - - $reference = ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE >= $behavior[$id] ? new Reference($id, $behavior[$id]) : null; - $code .= sprintf(" \$%s = %s;\n", $name, $this->getServiceCall($id, $reference)); - } - - if ('' !== $code) { - if ($isPreInstance) { - $code .= sprintf(<<<'EOTXT' - - if (isset($this->%s['%s'])) { - return $this->%1$s['%2$s']; - } - -EOTXT - , $definition->isPublic() ? 'services' : 'privates', $cId); - } - - $code .= "\n"; - } - - return $code; - } - - private function analyzeCircularReferences(array $edges, &$checkedNodes, &$currentPath) - { foreach ($edges as $edge) { $node = $edge->getDestNode(); $id = $node->getId(); - if ($node->getValue() && ($edge->isLazy() || $edge->isWeak())) { + if (!$node->getValue() instanceof Definition || $sourceId === $id || $edge->isLazy() || $edge->isWeak()) { // no-op } elseif (isset($currentPath[$id])) { + $currentId = $id; foreach (array_reverse($currentPath) as $parentId) { - $this->circularReferences[$parentId][$id] = $id; - $id = $parentId; + $this->circularReferences[$parentId][$currentId] = $currentId; + if ($parentId === $id) { + break; + } + $currentId = $parentId; } } elseif (!isset($checkedNodes[$id])) { - $checkedNodes[$id] = true; - $currentPath[$id] = $id; - $this->analyzeCircularReferences($node->getOutEdges(), $checkedNodes, $currentPath); - unset($currentPath[$id]); + $this->analyzeCircularReferences($id, $node->getOutEdges(), $checkedNodes, $currentPath); + } elseif (isset($this->circularReferences[$id])) { + $this->connectCircularReferences($id, $currentPath); + } + } + unset($currentPath[$sourceId]); + } + + private function connectCircularReferences($sourceId, &$currentPath, &$subPath = []) + { + $subPath[$sourceId] = $sourceId; + $currentPath[$sourceId] = $sourceId; + + foreach ($this->circularReferences[$sourceId] as $id) { + if (isset($currentPath[$id])) { + $currentId = $id; + foreach (array_reverse($currentPath) as $parentId) { + $this->circularReferences[$parentId][$currentId] = $currentId; + if ($parentId === $id) { + break; + } + $currentId = $parentId; + } + } elseif (!isset($subPath[$id]) && isset($this->circularReferences[$id])) { + $this->connectCircularReferences($id, $currentPath, $subPath); } } + unset($currentPath[$sourceId]); + unset($subPath[$sourceId]); } private function collectLineage($class, array &$lineage) @@ -398,7 +393,7 @@ private function collectLineage($class, array &$lineage) private function generateProxyClasses() { - $alreadyGenerated = array(); + $alreadyGenerated = []; $definitions = $this->container->getDefinitions(); $strip = '' === $this->docStar && method_exists('Symfony\Component\HttpKernel\Kernel', 'stripComments'); $proxyDumper = $this->getProxyDumper(); @@ -413,7 +408,9 @@ private function generateProxyClasses() $alreadyGenerated[$class] = true; // register class' reflector for resource tracking $this->container->getReflectionClass($class); - $proxyCode = "\n".$proxyDumper->getProxyCode($definition); + if ("\n" === $proxyCode = "\n".$proxyDumper->getProxyCode($definition)) { + continue; + } if ($strip) { $proxyCode = "inlineRequires && !$this->isHotPath($definition)) { - $lineage = $calls = $behavior = array(); - foreach ($inlinedDefinitions as $def) { - if (!$def->isDeprecated() && is_string($class = is_array($factory = $def->getFactory()) && is_string($factory[0]) ? $factory[0] : $def->getClass())) { + $lineage = []; + foreach ($this->inlinedDefinitions as $def) { + if (!$def->isDeprecated() && \is_string($class = \is_array($factory = $def->getFactory()) && \is_string($factory[0]) ? $factory[0] : $def->getClass())) { $this->collectLineage($class, $lineage); } - $arguments = array($def->getArguments(), $def->getFactory(), $def->getProperties(), $def->getMethodCalls(), $def->getConfigurator()); - $this->getServiceCallsFromArguments($arguments, $calls, false, $cId, $behavior, $inlinedDefinitions[$def]); } - foreach ($calls as $id => $callCount) { + foreach ($this->serviceCalls as $id => list($callCount, $behavior)) { if ('service_container' !== $id && $id !== $cId - && ContainerInterface::IGNORE_ON_UNINITIALIZED_REFERENCE !== $behavior[$id] + && ContainerInterface::IGNORE_ON_UNINITIALIZED_REFERENCE !== $behavior && $this->container->has($id) && $this->isTrivialInstance($def = $this->container->findDefinition($id)) - && is_string($class = is_array($factory = $def->getFactory()) && is_string($factory[0]) ? $factory[0] : $def->getClass()) + && \is_string($class = \is_array($factory = $def->getFactory()) && \is_string($factory[0]) ? $factory[0] : $def->getClass()) ) { $this->collectLineage($class, $lineage); } @@ -452,7 +447,7 @@ private function addServiceInclude(string $cId, Definition $definition, \SplObje } } - foreach ($inlinedDefinitions as $def) { + foreach ($this->inlinedDefinitions as $def) { if ($file = $def->getFile()) { $code .= sprintf(" include_once %s;\n", $this->dumpValue($file)); } @@ -465,62 +460,11 @@ private function addServiceInclude(string $cId, Definition $definition, \SplObje return $code; } - /** - * Generates the inline definition of a service. - * - * @throws RuntimeException When the factory definition is incomplete - * @throws ServiceCircularReferenceException When a circular reference is detected - */ - private function addServiceInlinedDefinitions(string $id, Definition $definition, \SplObjectStorage $inlinedDefinitions, bool &$isSimpleInstance): string - { - $code = ''; - - foreach ($inlinedDefinitions as $def) { - if ($definition === $def) { - continue; - } - if ($inlinedDefinitions[$def] <= 1 && !$def->getMethodCalls() && !$def->getProperties() && !$def->getConfigurator() && false === strpos($this->dumpValue($def->getClass()), '$')) { - continue; - } - if (isset($this->definitionVariables[$def])) { - $name = $this->definitionVariables[$def]; - } else { - $name = $this->getNextVariableName(); - $this->definitionVariables[$def] = new Variable($name); - } - - // a construct like: - // $a = new ServiceA(ServiceB $b); $b = new ServiceB(ServiceA $a); - // this is an indication for a wrong implementation, you can circumvent this problem - // by setting up your service structure like this: - // $b = new ServiceB(); - // $a = new ServiceA(ServiceB $b); - // $b->setServiceA(ServiceA $a); - if (isset($inlinedDefinitions[$definition]) && $this->hasReference($id, array($def->getArguments(), $def->getFactory()))) { - throw new ServiceCircularReferenceException($id, array($id)); - } - - $code .= $this->addNewInstance($def, '$'.$name, ' = ', $id); - - if (!$this->hasReference($id, array($def->getProperties(), $def->getMethodCalls(), $def->getConfigurator()), true)) { - $code .= $this->addServiceProperties($def, $name); - $code .= $this->addServiceMethodCalls($def, $name); - $code .= $this->addServiceConfigurator($def, $name); - } else { - $isSimpleInstance = false; - } - - $code .= "\n"; - } - - return $code; - } - /** * @throws InvalidArgumentException * @throws RuntimeException */ - private function addServiceInstance(string $id, Definition $definition, string $isSimpleInstance): string + private function addServiceInstance(string $id, Definition $definition, bool $isSimpleInstance): string { $class = $this->dumpValue($definition->getClass()); @@ -532,7 +476,7 @@ private function addServiceInstance(string $id, Definition $definition, string $ $instantiation = ''; if (!$isProxyCandidate && $definition->isShared()) { - $instantiation = sprintf('$this->%s[\'%s\'] = %s', $this->container->getDefinition($id)->isPublic() ? 'services' : 'privates', $id, $isSimpleInstance ? '' : '$instance'); + $instantiation = sprintf('$this->%s[%s] = %s', $this->container->getDefinition($id)->isPublic() ? 'services' : 'privates', $this->doExport($id), $isSimpleInstance ? '' : '$instance'); } elseif (!$isSimpleInstance) { $instantiation = '$instance'; } @@ -544,13 +488,7 @@ private function addServiceInstance(string $id, Definition $definition, string $ $instantiation .= ' = '; } - $code = $this->addNewInstance($definition, $return, $instantiation, $id); - - if (!$isSimpleInstance) { - $code .= "\n"; - } - - return $code; + return $this->addNewInstance($definition, $return, $instantiation, $id); } private function isTrivialInstance(Definition $definition): bool @@ -558,7 +496,7 @@ private function isTrivialInstance(Definition $definition): bool if ($definition->isSynthetic() || $definition->getFile() || $definition->getMethodCalls() || $definition->getProperties() || $definition->getConfigurator()) { return false; } - if ($definition->isDeprecated() || $definition->isLazy() || $definition->getFactory() || 3 < count($definition->getArguments()) || $definition->getErrors()) { + if ($definition->isDeprecated() || $definition->isLazy() || $definition->getFactory() || 3 < \count($definition->getArguments()) || $definition->getErrors()) { return false; } @@ -566,7 +504,7 @@ private function isTrivialInstance(Definition $definition): bool if (!$arg || $arg instanceof Parameter) { continue; } - if (is_array($arg) && 3 >= count($arg)) { + if (\is_array($arg) && 3 >= \count($arg)) { foreach ($arg as $k => $v) { if ($this->dumpValue($k) !== $this->dumpValue($k, false)) { return false; @@ -588,10 +526,6 @@ private function isTrivialInstance(Definition $definition): bool } } - if (false !== strpos($this->dumpLiteralClass($this->dumpValue($definition->getClass())), '$')) { - return false; - } - return true; } @@ -599,7 +533,7 @@ private function addServiceMethodCalls(Definition $definition, string $variableN { $calls = ''; foreach ($definition->getMethodCalls() as $call) { - $arguments = array(); + $arguments = []; foreach ($call[1] as $value) { $arguments[] = $this->dumpValue($value); } @@ -610,7 +544,7 @@ private function addServiceMethodCalls(Definition $definition, string $variableN return $calls; } - private function addServiceProperties(Definition $definition, $variableName = 'instance') + private function addServiceProperties(Definition $definition, string $variableName = 'instance') { $code = ''; foreach ($definition->getProperties() as $name => $value) { @@ -620,47 +554,16 @@ private function addServiceProperties(Definition $definition, $variableName = 'i return $code; } - /** - * @throws ServiceCircularReferenceException when the container contains a circular reference - */ - private function addServiceInlinedDefinitionsSetup(string $id, Definition $definition, \SplObjectStorage $inlinedDefinitions, bool $isSimpleInstance): string - { - $this->referenceVariables[$id] = new Variable('instance'); - - $code = ''; - foreach ($inlinedDefinitions as $def) { - if ($definition === $def || !$this->hasReference($id, array($def->getProperties(), $def->getMethodCalls(), $def->getConfigurator()), true)) { - continue; - } - - // if the instance is simple, the return statement has already been generated - // so, the only possible way to get there is because of a circular reference - if ($isSimpleInstance) { - throw new ServiceCircularReferenceException($id, array($id)); - } - - $name = (string) $this->definitionVariables[$def]; - $code .= $this->addServiceProperties($def, $name); - $code .= $this->addServiceMethodCalls($def, $name); - $code .= $this->addServiceConfigurator($def, $name); - } - - if ('' !== $code && ($definition->getProperties() || $definition->getMethodCalls() || $definition->getConfigurator())) { - $code .= "\n"; - } - - return $code; - } - private function addServiceConfigurator(Definition $definition, string $variableName = 'instance'): string { if (!$callable = $definition->getConfigurator()) { return ''; } - if (is_array($callable)) { + if (\is_array($callable)) { if ($callable[0] instanceof Reference - || ($callable[0] instanceof Definition && $this->definitionVariables->contains($callable[0]))) { + || ($callable[0] instanceof Definition && $this->definitionVariables->contains($callable[0])) + ) { return sprintf(" %s->%s(\$%s);\n", $this->dumpValue($callable[0]), $callable[1], $variableName); } @@ -683,29 +586,28 @@ private function addServiceConfigurator(Definition $definition, string $variable private function addService(string $id, Definition $definition, string &$file = null): string { $this->definitionVariables = new \SplObjectStorage(); - $this->referenceVariables = array(); + $this->referenceVariables = []; $this->variableCount = 0; + $this->referenceVariables[$id] = new Variable('instance'); - $return = array(); + $return = []; if ($class = $definition->getClass()) { - $class = $this->container->resolveEnvPlaceholders($class); + $class = $class instanceof Parameter ? '%'.$class.'%' : $this->container->resolveEnvPlaceholders($class); $return[] = sprintf(0 === strpos($class, '%') ? '@return object A %1$s instance' : '@return \%s', ltrim($class, '\\')); } elseif ($definition->getFactory()) { $factory = $definition->getFactory(); - if (is_string($factory)) { + if (\is_string($factory)) { $return[] = sprintf('@return object An instance returned by %s()', $factory); - } elseif (is_array($factory) && (is_string($factory[0]) || $factory[0] instanceof Definition || $factory[0] instanceof Reference)) { - if (is_string($factory[0]) || $factory[0] instanceof Reference) { - $return[] = sprintf('@return object An instance returned by %s::%s()', (string) $factory[0], $factory[1]); - } elseif ($factory[0] instanceof Definition) { - $return[] = sprintf('@return object An instance returned by %s::%s()', $factory[0]->getClass(), $factory[1]); - } + } elseif (\is_array($factory) && (\is_string($factory[0]) || $factory[0] instanceof Definition || $factory[0] instanceof Reference)) { + $class = $factory[0] instanceof Definition ? $factory[0]->getClass() : (string) $factory[0]; + $class = $class instanceof Parameter ? '%'.$class.'%' : $this->container->resolveEnvPlaceholders($class); + $return[] = sprintf('@return object An instance returned by %s::%s()', $class, $factory[1]); } } if ($definition->isDeprecated()) { - if ($return && 0 === strpos($return[count($return) - 1], '@return')) { + if ($return && 0 === strpos($return[\count($return) - 1], '@return')) { $return[] = ''; } @@ -737,6 +639,9 @@ private function addService(string $id, Definition $definition, string &$file = * Gets the $public '$id'$shared$autowired service. * * $return +EOF; + $code = str_replace('*/', ' ', $code).<<getDefinitionsFromArguments(array($definition)); - $constructorDefinitions = $this->getDefinitionsFromArguments(array($definition->getArguments(), $definition->getFactory())); - $otherDefinitions = new \SplObjectStorage(); - - foreach ($inlinedDefinitions as $def) { - if ($def === $definition || isset($constructorDefinitions[$def])) { - $constructorDefinitions[$def] = $inlinedDefinitions[$def]; - } else { - $otherDefinitions[$def] = $inlinedDefinitions[$def]; - } - } - - $isSimpleInstance = !$definition->getProperties() && !$definition->getMethodCalls() && !$definition->getConfigurator(); + $this->serviceCalls = []; + $this->inlinedDefinitions = $this->getDefinitionsFromArguments([$definition], null, $this->serviceCalls); - $code .= $this->addServiceInclude($id, $definition, $inlinedDefinitions); + $code .= $this->addServiceInclude($id, $definition); if ($this->getProxyDumper()->isProxyCandidate($definition)) { $factoryCode = $asFile ? "\$this->load('%s.php', false)" : '$this->%s(false)'; - $code .= $this->getProxyDumper()->getProxyFactoryCode($definition, $id, sprintf($factoryCode, $methodName)); + $code .= $this->getProxyDumper()->getProxyFactoryCode($definition, $id, sprintf($factoryCode, $methodName, $this->doExport($id))); } if ($definition->isDeprecated()) { $code .= sprintf(" @trigger_error(%s, E_USER_DEPRECATED);\n\n", $this->export($definition->getDeprecationMessage($id))); } - $code .= - $this->addServiceLocalTempVariables($id, $definition, $constructorDefinitions, $inlinedDefinitions). - $this->addServiceInlinedDefinitions($id, $definition, $constructorDefinitions, $isSimpleInstance). - $this->addServiceInstance($id, $definition, $isSimpleInstance). - $this->addServiceLocalTempVariables($id, $definition, $otherDefinitions, $inlinedDefinitions). - $this->addServiceInlinedDefinitions($id, $definition, $otherDefinitions, $isSimpleInstance). - $this->addServiceInlinedDefinitionsSetup($id, $definition, $inlinedDefinitions, $isSimpleInstance). - $this->addServiceProperties($definition). - $this->addServiceMethodCalls($definition). - $this->addServiceConfigurator($definition). - (!$isSimpleInstance ? "\n return \$instance;\n" : '') - ; + $code .= $this->addInlineService($id, $definition); if ($asFile) { $code = implode("\n", array_map(function ($line) { return $line ? substr($line, 8) : $line; }, explode("\n", $code))); @@ -794,8 +677,123 @@ protected function {$methodName}($lazyInitialization) $code .= " }\n"; } - $this->definitionVariables = null; - $this->referenceVariables = null; + $this->definitionVariables = $this->inlinedDefinitions = null; + $this->referenceVariables = $this->serviceCalls = null; + + return $code; + } + + private function addInlineVariables(string $id, Definition $definition, array $arguments, bool $forConstructor): string + { + $code = ''; + + foreach ($arguments as $argument) { + if (\is_array($argument)) { + $code .= $this->addInlineVariables($id, $definition, $argument, $forConstructor); + } elseif ($argument instanceof Reference) { + $code .= $this->addInlineReference($id, $definition, $argument, $forConstructor); + } elseif ($argument instanceof Definition) { + $code .= $this->addInlineService($id, $definition, $argument, $forConstructor); + } + } + + return $code; + } + + private function addInlineReference(string $id, Definition $definition, string $targetId, bool $forConstructor): string + { + list($callCount, $behavior) = $this->serviceCalls[$targetId]; + + while ($this->container->hasAlias($targetId)) { + $targetId = (string) $this->container->getAlias($targetId); + } + + if ($id === $targetId) { + return $this->addInlineService($id, $definition, $definition); + } + + if ('service_container' === $targetId || isset($this->referenceVariables[$targetId])) { + return ''; + } + + $hasSelfRef = isset($this->circularReferences[$id][$targetId]); + $forConstructor = $forConstructor && !isset($this->definitionVariables[$definition]); + $code = $hasSelfRef && !$forConstructor ? $this->addInlineService($id, $definition, $definition) : ''; + + if (isset($this->referenceVariables[$targetId]) || (2 > $callCount && (!$hasSelfRef || !$forConstructor))) { + return $code; + } + + $name = $this->getNextVariableName(); + $this->referenceVariables[$targetId] = new Variable($name); + + $reference = ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE >= $behavior ? new Reference($targetId, $behavior) : null; + $code .= sprintf(" \$%s = %s;\n", $name, $this->getServiceCall($targetId, $reference)); + + if (!$hasSelfRef || !$forConstructor) { + return $code; + } + + $code .= sprintf(<<<'EOTXT' + + if (isset($this->%s[%s])) { + return $this->%1$s[%2$s]; + } + +EOTXT + , + $this->container->getDefinition($id)->isPublic() ? 'services' : 'privates', + $this->doExport($id) + ); + + return $code; + } + + private function addInlineService(string $id, Definition $definition, Definition $inlineDef = null, bool $forConstructor = true): string + { + $isSimpleInstance = $isRootInstance = null === $inlineDef; + + if (isset($this->definitionVariables[$inlineDef = $inlineDef ?: $definition])) { + return ''; + } + + $arguments = [$inlineDef->getArguments(), $inlineDef->getFactory()]; + + $code = $this->addInlineVariables($id, $definition, $arguments, $forConstructor); + + if ($arguments = array_filter([$inlineDef->getProperties(), $inlineDef->getMethodCalls(), $inlineDef->getConfigurator()])) { + $isSimpleInstance = false; + } elseif ($definition !== $inlineDef && 2 > $this->inlinedDefinitions[$inlineDef]) { + return $code; + } + + if (isset($this->definitionVariables[$inlineDef])) { + $isSimpleInstance = false; + } else { + $name = $definition === $inlineDef ? 'instance' : $this->getNextVariableName(); + $this->definitionVariables[$inlineDef] = new Variable($name); + $code .= '' !== $code ? "\n" : ''; + + if ('instance' === $name) { + $code .= $this->addServiceInstance($id, $definition, $isSimpleInstance); + } else { + $code .= $this->addNewInstance($inlineDef, '$'.$name, ' = ', $id); + } + + if ('' !== $inline = $this->addInlineVariables($id, $definition, $arguments, false)) { + $code .= "\n".$inline."\n"; + } elseif ($arguments && 'instance' === $name) { + $code .= "\n"; + } + + $code .= $this->addServiceProperties($inlineDef, $name); + $code .= $this->addServiceMethodCalls($inlineDef, $name); + $code .= $this->addServiceConfigurator($inlineDef, $name); + } + + if ($isRootInstance && !$isSimpleInstance) { + $code .= "\n return \$instance;\n"; + } return $code; } @@ -830,12 +828,12 @@ private function generateServiceFiles() if (!$definition->isShared()) { $i = strpos($code, "\n\ninclude_once "); if (false !== $i && false !== $i = strpos($code, "\n\n", 2 + $i)) { - $code = array(substr($code, 0, 2 + $i), substr($code, 2 + $i)); + $code = [substr($code, 0, 2 + $i), substr($code, 2 + $i)]; } else { - $code = array("\n", $code); + $code = ["\n", $code]; } $code[1] = implode("\n", array_map(function ($line) { return $line ? ' '.$line : $line; }, explode("\n", $code[1]))); - $factory = sprintf('$this->factories%s[\'%s\']', $definition->isPublic() ? '' : "['service_container']", $id); + $factory = sprintf('$this->factories%s[%s]', $definition->isPublic() ? '' : "['service_container']", $this->doExport($id)); $code[1] = sprintf("%s = function () {\n%s};\n\nreturn %1\$s();\n", $factory, $code[1]); $code = $code[0].$code[1]; } @@ -850,14 +848,14 @@ private function addNewInstance(Definition $definition, $return, $instantiation, $class = $this->dumpValue($definition->getClass()); $return = ' '.$return.$instantiation; - $arguments = array(); + $arguments = []; foreach ($definition->getArguments() as $value) { $arguments[] = $this->dumpValue($value); } if (null !== $definition->getFactory()) { $callable = $definition->getFactory(); - if (is_array($callable)) { + if (\is_array($callable)) { if (!preg_match('/^[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*$/', $callable[1])) { throw new RuntimeException(sprintf('Cannot dump definition because of invalid factory method (%s)', $callable[1] ?: 'n/a')); } @@ -918,12 +916,12 @@ private function startClass(string $class, string $baseClass, string $baseClassW class $class extends $baseClass { private \$parameters; - private \$targetDirs = array(); + private \$targetDirs = []; /*{$this->docStar} * @internal but protected for BC on cache:clear */ - protected \$privates = array(); + protected \$privates = []; public function __construct() { @@ -941,7 +939,7 @@ public function __construct() } if ($this->asFiles) { $code = str_replace('$parameters', "\$buildParameters;\n private \$containerDir;\n private \$parameters", $code); - $code = str_replace('__construct()', '__construct(array $buildParameters = array(), $containerDir = __DIR__)', $code); + $code = str_replace('__construct()', '__construct(array $buildParameters = [], $containerDir = __DIR__)', $code); $code .= " \$this->buildParameters = \$buildParameters;\n"; $code .= " \$this->containerDir = \$containerDir;\n"; } @@ -961,7 +959,7 @@ public function __construct() if ($this->container->getParameterBag()->all()) { $code .= " \$this->parameters = \$this->getDefaultParameters();\n\n"; } - $code .= " \$this->services = \$this->privates = array();\n"; + $code .= " \$this->services = \$this->privates = [];\n"; $code .= $this->addSyntheticIds(); $code .= $this->addMethodMap(); @@ -973,7 +971,7 @@ public function __construct() public function reset() { - \$this->privates = array(); + \$this->privates = []; parent::reset(); } @@ -1041,7 +1039,7 @@ private function addSyntheticIds(): string } } - return $code ? " \$this->syntheticIds = array(\n{$code} );\n" : ''; + return $code ? " \$this->syntheticIds = [\n{$code} ];\n" : ''; } private function addRemovedIds(): string @@ -1062,10 +1060,13 @@ private function addRemovedIds(): string $ids = array_keys($ids); sort($ids); foreach ($ids as $id) { + if (preg_match('/^\.\d+_[^~]++~[._a-zA-Z\d]{7}$/', $id)) { + continue; + } $code .= ' '.$this->doExport($id)." => true,\n"; } - $code = "array(\n{$code} )"; + $code = "[\n{$code} ]"; } return <<methodMap = array(\n{$code} );\n" : ''; + return $code ? " \$this->methodMap = [\n{$code} ];\n" : ''; } private function addFileMap(): string @@ -1103,16 +1104,16 @@ private function addFileMap(): string } } - return $code ? " \$this->fileMap = array(\n{$code} );\n" : ''; + return $code ? " \$this->fileMap = [\n{$code} ];\n" : ''; } private function addAliases(): string { if (!$aliases = $this->container->getAliases()) { - return "\n \$this->aliases = array();\n"; + return "\n \$this->aliases = [];\n"; } - $code = " \$this->aliases = array(\n"; + $code = " \$this->aliases = [\n"; ksort($aliases); foreach ($aliases as $alias => $id) { $id = (string) $id; @@ -1122,7 +1123,7 @@ private function addAliases(): string $code .= ' '.$this->doExport($alias).' => '.$this->doExport($id).",\n"; } - return $code." );\n"; + return $code." ];\n"; } private function addInlineRequires(): string @@ -1131,14 +1132,14 @@ private function addInlineRequires(): string return ''; } - $lineage = array(); + $lineage = []; foreach ($this->container->findTaggedServiceIds($this->hotPathTag) as $id => $tags) { $definition = $this->container->getDefinition($id); - $inlinedDefinitions = $this->getDefinitionsFromArguments(array($definition)); + $inlinedDefinitions = $this->getDefinitionsFromArguments([$definition]); foreach ($inlinedDefinitions as $def) { - if (is_string($class = is_array($factory = $def->getFactory()) && is_string($factory[0]) ? $factory[0] : $def->getClass())) { + if (\is_string($class = \is_array($factory = $def->getFactory()) && \is_string($factory[0]) ? $factory[0] : $def->getClass())) { $this->collectLineage($class, $lineage); } } @@ -1162,15 +1163,15 @@ private function addDefaultParametersMethod(): string return ''; } - $php = array(); - $dynamicPhp = array(); + $php = []; + $dynamicPhp = []; foreach ($this->container->getParameterBag()->all() as $key => $value) { if ($key !== $resolvedKey = $this->container->resolveEnvPlaceholders($key)) { throw new InvalidArgumentException(sprintf('Parameter name cannot use env parameters: %s.', $resolvedKey)); } - $export = $this->exportParameters(array($value)); - $export = explode('0 => ', substr(rtrim($export, " )\n"), 7, -1), 2); + $export = $this->exportParameters([$value]); + $export = explode('0 => ', substr(rtrim($export, " ]\n"), 2, -1), 2); if (preg_match("/\\\$this->(?:getEnv\('(?:\w++:)*+\w++'\)|targetDirs\[\d++\])/", $export[1])) { $dynamicPhp[$key] = sprintf('%scase %s: $value = %s; break;', $export[0], $this->export($key), $export[1]); @@ -1178,7 +1179,8 @@ private function addDefaultParametersMethod(): string $php[] = sprintf('%s%s => %s,', $export[0], $this->export($key), $export[1]); } } - $parameters = sprintf("array(\n%s\n%s)", implode("\n", $php), str_repeat(' ', 8)); + + $parameters = sprintf("[\n%s\n%s]", implode("\n", $php), str_repeat(' ', 8)); $code = <<<'EOF' @@ -1236,7 +1238,7 @@ public function getParameterBag() } if ($dynamicPhp) { - $loadedDynamicParameters = $this->exportParameters(array_combine(array_keys($dynamicPhp), array_fill(0, count($dynamicPhp), false)), '', 8); + $loadedDynamicParameters = $this->exportParameters(array_combine(array_keys($dynamicPhp), array_fill(0, \count($dynamicPhp), false)), '', 8); $getDynamicParameter = <<<'EOF' switch ($name) { %s @@ -1248,19 +1250,19 @@ public function getParameterBag() EOF; $getDynamicParameter = sprintf($getDynamicParameter, implode("\n", $dynamicPhp)); } else { - $loadedDynamicParameters = 'array()'; + $loadedDynamicParameters = '[]'; $getDynamicParameter = str_repeat(' ', 8).'throw new InvalidArgumentException(sprintf(\'The dynamic parameter "%s" must be defined.\', $name));'; } $code .= <<docStar} * Computes a dynamic parameter. * - * @param string The name of the dynamic parameter to load + * @param string \$name The name of the dynamic parameter to load * * @return mixed The value of the dynamic parameter * @@ -1291,12 +1293,12 @@ protected function getDefaultParameters() */ private function exportParameters(array $parameters, string $path = '', int $indent = 12): string { - $php = array(); + $php = []; foreach ($parameters as $key => $value) { - if (is_array($value)) { + if (\is_array($value)) { $value = $this->exportParameters($value, $path.'/'.$key, $indent + 4); } elseif ($value instanceof ArgumentInterface) { - throw new InvalidArgumentException(sprintf('You cannot dump a container with parameters that contain special arguments. "%s" found in "%s".', get_class($value), $path.'/'.$key)); + throw new InvalidArgumentException(sprintf('You cannot dump a container with parameters that contain special arguments. "%s" found in "%s".', \get_class($value), $path.'/'.$key)); } elseif ($value instanceof Variable) { throw new InvalidArgumentException(sprintf('You cannot dump a container with parameters that contain variable references. Variable "%s" found in "%s".', $value, $path.'/'.$key)); } elseif ($value instanceof Definition) { @@ -1312,7 +1314,7 @@ private function exportParameters(array $parameters, string $path = '', int $ind $php[] = sprintf('%s%s => %s,', str_repeat(' ', $indent), $this->export($key), $value); } - return sprintf("array(\n%s\n%s)", implode("\n", $php), str_repeat(' ', $indent - 4)); + return sprintf("[\n%s\n%s]", implode("\n", $php), str_repeat(' ', $indent - 4)); } private function endClass(): string @@ -1337,19 +1339,19 @@ private function wrapServiceConditionals($value, string $code): string private function getServiceConditionals($value): string { - $conditions = array(); + $conditions = []; foreach (ContainerBuilder::getInitializedConditionals($value) as $service) { if (!$this->container->hasDefinition($service)) { return 'false'; } - $conditions[] = sprintf("isset(\$this->%s['%s'])", $this->container->getDefinition($service)->isPublic() ? 'services' : 'privates', $service); + $conditions[] = sprintf("isset(\$this->%s[%s])", $this->container->getDefinition($service)->isPublic() ? 'services' : 'privates', $this->doExport($service)); } foreach (ContainerBuilder::getServiceConditionals($value) as $service) { if ($this->container->hasDefinition($service) && !$this->container->getDefinition($service)->isPublic()) { continue; } - $conditions[] = sprintf("\$this->has('%s')", $service); + $conditions[] = sprintf("\$this->has(%s)", $this->doExport($service)); } if (!$conditions) { @@ -1359,121 +1361,56 @@ private function getServiceConditionals($value): string return implode(' && ', $conditions); } - private function getServiceCallsFromArguments(array $arguments, array &$calls, bool $isPreInstance, string $callerId, array &$behavior = array(), int $step = 1) + private function getDefinitionsFromArguments(array $arguments, \SplObjectStorage $definitions = null, array &$calls = []): \SplObjectStorage { + if (null === $definitions) { + $definitions = new \SplObjectStorage(); + } + foreach ($arguments as $argument) { - if (is_array($argument)) { - $this->getServiceCallsFromArguments($argument, $calls, $isPreInstance, $callerId, $behavior, $step); + if (\is_array($argument)) { + $this->getDefinitionsFromArguments($argument, $definitions, $calls); } elseif ($argument instanceof Reference) { $id = (string) $argument; if (!isset($calls[$id])) { - $calls[$id] = (int) ($isPreInstance && isset($this->circularReferences[$callerId][$id])); - } - if (!isset($behavior[$id])) { - $behavior[$id] = $argument->getInvalidBehavior(); + $calls[$id] = [0, $argument->getInvalidBehavior()]; } else { - $behavior[$id] = min($behavior[$id], $argument->getInvalidBehavior()); + $calls[$id][1] = min($calls[$id][1], $argument->getInvalidBehavior()); } - $calls[$id] += $step; - } - } - } - - private function getDefinitionsFromArguments(array $arguments, \SplObjectStorage $definitions = null): \SplObjectStorage - { - if (null === $definitions) { - $definitions = new \SplObjectStorage(); - } - - foreach ($arguments as $argument) { - if (is_array($argument)) { - $this->getDefinitionsFromArguments($argument, $definitions); + ++$calls[$id][0]; } elseif (!$argument instanceof Definition) { // no-op } elseif (isset($definitions[$argument])) { $definitions[$argument] = 1 + $definitions[$argument]; } else { $definitions[$argument] = 1; - $this->getDefinitionsFromArguments($argument->getArguments(), $definitions); - $this->getDefinitionsFromArguments(array($argument->getFactory()), $definitions); - $this->getDefinitionsFromArguments($argument->getProperties(), $definitions); - $this->getDefinitionsFromArguments($argument->getMethodCalls(), $definitions); - $this->getDefinitionsFromArguments(array($argument->getConfigurator()), $definitions); - // move current definition last in the list - $nbOccurences = $definitions[$argument]; - unset($definitions[$argument]); - $definitions[$argument] = $nbOccurences; + $arguments = [$argument->getArguments(), $argument->getFactory(), $argument->getProperties(), $argument->getMethodCalls(), $argument->getConfigurator()]; + $this->getDefinitionsFromArguments($arguments, $definitions, $calls); } } return $definitions; } - private function hasReference(string $id, array $arguments, bool $deep = false, array &$visited = array()): bool - { - if (!isset($this->circularReferences[$id])) { - return false; - } - - foreach ($arguments as $argument) { - if (is_array($argument)) { - if ($this->hasReference($id, $argument, $deep, $visited)) { - return true; - } - - continue; - } elseif ($argument instanceof Reference) { - $argumentId = (string) $argument; - if ($id === $argumentId) { - return true; - } - - if (!$deep || isset($visited[$argumentId]) || !isset($this->circularReferences[$id][$argumentId])) { - continue; - } - - $visited[$argumentId] = true; - - $service = $this->container->getDefinition($argumentId); - } elseif ($argument instanceof Definition) { - $service = $argument; - } else { - continue; - } - - // if the proxy manager is enabled, disable searching for references in lazy services, - // as these services will be instantiated lazily and don't have direct related references. - if ($service->isLazy() && !$this->getProxyDumper() instanceof NullDumper) { - continue; - } - - if ($this->hasReference($id, array($service->getArguments(), $service->getFactory(), $service->getProperties(), $service->getMethodCalls(), $service->getConfigurator()), $deep, $visited)) { - return true; - } - } - - return false; - } - /** * @throws RuntimeException */ private function dumpValue($value, bool $interpolate = true): string { - if (is_array($value)) { + if (\is_array($value)) { if ($value && $interpolate && false !== $param = array_search($value, $this->container->getParameterBag()->all(), true)) { return $this->dumpValue("%$param%"); } - $code = array(); + $code = []; foreach ($value as $k => $v) { $code[] = sprintf('%s => %s', $this->dumpValue($k, $interpolate), $this->dumpValue($v, $interpolate)); } - return sprintf('array(%s)', implode(', ', $code)); + return sprintf('[%s]', implode(', ', $code)); } elseif ($value instanceof ArgumentInterface) { - $scope = array($this->definitionVariables, $this->referenceVariables, $this->variableCount); + $scope = [$this->definitionVariables, $this->referenceVariables]; $this->definitionVariables = $this->referenceVariables = null; try { @@ -1492,14 +1429,14 @@ private function dumpValue($value, bool $interpolate = true): string } if ($value instanceof IteratorArgument) { - $operands = array(0); - $code = array(); + $operands = [0]; + $code = []; $code[] = 'new RewindableGenerator(function () {'; if (!$values = $value->getValues()) { $code[] = ' return new \EmptyIterator();'; } else { - $countCode = array(); + $countCode = []; $countCode[] = 'function () {'; foreach ($values as $k => $v) { @@ -1516,12 +1453,12 @@ private function dumpValue($value, bool $interpolate = true): string $countCode[] = ' }'; } - $code[] = sprintf(' }, %s)', count($operands) > 1 ? implode("\n", $countCode) : $operands[0]); + $code[] = sprintf(' }, %s)', \count($operands) > 1 ? implode("\n", $countCode) : $operands[0]); return implode("\n", $code); } } finally { - list($this->definitionVariables, $this->referenceVariables, $this->variableCount) = $scope; + list($this->definitionVariables, $this->referenceVariables) = $scope; } } elseif ($value instanceof Definition) { if (null !== $this->definitionVariables && $this->definitionVariables->contains($value)) { @@ -1537,7 +1474,7 @@ private function dumpValue($value, bool $interpolate = true): string throw new RuntimeException('Cannot dump definitions which have a configurator.'); } - $arguments = array(); + $arguments = []; foreach ($value->getArguments() as $argument) { $arguments[] = $this->dumpValue($argument); } @@ -1545,17 +1482,17 @@ private function dumpValue($value, bool $interpolate = true): string if (null !== $value->getFactory()) { $factory = $value->getFactory(); - if (is_string($factory)) { + if (\is_string($factory)) { return sprintf('%s(%s)', $this->dumpLiteralClass($this->dumpValue($factory)), implode(', ', $arguments)); } - if (is_array($factory)) { + if (\is_array($factory)) { if (!preg_match('/^[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*$/', $factory[1])) { throw new RuntimeException(sprintf('Cannot dump definition because of invalid factory method (%s)', $factory[1] ?: 'n/a')); } $class = $this->dumpValue($factory[0]); - if (is_string($factory[0])) { + if (\is_string($factory[0])) { return sprintf('%s::%s(%s)', $this->dumpLiteralClass($class), $factory[1], implode(', ', $arguments)); } @@ -1591,10 +1528,10 @@ private function dumpValue($value, bool $interpolate = true): string return $this->getServiceCall($id, $value); } elseif ($value instanceof Expression) { - return $this->getExpressionLanguage()->compile((string) $value, array('this' => 'container')); + return $this->getExpressionLanguage()->compile((string) $value, ['this' => 'container']); } elseif ($value instanceof Parameter) { return $this->dumpParameter($value); - } elseif (true === $interpolate && is_string($value)) { + } elseif (true === $interpolate && \is_string($value)) { if (preg_match('/^%([^%]+)%$/', $value, $match)) { // we do this to deal with non string values (Boolean, integer, ...) // the preg_replace_callback converts them to strings @@ -1608,7 +1545,7 @@ private function dumpValue($value, bool $interpolate = true): string return $code; } - } elseif (is_object($value) || is_resource($value)) { + } 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.'); } @@ -1640,16 +1577,16 @@ private function dumpParameter(string $name): string $value = $this->container->getParameter($name); $dumpedValue = $this->dumpValue($value, false); - if (!$value || !is_array($value)) { + if (!$value || !\is_array($value)) { return $dumpedValue; } if (!preg_match("/\\\$this->(?:getEnv\('(?:\w++:)*+\w++'\)|targetDirs\[\d++\])/", $dumpedValue)) { - return sprintf("\$this->parameters['%s']", $name); + return sprintf('$this->parameters[%s]', $this->doExport($name)); } } - return sprintf("\$this->getParameter('%s')", $name); + return sprintf('$this->getParameter(%s)', $this->doExport($name)); } private function getServiceCall(string $id, Reference $reference = null): string @@ -1662,8 +1599,10 @@ private function getServiceCall(string $id, Reference $reference = null): string return '$this'; } - if ($this->container->hasDefinition($id) && ($definition = $this->container->getDefinition($id)) && !$definition->isSynthetic()) { - if (null !== $reference && ContainerInterface::IGNORE_ON_UNINITIALIZED_REFERENCE === $reference->getInvalidBehavior()) { + if ($this->container->hasDefinition($id) && $definition = $this->container->getDefinition($id)) { + if ($definition->isSynthetic()) { + $code = sprintf('$this->get(%s%s)', $this->doExport($id), null !== $reference ? ', '.$reference->getInvalidBehavior() : ''); + } elseif (null !== $reference && ContainerInterface::IGNORE_ON_UNINITIALIZED_REFERENCE === $reference->getInvalidBehavior()) { $code = 'null'; if (!$definition->isShared()) { return $code; @@ -1671,19 +1610,20 @@ private function getServiceCall(string $id, Reference $reference = null): string } elseif ($this->isTrivialInstance($definition)) { $code = substr($this->addNewInstance($definition, '', '', $id), 8, -2); if ($definition->isShared()) { - $code = sprintf('$this->%s[\'%s\'] = %s', $definition->isPublic() ? 'services' : 'privates', $id, $code); + $code = sprintf('$this->%s[%s] = %s', $definition->isPublic() ? 'services' : 'privates', $this->doExport($id), $code); } + $code = "($code)"; } elseif ($this->asFiles && !$this->isHotPath($definition)) { $code = sprintf("\$this->load('%s.php')", $this->generateMethodName($id)); if (!$definition->isShared()) { - $factory = sprintf('$this->factories%s[\'%s\']', $definition->isPublic() ? '' : "['service_container']", $id); + $factory = sprintf('$this->factories%s[%s]', $definition->isPublic() ? '' : "['service_container']", $this->doExport($id)); $code = sprintf('(isset(%s) ? %1$s() : %s)', $factory, $code); } } else { $code = sprintf('$this->%s()', $this->generateMethodName($id)); } if ($definition->isShared()) { - $code = sprintf('($this->%s[\'%s\'] ?? %s)', $definition->isPublic() ? 'services' : 'privates', $id, $code); + $code = sprintf('($this->%s[%s] ?? %s)', $definition->isPublic() ? 'services' : 'privates', $this->doExport($id), $code); } return $code; @@ -1692,12 +1632,12 @@ private function getServiceCall(string $id, Reference $reference = null): string return 'null'; } if (null !== $reference && ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE < $reference->getInvalidBehavior()) { - $code = sprintf('$this->get(\'%s\', /* ContainerInterface::NULL_ON_INVALID_REFERENCE */ %d)', $id, ContainerInterface::NULL_ON_INVALID_REFERENCE); + $code = sprintf('$this->get(%s, /* ContainerInterface::NULL_ON_INVALID_REFERENCE */ %d)', $this->doExport($id), ContainerInterface::NULL_ON_INVALID_REFERENCE); } else { - $code = sprintf('$this->get(\'%s\')', $id); + $code = sprintf('$this->get(%s)', $this->doExport($id)); } - return sprintf('($this->services[\'%s\'] ?? %s)', $id, $code); + return sprintf('($this->services[%s] ?? %s)', $this->doExport($id), $code); } /** @@ -1705,8 +1645,8 @@ private function getServiceCall(string $id, Reference $reference = null): string */ private function initializeMethodNamesMap(string $class) { - $this->serviceIdToMethodNameMap = array(); - $this->usedMethodNames = array(); + $this->serviceIdToMethodNameMap = []; + $this->usedMethodNames = []; if ($reflectionClass = $this->container->getReflectionClass($class)) { foreach ($reflectionClass->getMethods() as $method) { @@ -1744,9 +1684,9 @@ private function generateMethodName(string $id): string private function getNextVariableName(): string { $firstChars = self::FIRST_CHARS; - $firstCharsLength = strlen($firstChars); + $firstCharsLength = \strlen($firstChars); $nonFirstChars = self::NON_FIRST_CHARS; - $nonFirstCharsLength = strlen($nonFirstChars); + $nonFirstCharsLength = \strlen($nonFirstChars); while (true) { $name = ''; @@ -1766,7 +1706,7 @@ private function getNextVariableName(): string ++$this->variableCount; // check that the name is not reserved - if (in_array($name, $this->reservedVariables, true)) { + if (\in_array($name, $this->reservedVariables, true)) { continue; } @@ -1808,12 +1748,12 @@ private function isHotPath(Definition $definition) private function export($value) { - if (null !== $this->targetDirRegex && is_string($value) && preg_match($this->targetDirRegex, $value, $matches, PREG_OFFSET_CAPTURE)) { + if (null !== $this->targetDirRegex && \is_string($value) && preg_match($this->targetDirRegex, $value, $matches, PREG_OFFSET_CAPTURE)) { $prefix = $matches[0][1] ? $this->doExport(substr($value, 0, $matches[0][1]), true).'.' : ''; - $suffix = $matches[0][1] + strlen($matches[0][0]); + $suffix = $matches[0][1] + \strlen($matches[0][0]); $suffix = isset($value[$suffix]) ? '.'.$this->doExport(substr($value, $suffix), true) : ''; $dirname = $this->asFiles ? '$this->containerDir' : '__DIR__'; - $offset = 1 + $this->targetDirMaxMatches - count($matches); + $offset = 1 + $this->targetDirMaxMatches - \count($matches); if ($this->asFiles || 0 < $offset) { $dirname = sprintf('$this->targetDirs[%d]', $offset); @@ -1831,7 +1771,7 @@ private function export($value) private function doExport($value, $resolveEnv = false) { - if (is_string($value) && false !== strpos($value, "\n")) { + if (\is_string($value) && false !== strpos($value, "\n")) { $cleanParts = explode("\n", $value); $cleanParts = array_map(function ($part) { return var_export($part, true); }, $cleanParts); $export = implode('."\n".', $cleanParts); diff --git a/Dumper/XmlDumper.php b/Dumper/XmlDumper.php index 664e58aa8..620d09c14 100644 --- a/Dumper/XmlDumper.php +++ b/Dumper/XmlDumper.php @@ -11,15 +11,15 @@ 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\Parameter; -use Symfony\Component\DependencyInjection\Reference; use Symfony\Component\DependencyInjection\Definition; -use Symfony\Component\DependencyInjection\Alias; use Symfony\Component\DependencyInjection\Exception\RuntimeException; +use Symfony\Component\DependencyInjection\Parameter; +use Symfony\Component\DependencyInjection\Reference; use Symfony\Component\ExpressionLanguage\Expression; /** @@ -40,7 +40,7 @@ class XmlDumper extends Dumper * * @return string An xml string representing of the service container */ - public function dump(array $options = array()) + public function dump(array $options = []) { $this->document = new \DOMDocument('1.0', 'utf-8'); $this->document->formatOutput = true; @@ -80,7 +80,7 @@ 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])) { + if (\count($methodcall[1])) { $this->convertParameters($methodcall[1], 'argument', $call); } $parent->appendChild($call); @@ -160,10 +160,10 @@ private function addService($definition, $id, \DOMElement $parent) if ($callable = $definition->getFactory()) { $factory = $this->document->createElement('factory'); - if (is_array($callable) && $callable[0] instanceof Definition) { + if (\is_array($callable) && $callable[0] instanceof Definition) { $this->addService($callable[0], null, $factory); $factory->setAttribute('method', $callable[1]); - } elseif (is_array($callable)) { + } elseif (\is_array($callable)) { if (null !== $callable[0]) { $factory->setAttribute($callable[0] instanceof Reference ? 'service' : 'class', $callable[0]); } @@ -196,10 +196,10 @@ private function addService($definition, $id, \DOMElement $parent) if ($callable = $definition->getConfigurator()) { $configurator = $this->document->createElement('configurator'); - if (is_array($callable) && $callable[0] instanceof Definition) { + if (\is_array($callable) && $callable[0] instanceof Definition) { $this->addService($callable[0], null, $configurator); $configurator->setAttribute('method', $callable[1]); - } elseif (is_array($callable)) { + } elseif (\is_array($callable)) { $configurator->setAttribute($callable[0] instanceof Reference ? 'service' : 'class', $callable[0]); $configurator->setAttribute('method', $callable[1]); } else { @@ -261,7 +261,7 @@ private function addServices(\DOMElement $parent) */ private function convertParameters(array $parameters, $type, \DOMElement $parent, $keyAttribute = 'key') { - $withKeys = array_keys($parameters) !== range(0, count($parameters) - 1); + $withKeys = array_keys($parameters) !== range(0, \count($parameters) - 1); foreach ($parameters as $key => $value) { $element = $this->document->createElement($type); if ($withKeys) { @@ -271,7 +271,7 @@ private function convertParameters(array $parameters, $type, \DOMElement $parent if ($value instanceof ServiceClosureArgument) { $value = $value->getValues()[0]; } - if (is_array($value)) { + if (\is_array($value)) { $element->setAttribute('type', 'collection'); $this->convertParameters($value, $type, $element, 'key'); } elseif ($value instanceof TaggedIteratorArgument) { @@ -303,7 +303,7 @@ private function convertParameters(array $parameters, $type, \DOMElement $parent $text = $this->document->createTextNode(self::phpToXml(base64_encode($value))); $element->appendChild($text); } else { - if (in_array($value, array('null', 'true', 'false'), true)) { + if (\in_array($value, ['null', 'true', 'false'], true)) { $element->setAttribute('type', 'string'); } $text = $this->document->createTextNode(self::phpToXml($value)); @@ -320,11 +320,11 @@ private function convertParameters(array $parameters, $type, \DOMElement $parent */ private function escape(array $arguments) { - $args = array(); + $args = []; foreach ($arguments as $k => $v) { - if (is_array($v)) { + if (\is_array($v)) { $args[$k] = $this->escape($v); - } elseif (is_string($v)) { + } elseif (\is_string($v)) { $args[$k] = str_replace('%', '%%', $v); } else { $args[$k] = $v; @@ -354,7 +354,7 @@ public static function phpToXml($value) return 'false'; case $value instanceof Parameter: return '%'.$value.'%'; - case is_object($value) || is_resource($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; diff --git a/Dumper/YamlDumper.php b/Dumper/YamlDumper.php index 8fa341bca..23b4ff79e 100644 --- a/Dumper/YamlDumper.php +++ b/Dumper/YamlDumper.php @@ -11,10 +11,6 @@ namespace Symfony\Component\DependencyInjection\Dumper; -use Symfony\Component\Yaml\Dumper as YmlDumper; -use Symfony\Component\Yaml\Parser; -use Symfony\Component\Yaml\Tag\TaggedValue; -use Symfony\Component\Yaml\Yaml; use Symfony\Component\DependencyInjection\Alias; use Symfony\Component\DependencyInjection\Argument\ArgumentInterface; use Symfony\Component\DependencyInjection\Argument\IteratorArgument; @@ -22,10 +18,14 @@ 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\DependencyInjection\Exception\RuntimeException; 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. @@ -41,7 +41,7 @@ class YamlDumper extends Dumper * * @return string A YAML string representing of the service container */ - public function dump(array $options = array()) + 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.'); @@ -72,7 +72,7 @@ private function addService(string $id, Definition $definition): string $tagsCode = ''; foreach ($definition->getTags() as $name => $tags) { foreach ($tags as $attributes) { - $att = array(); + $att = []; foreach ($attributes as $key => $value) { $att[] = sprintf('%s: %s', $this->dumper->dump($key), $this->dumper->dump($value)); } @@ -94,7 +94,7 @@ private function addService(string $id, Definition $definition): string } if ($definition->isDeprecated()) { - $code .= sprintf(" deprecated: %s\n", $definition->getDeprecationMessage('%service_id%')); + $code .= sprintf(" deprecated: %s\n", $this->dumper->dump($definition->getDeprecationMessage('%service_id%'))); } if ($definition->isAutowired()) { @@ -190,7 +190,7 @@ private function addParameters(): string $parameters = $this->prepareParameters($this->container->getParameterBag()->all(), $this->container->isCompiled()); - return $this->dumper->dump(array('parameters' => $parameters), 2); + return $this->dumper->dump(['parameters' => $parameters], 2); } /** @@ -202,11 +202,11 @@ private function addParameters(): string */ private function dumpCallable($callable) { - if (is_array($callable)) { + if (\is_array($callable)) { if ($callable[0] instanceof Reference) { - $callable = array($this->getServiceCall((string) $callable[0], $callable[0]), $callable[1]); + $callable = [$this->getServiceCall((string) $callable[0], $callable[0]), $callable[1]]; } else { - $callable = array($callable[0], $callable[1]); + $callable = [$callable[0], $callable[1]]; } } @@ -234,14 +234,14 @@ private function dumpValue($value) if ($value instanceof IteratorArgument) { $tag = 'iterator'; } else { - throw new RuntimeException(sprintf('Unspecified Yaml tag for type "%s".', get_class($value))); + 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 = array(); + if (\is_array($value)) { + $code = []; foreach ($value as $k => $v) { $code[$k] = $this->dumpValue($v); } @@ -255,7 +255,7 @@ private function dumpValue($value) 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)) { + } 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.'); } @@ -288,11 +288,11 @@ private function getExpressionCall($expression) private function prepareParameters(array $parameters, bool $escape = true): array { - $filtered = array(); + $filtered = []; foreach ($parameters as $key => $value) { - if (is_array($value)) { + if (\is_array($value)) { $value = $this->prepareParameters($value, $escape); - } elseif ($value instanceof Reference || is_string($value) && 0 === strpos($value, '@')) { + } elseif ($value instanceof Reference || \is_string($value) && 0 === strpos($value, '@')) { $value = '@'.$value; } @@ -304,11 +304,11 @@ private function prepareParameters(array $parameters, bool $escape = true): arra private function escape(array $arguments): array { - $args = array(); + $args = []; foreach ($arguments as $k => $v) { - if (is_array($v)) { + if (\is_array($v)) { $args[$k] = $this->escape($v); - } elseif (is_string($v)) { + } elseif (\is_string($v)) { $args[$k] = str_replace('%', '%%', $v); } else { $args[$k] = $v; diff --git a/EnvVarProcessor.php b/EnvVarProcessor.php index 43022ddb7..b62e93ae5 100644 --- a/EnvVarProcessor.php +++ b/EnvVarProcessor.php @@ -32,7 +32,7 @@ public function __construct(ContainerInterface $container) */ public static function getProvidedTypes() { - return array( + return [ 'base64' => 'string', 'bool' => 'bool', 'const' => 'bool|int|float|string|array', @@ -43,7 +43,7 @@ public static function getProvidedTypes() 'json' => 'array', 'resolve' => 'string', 'string' => 'string', - ); + ]; } /** @@ -111,11 +111,11 @@ public function getEnv($prefix, $name, \Closure $getEnv) } if ('const' === $prefix) { - if (!defined($env)) { + if (!\defined($env)) { throw new RuntimeException(sprintf('Env var "%s" maps to undefined constant "%s".', $name, $env)); } - return constant($env); + return \constant($env); } if ('base64' === $prefix) { @@ -129,8 +129,8 @@ public function getEnv($prefix, $name, \Closure $getEnv) throw new RuntimeException(sprintf('Invalid JSON in env var "%s": '.json_last_error_msg(), $name)); } - if (null !== $env && !is_array($env)) { - throw new RuntimeException(sprintf('Invalid JSON env var "%s": array or null expected, %s given.', $name, gettype($env))); + if (null !== $env && !\is_array($env)) { + throw new RuntimeException(sprintf('Invalid JSON env var "%s": array or null expected, %s given.', $name, \gettype($env))); } return $env; @@ -143,7 +143,7 @@ public function getEnv($prefix, $name, \Closure $getEnv) } $value = $this->container->getParameter($match[1]); if (!is_scalar($value)) { - throw new RuntimeException(sprintf('Parameter "%s" found when resolving env var "%s" must be scalar, "%s" given.', $match[1], $name, gettype($value))); + throw new RuntimeException(sprintf('Parameter "%s" found when resolving env var "%s" must be scalar, "%s" given.', $match[1], $name, \gettype($value))); } return $value; diff --git a/Exception/ParameterNotFoundException.php b/Exception/ParameterNotFoundException.php index 07066a928..9fdc2fd77 100644 --- a/Exception/ParameterNotFoundException.php +++ b/Exception/ParameterNotFoundException.php @@ -34,7 +34,7 @@ class ParameterNotFoundException extends InvalidArgumentException implements Not * @param string[] $alternatives Some parameter name alternatives * @param string|null $nonNestedAlternative The alternative parameter name when the user expected dot notation for nested parameters */ - public function __construct(string $key, string $sourceId = null, string $sourceKey = null, \Exception $previous = null, array $alternatives = array(), string $nonNestedAlternative = null) + public function __construct(string $key, string $sourceId = null, string $sourceKey = null, \Exception $previous = null, array $alternatives = [], string $nonNestedAlternative = null) { $this->key = $key; $this->sourceId = $sourceId; @@ -58,7 +58,7 @@ public function updateRepr() } if ($this->alternatives) { - if (1 == count($this->alternatives)) { + if (1 == \count($this->alternatives)) { $this->message .= ' Did you mean this: "'; } else { $this->message .= ' Did you mean one of these: "'; diff --git a/Exception/ServiceNotFoundException.php b/Exception/ServiceNotFoundException.php index dabd9da4a..5c63aea06 100644 --- a/Exception/ServiceNotFoundException.php +++ b/Exception/ServiceNotFoundException.php @@ -24,7 +24,7 @@ class ServiceNotFoundException extends InvalidArgumentException implements NotFo private $sourceId; private $alternatives; - public function __construct(string $id, string $sourceId = null, \Exception $previous = null, array $alternatives = array(), string $msg = null) + public function __construct(string $id, string $sourceId = null, \Exception $previous = null, array $alternatives = [], string $msg = null) { if (null !== $msg) { // no-op @@ -35,7 +35,7 @@ public function __construct(string $id, string $sourceId = null, \Exception $pre } if ($alternatives) { - if (1 == count($alternatives)) { + if (1 == \count($alternatives)) { $msg .= ' Did you mean this: "'; } else { $msg .= ' Did you mean one of these: "'; diff --git a/ExpressionLanguage.php b/ExpressionLanguage.php index a64561c3a..4be1ae708 100644 --- a/ExpressionLanguage.php +++ b/ExpressionLanguage.php @@ -26,7 +26,7 @@ class ExpressionLanguage extends BaseExpressionLanguage /** * {@inheritdoc} */ - public function __construct(CacheItemPoolInterface $cache = null, array $providers = array(), callable $serviceCompiler = null) + public function __construct(CacheItemPoolInterface $cache = null, array $providers = [], callable $serviceCompiler = null) { // prepend the default provider to let users override it easily array_unshift($providers, new ExpressionLanguageProvider($serviceCompiler)); diff --git a/ExpressionLanguageProvider.php b/ExpressionLanguageProvider.php index e2084aa85..9198ca0a4 100644 --- a/ExpressionLanguageProvider.php +++ b/ExpressionLanguageProvider.php @@ -33,7 +33,7 @@ public function __construct(callable $serviceCompiler = null) public function getFunctions() { - return array( + return [ new ExpressionFunction('service', $this->serviceCompiler ?: function ($arg) { return sprintf('$this->get(%s)', $arg); }, function (array $variables, $value) { @@ -45,6 +45,6 @@ public function getFunctions() }, function (array $variables, $value) { return $variables['container']->getParameter($value); }), - ); + ]; } } diff --git a/Extension/ConfigurationExtensionInterface.php b/Extension/ConfigurationExtensionInterface.php index da590635b..c3bd8423b 100644 --- a/Extension/ConfigurationExtensionInterface.php +++ b/Extension/ConfigurationExtensionInterface.php @@ -11,8 +11,8 @@ namespace Symfony\Component\DependencyInjection\Extension; -use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\Config\Definition\ConfigurationInterface; +use Symfony\Component\DependencyInjection\ContainerBuilder; /** * ConfigurationExtensionInterface is the interface implemented by container extension classes. diff --git a/Extension/Extension.php b/Extension/Extension.php index 7bb8ae3b5..25d07ff83 100644 --- a/Extension/Extension.php +++ b/Extension/Extension.php @@ -11,12 +11,12 @@ namespace Symfony\Component\DependencyInjection\Extension; +use Symfony\Component\Config\Definition\ConfigurationInterface; +use Symfony\Component\Config\Definition\Processor; use Symfony\Component\DependencyInjection\Container; +use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Exception\BadMethodCallException; use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException; -use Symfony\Component\DependencyInjection\ContainerBuilder; -use Symfony\Component\Config\Definition\Processor; -use Symfony\Component\Config\Definition\ConfigurationInterface; /** * Provides useful features shared by many extensions. @@ -25,7 +25,7 @@ */ abstract class Extension implements ExtensionInterface, ConfigurationExtensionInterface { - private $processedConfigs = array(); + private $processedConfigs = []; /** * {@inheritdoc} @@ -65,7 +65,7 @@ public function getNamespace() */ public function getAlias() { - $className = get_class($this); + $className = \get_class($this); if ('Extension' != substr($className, -9)) { throw new BadMethodCallException('This extension does not follow the naming convention; you must overwrite the getAlias() method.'); } @@ -79,7 +79,7 @@ public function getAlias() */ public function getConfiguration(array $config, ContainerBuilder $container) { - $class = get_class($this); + $class = \get_class($this); $class = substr_replace($class, '\Configuration', strrpos($class, '\\')); $class = $container->getReflectionClass($class); @@ -116,7 +116,7 @@ final public function getProcessedConfigs() try { return $this->processedConfigs; } finally { - $this->processedConfigs = array(); + $this->processedConfigs = []; } } diff --git a/LICENSE b/LICENSE index 21d7fb9e2..a677f4376 100644 --- a/LICENSE +++ b/LICENSE @@ -1,4 +1,4 @@ -Copyright (c) 2004-2018 Fabien Potencier +Copyright (c) 2004-2019 Fabien Potencier Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal diff --git a/LazyProxy/Instantiator/RealServiceInstantiator.php b/LazyProxy/Instantiator/RealServiceInstantiator.php index cad932003..4d6a9f05a 100644 --- a/LazyProxy/Instantiator/RealServiceInstantiator.php +++ b/LazyProxy/Instantiator/RealServiceInstantiator.php @@ -28,6 +28,6 @@ class RealServiceInstantiator implements InstantiatorInterface */ public function instantiateProxy(ContainerInterface $container, Definition $definition, $id, $realInstantiator) { - return call_user_func($realInstantiator); + return $realInstantiator(); } } diff --git a/LazyProxy/ProxyHelper.php b/LazyProxy/ProxyHelper.php index d258980d6..65e432d93 100644 --- a/LazyProxy/ProxyHelper.php +++ b/LazyProxy/ProxyHelper.php @@ -31,7 +31,7 @@ public static function getTypeHint(\ReflectionFunctionAbstract $r, \ReflectionPa if (!$type) { return; } - if (!is_string($type)) { + if (!\is_string($type)) { $name = $type->getName(); if ($type->isBuiltin()) { diff --git a/Loader/ClosureLoader.php b/Loader/ClosureLoader.php index f8f2efe2e..939dd7cb7 100644 --- a/Loader/ClosureLoader.php +++ b/Loader/ClosureLoader.php @@ -11,8 +11,8 @@ namespace Symfony\Component\DependencyInjection\Loader; -use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\Config\Loader\Loader; +use Symfony\Component\DependencyInjection\ContainerBuilder; /** * ClosureLoader loads service definitions from a PHP closure. @@ -35,7 +35,7 @@ public function __construct(ContainerBuilder $container) */ public function load($resource, $type = null) { - call_user_func($resource, $this->container); + $resource($this->container); } /** diff --git a/Loader/Configurator/AbstractConfigurator.php b/Loader/Configurator/AbstractConfigurator.php index 73ca320e3..f7222d0ed 100644 --- a/Loader/Configurator/AbstractConfigurator.php +++ b/Loader/Configurator/AbstractConfigurator.php @@ -28,10 +28,10 @@ abstract class AbstractConfigurator public function __call($method, $args) { if (method_exists($this, 'set'.$method)) { - return call_user_func_array(array($this, 'set'.$method), $args); + return \call_user_func_array([$this, 'set'.$method], $args); } - throw new \BadMethodCallException(sprintf('Call to undefined method %s::%s()', get_class($this), $method)); + throw new \BadMethodCallException(sprintf('Call to undefined method %s::%s()', \get_class($this), $method)); } /** @@ -44,7 +44,7 @@ public function __call($method, $args) */ public static function processValue($value, $allowServices = false) { - if (is_array($value)) { + if (\is_array($value)) { foreach ($value as $k => $v) { $value[$k] = static::processValue($v, $allowServices); } @@ -82,6 +82,6 @@ public static function processValue($value, $allowServices = false) } } - throw new InvalidArgumentException(sprintf('Cannot use values of type "%s" in service configuration files.', is_object($value) ? get_class($value) : gettype($value))); + throw new InvalidArgumentException(sprintf('Cannot use values of type "%s" in service configuration files.', \is_object($value) ? \get_class($value) : \gettype($value))); } } diff --git a/Loader/Configurator/AbstractServiceConfigurator.php b/Loader/Configurator/AbstractServiceConfigurator.php index 3d89e2a99..9d3305e8e 100644 --- a/Loader/Configurator/AbstractServiceConfigurator.php +++ b/Loader/Configurator/AbstractServiceConfigurator.php @@ -18,9 +18,9 @@ abstract class AbstractServiceConfigurator extends AbstractConfigurator { protected $parent; protected $id; - private $defaultTags = array(); + private $defaultTags = []; - public function __construct(ServicesConfigurator $parent, Definition $definition, string $id = null, array $defaultTags = array()) + public function __construct(ServicesConfigurator $parent, Definition $definition, string $id = null, array $defaultTags = []) { $this->parent = $parent; $this->definition = $definition; @@ -36,7 +36,7 @@ public function __destruct() $this->definition->addTag($name, $attributes); } } - $this->defaultTags = array(); + $this->defaultTags = []; } /** diff --git a/Loader/Configurator/ContainerConfigurator.php b/Loader/Configurator/ContainerConfigurator.php index 8ea04119d..084d06d50 100644 --- a/Loader/Configurator/ContainerConfigurator.php +++ b/Loader/Configurator/ContainerConfigurator.php @@ -61,7 +61,7 @@ final public function extension(string $namespace, array $config) final public function import(string $resource, string $type = null, bool $ignoreErrors = false) { - $this->loader->setCurrentDir(dirname($this->path)); + $this->loader->setCurrentDir(\dirname($this->path)); $this->loader->import($resource, $type, $ignoreErrors, $this->file); } diff --git a/Loader/Configurator/DefaultsConfigurator.php b/Loader/Configurator/DefaultsConfigurator.php index 07f6b7257..b928d7586 100644 --- a/Loader/Configurator/DefaultsConfigurator.php +++ b/Loader/Configurator/DefaultsConfigurator.php @@ -32,7 +32,7 @@ class DefaultsConfigurator extends AbstractServiceConfigurator * * @throws InvalidArgumentException when an invalid tag name or attribute is provided */ - final public function tag(string $name, array $attributes = array()) + final public function tag(string $name, array $attributes = []) { if ('' === $name) { throw new InvalidArgumentException('The tag name in "_defaults" must be a non-empty string.'); diff --git a/Loader/Configurator/PrototypeConfigurator.php b/Loader/Configurator/PrototypeConfigurator.php index 573dcc51e..1f639360f 100644 --- a/Loader/Configurator/PrototypeConfigurator.php +++ b/Loader/Configurator/PrototypeConfigurator.php @@ -49,7 +49,7 @@ public function __construct(ServicesConfigurator $parent, PhpFileLoader $loader, $definition->setAutowired($defaults->isAutowired()); $definition->setAutoconfigured($defaults->isAutoconfigured()); $definition->setBindings($defaults->getBindings()); - $definition->setChanges(array()); + $definition->setChanges([]); $this->loader = $loader; $this->resource = $resource; diff --git a/Loader/Configurator/ServicesConfigurator.php b/Loader/Configurator/ServicesConfigurator.php index 978bb87a7..366828ea4 100644 --- a/Loader/Configurator/ServicesConfigurator.php +++ b/Loader/Configurator/ServicesConfigurator.php @@ -40,7 +40,7 @@ public function __construct(ContainerBuilder $container, PhpFileLoader $loader, $this->instanceof = &$instanceof; $this->anonymousHash = ContainerBuilder::hash($path ?: mt_rand()); $this->anonymousCount = &$anonymousCount; - $instanceof = array(); + $instanceof = []; } /** @@ -88,7 +88,7 @@ final public function set(?string $id, string $class = null): ServiceConfigurato $definition->setAutowired($defaults->isAutowired()); $definition->setAutoconfigured($defaults->isAutoconfigured()); $definition->setBindings($defaults->getBindings()); - $definition->setChanges(array()); + $definition->setChanges([]); $configurator = new ServiceConfigurator($this->container, $this->instanceof, $allowParent, $this, $definition, $id, $defaults->getTags()); @@ -127,7 +127,7 @@ final public function get(string $id): ServiceConfigurator $allowParent = !$this->defaults->getChanges() && empty($this->instanceof); $definition = $this->container->getDefinition($id); - return new ServiceConfigurator($this->container, $definition->getInstanceofConditionals(), $allowParent, $this, $definition, $id, array()); + return new ServiceConfigurator($this->container, $definition->getInstanceofConditionals(), $allowParent, $this, $definition, $id, []); } /** diff --git a/Loader/Configurator/Traits/CallTrait.php b/Loader/Configurator/Traits/CallTrait.php index abc14e215..8e6b17a19 100644 --- a/Loader/Configurator/Traits/CallTrait.php +++ b/Loader/Configurator/Traits/CallTrait.php @@ -25,7 +25,7 @@ trait CallTrait * * @throws InvalidArgumentException on empty $method param */ - final public function call($method, array $arguments = array()) + final public function call($method, array $arguments = []) { $this->definition->addMethodCall($method, static::processValue($arguments, true)); diff --git a/Loader/Configurator/Traits/DecorateTrait.php b/Loader/Configurator/Traits/DecorateTrait.php index 0891fd906..173ad15f0 100644 --- a/Loader/Configurator/Traits/DecorateTrait.php +++ b/Loader/Configurator/Traits/DecorateTrait.php @@ -18,8 +18,8 @@ trait DecorateTrait /** * Sets the service that this service is decorating. * - * @param null|string $id The decorated service id, use null to remove decoration - * @param null|string $renamedId The new decorated service id + * @param string|null $id The decorated service id, use null to remove decoration + * @param string|null $renamedId The new decorated service id * @param int $priority The priority of decoration * * @return $this diff --git a/Loader/Configurator/Traits/FactoryTrait.php b/Loader/Configurator/Traits/FactoryTrait.php index 12e8859ca..0d50fb747 100644 --- a/Loader/Configurator/Traits/FactoryTrait.php +++ b/Loader/Configurator/Traits/FactoryTrait.php @@ -24,7 +24,7 @@ trait FactoryTrait */ final public function factory($factory) { - if (is_string($factory) && 1 === substr_count($factory, ':')) { + if (\is_string($factory) && 1 === substr_count($factory, ':')) { $factoryParts = explode(':', $factory); throw new InvalidArgumentException(sprintf('Invalid factory "%s": the `service:method` notation is not available when using PHP-based DI configuration. Use "[ref(\'%s\'), \'%s\']" instead.', $factory, $factoryParts[0], $factoryParts[1])); diff --git a/Loader/Configurator/Traits/TagTrait.php b/Loader/Configurator/Traits/TagTrait.php index aeb8b047d..d17339f88 100644 --- a/Loader/Configurator/Traits/TagTrait.php +++ b/Loader/Configurator/Traits/TagTrait.php @@ -23,9 +23,9 @@ trait TagTrait * * @return $this */ - final public function tag($name, array $attributes = array()) + final public function tag($name, array $attributes = []) { - if (!is_string($name) || '' === $name) { + if (!\is_string($name) || '' === $name) { throw new InvalidArgumentException(sprintf('The tag name for service "%s" must be a non-empty string.', $this->id)); } diff --git a/Loader/DirectoryLoader.php b/Loader/DirectoryLoader.php index 769f1026e..a57cac3b5 100644 --- a/Loader/DirectoryLoader.php +++ b/Loader/DirectoryLoader.php @@ -49,6 +49,6 @@ public function supports($resource, $type = null) return true; } - return null === $type && is_string($resource) && '/' === substr($resource, -1); + return null === $type && \is_string($resource) && '/' === substr($resource, -1); } } diff --git a/Loader/FileLoader.php b/Loader/FileLoader.php index 83a3f4f87..289491571 100644 --- a/Loader/FileLoader.php +++ b/Loader/FileLoader.php @@ -11,13 +11,13 @@ namespace Symfony\Component\DependencyInjection\Loader; +use Symfony\Component\Config\FileLocatorInterface; +use Symfony\Component\Config\Loader\FileLoader as BaseFileLoader; +use Symfony\Component\Config\Resource\GlobResource; use Symfony\Component\DependencyInjection\ChildDefinition; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Definition; use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException; -use Symfony\Component\Config\Loader\FileLoader as BaseFileLoader; -use Symfony\Component\Config\FileLocatorInterface; -use Symfony\Component\Config\Resource\GlobResource; /** * FileLoader is the abstract class used by all built-in loaders that are file based. @@ -28,7 +28,7 @@ abstract class FileLoader extends BaseFileLoader { protected $container; protected $isLoadingInstanceof = false; - protected $instanceof = array(); + protected $instanceof = []; public function __construct(ContainerBuilder $container, FileLocatorInterface $locator) { @@ -57,8 +57,8 @@ public function registerClasses(Definition $prototype, $namespace, $resource, $e $classes = $this->findClasses($namespace, $resource, $exclude); // prepare for deep cloning $serializedPrototype = serialize($prototype); - $interfaces = array(); - $singlyImplemented = array(); + $interfaces = []; + $singlyImplemented = []; foreach ($classes as $class => $errorMessage) { if (interface_exists($class, false)) { @@ -93,7 +93,7 @@ protected function setDefinition($id, Definition $definition) { if ($this->isLoadingInstanceof) { if (!$definition instanceof ChildDefinition) { - throw new InvalidArgumentException(sprintf('Invalid type definition "%s": ChildDefinition expected, "%s" given.', $id, get_class($definition))); + throw new InvalidArgumentException(sprintf('Invalid type definition "%s": ChildDefinition expected, "%s" given.', $id, \get_class($definition))); } $this->instanceof[$id] = $definition; } else { @@ -105,7 +105,7 @@ private function findClasses($namespace, $pattern, $excludePattern) { $parameterBag = $this->container->getParameterBag(); - $excludePaths = array(); + $excludePaths = []; $excludePrefix = null; if ($excludePattern) { $excludePattern = $parameterBag->unescapeValue($parameterBag->resolveValue($excludePattern)); @@ -120,12 +120,12 @@ private function findClasses($namespace, $pattern, $excludePattern) } $pattern = $parameterBag->unescapeValue($parameterBag->resolveValue($pattern)); - $classes = array(); + $classes = []; $extRegexp = '/\\.php$/'; $prefixLen = null; foreach ($this->glob($pattern, true, $resource) as $path => $info) { if (null === $prefixLen) { - $prefixLen = strlen($resource->getPrefix()); + $prefixLen = \strlen($resource->getPrefix()); if ($excludePrefix && 0 !== strpos($excludePrefix, $resource->getPrefix())) { throw new InvalidArgumentException(sprintf('Invalid "exclude" pattern when importing classes for "%s": make sure your "exclude" pattern (%s) is a subset of the "resource" pattern (%s)', $namespace, $excludePattern, $pattern)); @@ -139,7 +139,7 @@ private function findClasses($namespace, $pattern, $excludePattern) if (!preg_match($extRegexp, $path, $m) || !$info->isReadable()) { continue; } - $class = $namespace.ltrim(str_replace('/', '\\', substr($path, $prefixLen, -strlen($m[0]))), '\\'); + $class = $namespace.ltrim(str_replace('/', '\\', substr($path, $prefixLen, -\strlen($m[0]))), '\\'); if (!preg_match('/^[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*+(?:\\\\[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*+)*+$/', $class)) { continue; diff --git a/Loader/IniFileLoader.php b/Loader/IniFileLoader.php index 6cc9a1aca..307a3eefb 100644 --- a/Loader/IniFileLoader.php +++ b/Loader/IniFileLoader.php @@ -32,14 +32,14 @@ public function load($resource, $type = null) // first pass to catch parsing errors $result = parse_ini_file($path, true); - if (false === $result || array() === $result) { + if (false === $result || [] === $result) { throw new InvalidArgumentException(sprintf('The "%s" file is not valid.', $resource)); } // real raw parsing $result = parse_ini_file($path, true, INI_SCANNER_RAW); - if (isset($result['parameters']) && is_array($result['parameters'])) { + if (isset($result['parameters']) && \is_array($result['parameters'])) { foreach ($result['parameters'] as $key => $value) { $this->container->setParameter($key, $this->phpize($value)); } @@ -51,7 +51,7 @@ public function load($resource, $type = null) */ public function supports($resource, $type = null) { - if (!is_string($resource)) { + if (!\is_string($resource)) { return false; } @@ -70,19 +70,21 @@ public function supports($resource, $type = null) private function phpize($value) { // trim on the right as comments removal keep whitespaces - $value = rtrim($value); + if ($value !== $v = rtrim($value)) { + $value = '""' === substr_replace($v, '', 1, -1) ? substr($v, 1, -1) : $v; + } $lowercaseValue = strtolower($value); switch (true) { - case defined($value): - return constant($value); + case \defined($value): + return \constant($value); case 'yes' === $lowercaseValue || 'on' === $lowercaseValue: return true; case 'no' === $lowercaseValue || 'off' === $lowercaseValue || 'none' === $lowercaseValue: return false; case isset($value[1]) && ( - ("'" === $value[0] && "'" === $value[strlen($value) - 1]) || - ('"' === $value[0] && '"' === $value[strlen($value) - 1]) + ("'" === $value[0] && "'" === $value[\strlen($value) - 1]) || + ('"' === $value[0] && '"' === $value[\strlen($value) - 1]) ): // quoted string return substr($value, 1, -1); diff --git a/Loader/PhpFileLoader.php b/Loader/PhpFileLoader.php index 022533845..033798f68 100644 --- a/Loader/PhpFileLoader.php +++ b/Loader/PhpFileLoader.php @@ -33,7 +33,7 @@ public function load($resource, $type = null) $loader = $this; $path = $this->locator->locate($resource); - $this->setCurrentDir(dirname($path)); + $this->setCurrentDir(\dirname($path)); $this->container->fileExists($path); // the closure forbids access to the private scope in the included file @@ -53,7 +53,7 @@ public function load($resource, $type = null) */ public function supports($resource, $type = null) { - if (!is_string($resource)) { + if (!\is_string($resource)) { return false; } diff --git a/Loader/XmlFileLoader.php b/Loader/XmlFileLoader.php index 3b1c3548f..36e630641 100644 --- a/Loader/XmlFileLoader.php +++ b/Loader/XmlFileLoader.php @@ -12,18 +12,18 @@ namespace Symfony\Component\DependencyInjection\Loader; use Symfony\Component\Config\Util\XmlUtils; -use Symfony\Component\DependencyInjection\Argument\TaggedIteratorArgument; -use Symfony\Component\DependencyInjection\ContainerInterface; use Symfony\Component\DependencyInjection\Alias; use Symfony\Component\DependencyInjection\Argument\BoundArgument; use Symfony\Component\DependencyInjection\Argument\IteratorArgument; -use Symfony\Component\DependencyInjection\Definition; +use Symfony\Component\DependencyInjection\Argument\TaggedIteratorArgument; use Symfony\Component\DependencyInjection\ChildDefinition; use Symfony\Component\DependencyInjection\ContainerBuilder; -use Symfony\Component\DependencyInjection\Reference; +use Symfony\Component\DependencyInjection\ContainerInterface; +use Symfony\Component\DependencyInjection\Definition; use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException; use Symfony\Component\DependencyInjection\Exception\RuntimeException; use Symfony\Component\DependencyInjection\Extension\ExtensionInterface; +use Symfony\Component\DependencyInjection\Reference; use Symfony\Component\ExpressionLanguage\Expression; /** @@ -64,7 +64,7 @@ public function load($resource, $type = null) try { $this->parseDefinitions($xml, $path, $defaults); } finally { - $this->instanceof = array(); + $this->instanceof = []; } } @@ -73,7 +73,7 @@ public function load($resource, $type = null) */ public function supports($resource, $type = null) { - if (!is_string($resource)) { + if (!\is_string($resource)) { return false; } @@ -112,7 +112,7 @@ private function parseImports(\DOMDocument $xml, $file) return; } - $defaultDirectory = dirname($file); + $defaultDirectory = \dirname($file); foreach ($imports as $import) { $this->setCurrentDir($defaultDirectory); $this->import($import->getAttribute('resource'), XmlUtils::phpize($import->getAttribute('type')) ?: null, (bool) XmlUtils::phpize($import->getAttribute('ignore-errors')), $file); @@ -133,13 +133,13 @@ private function parseDefinitions(\DOMDocument $xml, $file, $defaults) if (false === $services = $xpath->query('//container:services/container:service|//container:services/container:prototype')) { return; } - $this->setCurrentDir(dirname($file)); + $this->setCurrentDir(\dirname($file)); - $this->instanceof = array(); + $this->instanceof = []; $this->isLoadingInstanceof = true; $instanceof = $xpath->query('//container:services/container:instanceof'); foreach ($instanceof as $service) { - $this->setDefinition((string) $service->getAttribute('id'), $this->parseDefinition($service, $file, array())); + $this->setDefinition((string) $service->getAttribute('id'), $this->parseDefinition($service, $file, [])); } $this->isLoadingInstanceof = false; @@ -165,12 +165,12 @@ private function getServiceDefaults(\DOMDocument $xml, $file) $xpath->registerNamespace('container', self::NS); if (null === $defaultsNode = $xpath->query('//container:services/container:defaults')->item(0)) { - return array(); + return []; } - $defaults = array( + $defaults = [ 'tags' => $this->getChildren($defaultsNode, 'tag'), 'bind' => array_map(function ($v) { return new BoundArgument($v); }, $this->getArgumentsAsPhp($defaultsNode, 'bind', $file)), - ); + ]; foreach ($defaults['tags'] as $tag) { if ('' === $tag->getAttribute('name')) { @@ -254,10 +254,10 @@ private function parseDefinition(\DOMElement $service, $file, array $defaults) $definition->setAutoconfigured($defaults['autoconfigure']); } - $definition->setChanges(array()); + $definition->setChanges([]); } - foreach (array('class', 'public', 'shared', 'synthetic', 'lazy', 'abstract') as $key) { + foreach (['class', 'public', 'shared', 'synthetic', 'lazy', 'abstract'] as $key) { if ($value = $service->getAttribute($key)) { $method = 'set'.$key; $definition->$method(XmlUtils::phpize($value)); @@ -298,7 +298,7 @@ private function parseDefinition(\DOMElement $service, $file, array $defaults) $class = $factory->hasAttribute('class') ? $factory->getAttribute('class') : null; } - $definition->setFactory(array($class, $factory->getAttribute('method'))); + $definition->setFactory([$class, $factory->getAttribute('method')]); } } @@ -313,7 +313,7 @@ private function parseDefinition(\DOMElement $service, $file, array $defaults) $class = $configurator->getAttribute('class'); } - $definition->setConfigurator(array($class, $configurator->getAttribute('method'))); + $definition->setConfigurator([$class, $configurator->getAttribute('method')]); } } @@ -328,7 +328,7 @@ private function parseDefinition(\DOMElement $service, $file, array $defaults) } foreach ($tags as $tag) { - $parameters = array(); + $parameters = []; foreach ($tag->attributes as $name => $node) { if ('name' === $name) { continue; @@ -378,9 +378,9 @@ private function parseDefinition(\DOMElement $service, $file, array $defaults) private function parseFileToDOM($file) { try { - $dom = XmlUtils::loadFile($file, array($this, 'validateSchema')); + $dom = XmlUtils::loadFile($file, [$this, 'validateSchema']); } catch (\InvalidArgumentException $e) { - throw new InvalidArgumentException(sprintf('Unable to parse file "%s".', $file), $e->getCode(), $e); + throw new InvalidArgumentException(sprintf('Unable to parse file "%s": %s', $file, $e->getMessage()), $e->getCode(), $e); } $this->validateExtensions($dom, $file); @@ -397,9 +397,9 @@ private function parseFileToDOM($file) */ private function processAnonymousServices(\DOMDocument $xml, $file, $defaults) { - $definitions = array(); + $definitions = []; $count = 0; - $suffix = ContainerBuilder::hash($file); + $suffix = '~'.ContainerBuilder::hash($file); $xpath = new \DOMXPath($xml); $xpath->registerNamespace('container', self::NS); @@ -409,11 +409,11 @@ private function processAnonymousServices(\DOMDocument $xml, $file, $defaults) foreach ($nodes as $node) { if ($services = $this->getChildren($node, 'service')) { // give it a unique name - $id = sprintf('.%d_%s', ++$count, preg_replace('/^.*\\\\/', '', $services[0]->getAttribute('class')).'~'.$suffix); + $id = sprintf('.%d_%s', ++$count, preg_replace('/^.*\\\\/', '', $services[0]->getAttribute('class')).$suffix); $node->setAttribute('id', $id); $node->setAttribute('service', $id); - $definitions[$id] = array($services[0], $file); + $definitions[$id] = [$services[0], $file]; $services[0]->setAttribute('id', $id); // anonymous services are always private @@ -433,7 +433,7 @@ private function processAnonymousServices(\DOMDocument $xml, $file, $defaults) // resolve definitions uksort($definitions, 'strnatcmp'); foreach (array_reverse($definitions) as $id => list($domElement, $file)) { - if (null !== $definition = $this->parseDefinition($domElement, $file, array())) { + if (null !== $definition = $this->parseDefinition($domElement, $file, [])) { $this->setDefinition($id, $definition); } } @@ -451,7 +451,7 @@ private function processAnonymousServices(\DOMDocument $xml, $file, $defaults) */ private function getArgumentsAsPhp(\DOMElement $node, $name, $file, $lowercase = true, $isChildDefinition = false) { - $arguments = array(); + $arguments = []; foreach ($this->getChildren($node, $name) as $arg) { if ($arg->hasAttribute('name')) { $arg->setAttribute('key', $arg->getAttribute('name')); @@ -482,7 +482,7 @@ private function getArgumentsAsPhp(\DOMElement $node, $name, $file, $lowercase = switch ($arg->getAttribute('type')) { case 'service': - if (!$arg->getAttribute('id')) { + if ('' === $arg->getAttribute('id')) { throw new InvalidArgumentException(sprintf('Tag "<%s>" with type="service" has no or empty "id" attribute in "%s".', $name, $file)); } @@ -522,7 +522,7 @@ private function getArgumentsAsPhp(\DOMElement $node, $name, $file, $lowercase = $arguments[$key] = $arg->nodeValue; break; case 'constant': - $arguments[$key] = constant(trim($arg->nodeValue)); + $arguments[$key] = \constant(trim($arg->nodeValue)); break; default: $arguments[$key] = XmlUtils::phpize($arg->nodeValue); @@ -538,11 +538,11 @@ private function getArgumentsAsPhp(\DOMElement $node, $name, $file, $lowercase = * @param \DOMNode $node * @param mixed $name * - * @return array + * @return \DOMElement[] */ private function getChildren(\DOMNode $node, $name) { - $children = array(); + $children = []; foreach ($node->childNodes as $child) { if ($child instanceof \DOMElement && $child->localName === $name && self::NS === $child->namespaceURI) { $children[] = $child; @@ -563,11 +563,11 @@ private function getChildren(\DOMNode $node, $name) */ public function validateSchema(\DOMDocument $dom) { - $schemaLocations = array('http://symfony.com/schema/dic/services' => str_replace('\\', '/', __DIR__.'/schema/dic/services/services-1.0.xsd')); + $schemaLocations = ['http://symfony.com/schema/dic/services' => str_replace('\\', '/', __DIR__.'/schema/dic/services/services-1.0.xsd')]; if ($element = $dom->documentElement->getAttributeNS('http://www.w3.org/2001/XMLSchema-instance', 'schemaLocation')) { $items = preg_split('/\s+/', $element); - for ($i = 0, $nb = count($items); $i < $nb; $i += 2) { + for ($i = 0, $nb = \count($items); $i < $nb; $i += 2) { if (!$this->container->hasExtension($items[$i])) { continue; } @@ -576,7 +576,7 @@ public function validateSchema(\DOMDocument $dom) $path = str_replace($extension->getNamespace(), str_replace('\\', '/', $extension->getXsdValidationBasePath()).'/', $items[$i + 1]); if (!is_file($path)) { - throw new RuntimeException(sprintf('Extension "%s" references a non-existent XSD file "%s"', get_class($extension), $path)); + throw new RuntimeException(sprintf('Extension "%s" references a non-existent XSD file "%s"', \get_class($extension), $path)); } $schemaLocations[$items[$i]] = $path; @@ -584,7 +584,7 @@ public function validateSchema(\DOMDocument $dom) } } - $tmpfiles = array(); + $tmpfiles = []; $imports = ''; foreach ($schemaLocations as $namespace => $location) { $parts = explode('/', $location); @@ -600,7 +600,7 @@ public function validateSchema(\DOMDocument $dom) $locationstart = 'phar:///'; } } - $drive = '\\' === DIRECTORY_SEPARATOR ? array_shift($parts).'/' : ''; + $drive = '\\' === \DIRECTORY_SEPARATOR ? array_shift($parts).'/' : ''; $location = $locationstart.$drive.implode('/', array_map('rawurlencode', $parts)); $imports .= sprintf(' '."\n", $namespace, $location); @@ -639,7 +639,7 @@ public function validateSchema(\DOMDocument $dom) private function validateAlias(\DOMElement $alias, $file) { foreach ($alias->attributes as $name => $node) { - if (!in_array($name, array('alias', 'id', 'public'))) { + if (!\in_array($name, ['alias', 'id', 'public'])) { throw new InvalidArgumentException(sprintf('Invalid attribute "%s" defined for alias "%s" in "%s".', $name, $alias->getAttribute('id'), $file)); } } @@ -669,13 +669,7 @@ private function validateExtensions(\DOMDocument $dom, $file) // can it be handled by an extension? if (!$this->container->hasExtension($node->namespaceURI)) { $extensionNamespaces = array_filter(array_map(function (ExtensionInterface $ext) { return $ext->getNamespace(); }, $this->container->getExtensions())); - throw new InvalidArgumentException(sprintf( - 'There is no extension able to load the configuration for "%s" (in %s). Looked for namespace "%s", found %s', - $node->tagName, - $file, - $node->namespaceURI, - $extensionNamespaces ? sprintf('"%s"', implode('", "', $extensionNamespaces)) : 'none' - )); + throw new InvalidArgumentException(sprintf('There is no extension able to load the configuration for "%s" (in %s). Looked for namespace "%s", found %s', $node->tagName, $file, $node->namespaceURI, $extensionNamespaces ? sprintf('"%s"', implode('", "', $extensionNamespaces)) : 'none')); } } } @@ -693,8 +687,8 @@ private function loadFromExtensions(\DOMDocument $xml) } $values = static::convertDomElementToArray($node); - if (!is_array($values)) { - $values = array(); + if (!\is_array($values)) { + $values = []; } $this->container->loadFromExtension($node->namespaceURI, $values); diff --git a/Loader/YamlFileLoader.php b/Loader/YamlFileLoader.php index 6b9f12e51..550184531 100644 --- a/Loader/YamlFileLoader.php +++ b/Loader/YamlFileLoader.php @@ -20,15 +20,15 @@ use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\ContainerInterface; use Symfony\Component\DependencyInjection\Definition; -use Symfony\Component\DependencyInjection\Reference; use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException; use Symfony\Component\DependencyInjection\Exception\RuntimeException; use Symfony\Component\DependencyInjection\Extension\ExtensionInterface; +use Symfony\Component\DependencyInjection\Reference; +use Symfony\Component\ExpressionLanguage\Expression; use Symfony\Component\Yaml\Exception\ParseException; use Symfony\Component\Yaml\Parser as YamlParser; use Symfony\Component\Yaml\Tag\TaggedValue; use Symfony\Component\Yaml\Yaml; -use Symfony\Component\ExpressionLanguage\Expression; /** * YamlFileLoader loads YAML files service definitions. @@ -37,7 +37,7 @@ */ class YamlFileLoader extends FileLoader { - private static $serviceKeywords = array( + private static $serviceKeywords = [ 'alias' => 'alias', 'parent' => 'parent', 'class' => 'class', @@ -60,9 +60,9 @@ class YamlFileLoader extends FileLoader 'autowire' => 'autowire', 'autoconfigure' => 'autoconfigure', 'bind' => 'bind', - ); + ]; - private static $prototypeKeywords = array( + private static $prototypeKeywords = [ 'resource' => 'resource', 'namespace' => 'namespace', 'exclude' => 'exclude', @@ -81,9 +81,9 @@ class YamlFileLoader extends FileLoader 'autowire' => 'autowire', 'autoconfigure' => 'autoconfigure', 'bind' => 'bind', - ); + ]; - private static $instanceofKeywords = array( + private static $instanceofKeywords = [ 'shared' => 'shared', 'lazy' => 'lazy', 'public' => 'public', @@ -92,15 +92,15 @@ class YamlFileLoader extends FileLoader 'calls' => 'calls', 'tags' => 'tags', 'autowire' => 'autowire', - ); + ]; - private static $defaultsKeywords = array( + private static $defaultsKeywords = [ 'public' => 'public', 'tags' => 'tags', 'autowire' => 'autowire', 'autoconfigure' => 'autoconfigure', 'bind' => 'bind', - ); + ]; private $yamlParser; @@ -128,7 +128,7 @@ public function load($resource, $type = null) // parameters if (isset($content['parameters'])) { - if (!is_array($content['parameters'])) { + if (!\is_array($content['parameters'])) { throw new InvalidArgumentException(sprintf('The "parameters" key should contain an array in %s. Check your YAML syntax.', $path)); } @@ -142,12 +142,12 @@ public function load($resource, $type = null) // services $this->anonymousServicesCount = 0; - $this->anonymousServicesSuffix = ContainerBuilder::hash($path); - $this->setCurrentDir(dirname($path)); + $this->anonymousServicesSuffix = '~'.ContainerBuilder::hash($path); + $this->setCurrentDir(\dirname($path)); try { $this->parseDefinitions($content, $path); } finally { - $this->instanceof = array(); + $this->instanceof = []; } } @@ -156,15 +156,15 @@ public function load($resource, $type = null) */ public function supports($resource, $type = null) { - if (!is_string($resource)) { + if (!\is_string($resource)) { return false; } - if (null === $type && in_array(pathinfo($resource, PATHINFO_EXTENSION), array('yaml', 'yml'), true)) { + if (null === $type && \in_array(pathinfo($resource, PATHINFO_EXTENSION), ['yaml', 'yml'], true)) { return true; } - return in_array($type, array('yaml', 'yml'), true); + return \in_array($type, ['yaml', 'yml'], true); } private function parseImports(array $content, string $file) @@ -173,14 +173,14 @@ private function parseImports(array $content, string $file) return; } - if (!is_array($content['imports'])) { + if (!\is_array($content['imports'])) { throw new InvalidArgumentException(sprintf('The "imports" key should contain an array in %s. Check your YAML syntax.', $file)); } - $defaultDirectory = dirname($file); + $defaultDirectory = \dirname($file); foreach ($content['imports'] as $import) { - if (!is_array($import)) { - $import = array('resource' => $import); + if (!\is_array($import)) { + $import = ['resource' => $import]; } if (!isset($import['resource'])) { throw new InvalidArgumentException(sprintf('An import should provide a resource in %s. Check your YAML syntax.', $file)); @@ -197,7 +197,7 @@ private function parseDefinitions(array $content, string $file) return; } - if (!is_array($content['services'])) { + if (!\is_array($content['services'])) { throw new InvalidArgumentException(sprintf('The "services" key should contain an array in %s. Check your YAML syntax.', $file)); } @@ -205,19 +205,19 @@ private function parseDefinitions(array $content, string $file) $instanceof = $content['services']['_instanceof']; unset($content['services']['_instanceof']); - if (!is_array($instanceof)) { - throw new InvalidArgumentException(sprintf('Service "_instanceof" key must be an array, "%s" given in "%s".', gettype($instanceof), $file)); + if (!\is_array($instanceof)) { + throw new InvalidArgumentException(sprintf('Service "_instanceof" key must be an array, "%s" given in "%s".', \gettype($instanceof), $file)); } - $this->instanceof = array(); + $this->instanceof = []; $this->isLoadingInstanceof = true; foreach ($instanceof as $id => $service) { - if (!$service || !is_array($service)) { + if (!$service || !\is_array($service)) { throw new InvalidArgumentException(sprintf('Type definition "%s" must be a non-empty array within "_instanceof" in %s. Check your YAML syntax.', $id, $file)); } - if (is_string($service) && 0 === strpos($service, '@')) { + if (\is_string($service) && 0 === strpos($service, '@')) { throw new InvalidArgumentException(sprintf('Type definition "%s" cannot be an alias within "_instanceof" in %s. Check your YAML syntax.', $id, $file)); } - $this->parseDefinition($id, $service, $file, array()); + $this->parseDefinition($id, $service, $file, []); } } @@ -234,13 +234,13 @@ private function parseDefinitions(array $content, string $file) private function parseDefaults(array &$content, string $file): array { if (!array_key_exists('_defaults', $content['services'])) { - return array(); + return []; } $defaults = $content['services']['_defaults']; unset($content['services']['_defaults']); - if (!is_array($defaults)) { - throw new InvalidArgumentException(sprintf('Service "_defaults" key must be an array, "%s" given in "%s".', gettype($defaults), $file)); + if (!\is_array($defaults)) { + throw new InvalidArgumentException(sprintf('Service "_defaults" key must be an array, "%s" given in "%s".', \gettype($defaults), $file)); } foreach ($defaults as $key => $default) { @@ -250,13 +250,13 @@ private function parseDefaults(array &$content, string $file): array } if (isset($defaults['tags'])) { - if (!is_array($tags = $defaults['tags'])) { + if (!\is_array($tags = $defaults['tags'])) { throw new InvalidArgumentException(sprintf('Parameter "tags" in "_defaults" must be an array in %s. Check your YAML syntax.', $file)); } foreach ($tags as $tag) { - if (!is_array($tag)) { - $tag = array('name' => $tag); + if (!\is_array($tag)) { + $tag = ['name' => $tag]; } if (!isset($tag['name'])) { @@ -265,7 +265,7 @@ private function parseDefaults(array &$content, string $file): array $name = $tag['name']; unset($tag['name']); - if (!is_string($name) || '' === $name) { + if (!\is_string($name) || '' === $name) { throw new InvalidArgumentException(sprintf('The tag name in "_defaults" must be a non-empty string in %s.', $file)); } @@ -278,7 +278,7 @@ private function parseDefaults(array &$content, string $file): array } if (isset($defaults['bind'])) { - if (!is_array($defaults['bind'])) { + if (!\is_array($defaults['bind'])) { throw new InvalidArgumentException(sprintf('Parameter "bind" in "_defaults" must be an array in %s. Check your YAML syntax.', $file)); } @@ -291,7 +291,7 @@ private function parseDefaults(array &$content, string $file): array private function isUsingShortSyntax(array $service): bool { foreach ($service as $key => $value) { - if (is_string($key) && ('' === $key || '$' !== $key[0])) { + if (\is_string($key) && ('' === $key || '$' !== $key[0])) { return false; } } @@ -315,7 +315,7 @@ private function parseDefinition($id, $service, $file, array $defaults) throw new InvalidArgumentException(sprintf('Service names that start with an underscore are reserved. Rename the "%s" service or define it in XML instead.', $id)); } - if (is_string($service) && 0 === strpos($service, '@')) { + if (\is_string($service) && 0 === strpos($service, '@')) { $this->container->setAlias($id, $alias = new Alias(substr($service, 1))); if (isset($defaults['public'])) { $alias->setPublic($defaults['public']); @@ -324,16 +324,16 @@ private function parseDefinition($id, $service, $file, array $defaults) return; } - if (is_array($service) && $this->isUsingShortSyntax($service)) { - $service = array('arguments' => $service); + if (\is_array($service) && $this->isUsingShortSyntax($service)) { + $service = ['arguments' => $service]; } if (null === $service) { - $service = array(); + $service = []; } - if (!is_array($service)) { - throw new InvalidArgumentException(sprintf('A service definition must be an array or a string starting with "@" but %s found for service "%s" in %s. Check your YAML syntax.', gettype($service), $id, $file)); + if (!\is_array($service)) { + throw new InvalidArgumentException(sprintf('A service definition must be an array or a string starting with "@" but %s found for service "%s" in %s. Check your YAML syntax.', \gettype($service), $id, $file)); } $this->checkDefinition($id, $service, $file); @@ -347,7 +347,7 @@ private function parseDefinition($id, $service, $file, array $defaults) } foreach ($service as $key => $value) { - if (!in_array($key, array('alias', 'public'))) { + if (!\in_array($key, ['alias', 'public'])) { throw new InvalidArgumentException(sprintf('The configuration key "%s" is unsupported for the service "%s" which is defined as an alias in "%s". Allowed configuration keys for service aliases are "alias" and "public".', $key, $id, $file)); } } @@ -390,7 +390,7 @@ private function parseDefinition($id, $service, $file, array $defaults) $definition->setAutoconfigured($defaults['autoconfigure']); } - $definition->setChanges(array()); + $definition->setChanges([]); } if (isset($service['class'])) { @@ -442,28 +442,28 @@ private function parseDefinition($id, $service, $file, array $defaults) } if (isset($service['calls'])) { - if (!is_array($service['calls'])) { + if (!\is_array($service['calls'])) { throw new InvalidArgumentException(sprintf('Parameter "calls" must be an array for service "%s" in %s. Check your YAML syntax.', $id, $file)); } foreach ($service['calls'] as $call) { if (isset($call['method'])) { $method = $call['method']; - $args = isset($call['arguments']) ? $this->resolveServices($call['arguments'], $file) : array(); + $args = isset($call['arguments']) ? $this->resolveServices($call['arguments'], $file) : []; } else { $method = $call[0]; - $args = isset($call[1]) ? $this->resolveServices($call[1], $file) : array(); + $args = isset($call[1]) ? $this->resolveServices($call[1], $file) : []; } - if (!is_array($args)) { + if (!\is_array($args)) { throw new InvalidArgumentException(sprintf('The second parameter for function call "%s" must be an array of its arguments for service "%s" in %s. Check your YAML syntax.', $method, $id, $file)); } $definition->addMethodCall($method, $args); } } - $tags = isset($service['tags']) ? $service['tags'] : array(); - if (!is_array($tags)) { + $tags = isset($service['tags']) ? $service['tags'] : []; + if (!\is_array($tags)) { throw new InvalidArgumentException(sprintf('Parameter "tags" must be an array for service "%s" in %s. Check your YAML syntax.', $id, $file)); } @@ -472,8 +472,8 @@ private function parseDefinition($id, $service, $file, array $defaults) } foreach ($tags as $tag) { - if (!is_array($tag)) { - $tag = array('name' => $tag); + if (!\is_array($tag)) { + $tag = ['name' => $tag]; } if (!isset($tag['name'])) { @@ -482,7 +482,7 @@ private function parseDefinition($id, $service, $file, array $defaults) $name = $tag['name']; unset($tag['name']); - if (!is_string($name) || '' === $name) { + if (!\is_string($name) || '' === $name) { throw new InvalidArgumentException(sprintf('The tag name for service "%s" in %s must be a non-empty string.', $id, $file)); } @@ -511,10 +511,10 @@ private function parseDefinition($id, $service, $file, array $defaults) if (isset($defaults['bind']) || isset($service['bind'])) { // deep clone, to avoid multiple process of the same instance in the passes - $bindings = isset($defaults['bind']) ? unserialize(serialize($defaults['bind'])) : array(); + $bindings = isset($defaults['bind']) ? unserialize(serialize($defaults['bind'])) : []; if (isset($service['bind'])) { - if (!is_array($service['bind'])) { + if (!\is_array($service['bind'])) { throw new InvalidArgumentException(sprintf('Parameter "bind" must be an array for service "%s" in %s. Check your YAML syntax.', $id, $file)); } @@ -537,7 +537,7 @@ private function parseDefinition($id, $service, $file, array $defaults) } if (array_key_exists('resource', $service)) { - if (!is_string($service['resource'])) { + if (!\is_string($service['resource'])) { throw new InvalidArgumentException(sprintf('A "resource" attribute must be of type string for service "%s" in %s. Check your YAML syntax.', $id, $file)); } $exclude = isset($service['exclude']) ? $service['exclude'] : null; @@ -556,13 +556,13 @@ private function parseDefinition($id, $service, $file, array $defaults) * @param string $id A service identifier * @param string $file A parsed file * - * @throws InvalidArgumentException When errors are occuried + * @throws InvalidArgumentException When errors occur * * @return string|array A parsed callable */ private function parseCallable($callable, $parameter, $id, $file) { - if (is_string($callable)) { + if (\is_string($callable)) { if ('' !== $callable && '@' === $callable[0]) { throw new InvalidArgumentException(sprintf('The value of the "%s" option for the "%s" service must be the id of the service without the "@" prefix (replace "%s" with "%s").', $parameter, $id, $callable, substr($callable, 1))); } @@ -570,15 +570,15 @@ private function parseCallable($callable, $parameter, $id, $file) if (false !== strpos($callable, ':') && false === strpos($callable, '::')) { $parts = explode(':', $callable); - return array($this->resolveServices('@'.$parts[0], $file), $parts[1]); + return [$this->resolveServices('@'.$parts[0], $file), $parts[1]]; } return $callable; } - if (is_array($callable)) { + if (\is_array($callable)) { if (isset($callable[0]) && isset($callable[1])) { - return array($this->resolveServices($callable[0], $file), $callable[1]); + return [$this->resolveServices($callable[0], $file), $callable[1]]; } if ('factory' === $parameter && isset($callable[1]) && null === $callable[0]) { @@ -621,7 +621,7 @@ protected function loadFile($file) try { $configuration = $this->yamlParser->parseFile($file, Yaml::PARSE_CONSTANT | Yaml::PARSE_CUSTOM_TAGS); } catch (ParseException $e) { - throw new InvalidArgumentException(sprintf('The file "%s" does not contain valid YAML.', $file), 0, $e); + throw new InvalidArgumentException(sprintf('The file "%s" does not contain valid YAML: %s', $file, $e->getMessage()), 0, $e); } return $this->validate($configuration, $file); @@ -643,24 +643,18 @@ private function validate($content, $file) return $content; } - if (!is_array($content)) { + if (!\is_array($content)) { throw new InvalidArgumentException(sprintf('The service file "%s" is not valid. It should contain an array. Check your YAML syntax.', $file)); } foreach ($content as $namespace => $data) { - if (in_array($namespace, array('imports', 'parameters', 'services'))) { + if (\in_array($namespace, ['imports', 'parameters', 'services'])) { continue; } if (!$this->container->hasExtension($namespace)) { $extensionNamespaces = array_filter(array_map(function (ExtensionInterface $ext) { return $ext->getAlias(); }, $this->container->getExtensions())); - throw new InvalidArgumentException(sprintf( - 'There is no extension able to load the configuration for "%s" (in %s). Looked for namespace "%s", found %s', - $namespace, - $file, - $namespace, - $extensionNamespaces ? sprintf('"%s"', implode('", "', $extensionNamespaces)) : 'none' - )); + throw new InvalidArgumentException(sprintf('There is no extension able to load the configuration for "%s" (in %s). Looked for namespace "%s", found %s', $namespace, $file, $namespace, $extensionNamespaces ? sprintf('"%s"', implode('", "', $extensionNamespaces)) : 'none')); } } @@ -681,7 +675,7 @@ private function resolveServices($value, $file, $isParameter = false) if ($value instanceof TaggedValue) { $argument = $value->getValue(); if ('iterator' === $value->getTag()) { - if (!is_array($argument)) { + if (!\is_array($argument)) { throw new InvalidArgumentException(sprintf('"!iterator" tag only accepts sequences in "%s".', $file)); } $argument = $this->resolveServices($argument, $file, $isParameter); @@ -692,7 +686,7 @@ private function resolveServices($value, $file, $isParameter = false) } } if ('tagged' === $value->getTag()) { - if (!is_string($argument) || !$argument) { + if (!\is_string($argument) || !$argument) { throw new InvalidArgumentException(sprintf('"!tagged" tag only accepts non empty string in "%s".', $file)); } @@ -706,10 +700,10 @@ private function resolveServices($value, $file, $isParameter = false) $isLoadingInstanceof = $this->isLoadingInstanceof; $this->isLoadingInstanceof = false; $instanceof = $this->instanceof; - $this->instanceof = array(); + $this->instanceof = []; $id = sprintf('.%d_%s', ++$this->anonymousServicesCount, preg_replace('/^.*\\\\/', '', isset($argument['class']) ? $argument['class'] : '').$this->anonymousServicesSuffix); - $this->parseDefinition($id, $argument, $file, array()); + $this->parseDefinition($id, $argument, $file, []); if (!$this->container->hasDefinition($id)) { throw new InvalidArgumentException(sprintf('Creating an alias using the tag "!service" is not allowed in "%s".', $file)); @@ -726,17 +720,17 @@ private function resolveServices($value, $file, $isParameter = false) throw new InvalidArgumentException(sprintf('Unsupported tag "!%s".', $value->getTag())); } - if (is_array($value)) { + if (\is_array($value)) { foreach ($value as $k => $v) { $value[$k] = $this->resolveServices($v, $file, $isParameter); } - } elseif (is_string($value) && 0 === strpos($value, '@=')) { + } elseif (\is_string($value) && 0 === strpos($value, '@=')) { if (!class_exists(Expression::class)) { throw new \LogicException(sprintf('The "@=" expression syntax cannot be used without the ExpressionLanguage component. Try running "composer require symfony/expression-language".')); } return new Expression(substr($value, 2)); - } elseif (is_string($value) && 0 === strpos($value, '@')) { + } elseif (\is_string($value) && 0 === strpos($value, '@')) { if (0 === strpos($value, '@@')) { $value = substr($value, 1); $invalidBehavior = null; @@ -765,12 +759,12 @@ private function resolveServices($value, $file, $isParameter = false) private function loadFromExtensions(array $content) { foreach ($content as $namespace => $values) { - if (in_array($namespace, array('imports', 'parameters', 'services'))) { + if (\in_array($namespace, ['imports', 'parameters', 'services'])) { continue; } - if (!is_array($values) && null !== $values) { - $values = array(); + if (!\is_array($values) && null !== $values) { + $values = []; } $this->container->loadFromExtension($namespace, $values); @@ -788,7 +782,7 @@ private function checkDefinition($id, array $definition, $file) { if ($this->isLoadingInstanceof) { $keywords = self::$instanceofKeywords; - } elseif ($throw = (isset($definition['resource']) || isset($definition['namespace']))) { + } elseif (isset($definition['resource']) || isset($definition['namespace'])) { $keywords = self::$prototypeKeywords; } else { $keywords = self::$serviceKeywords; diff --git a/ParameterBag/EnvPlaceholderParameterBag.php b/ParameterBag/EnvPlaceholderParameterBag.php index 20fc77c8b..1a1579338 100644 --- a/ParameterBag/EnvPlaceholderParameterBag.php +++ b/ParameterBag/EnvPlaceholderParameterBag.php @@ -11,8 +11,8 @@ namespace Symfony\Component\DependencyInjection\ParameterBag; -use Symfony\Component\DependencyInjection\Exception\RuntimeException; use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException; +use Symfony\Component\DependencyInjection\Exception\RuntimeException; /** * @author Nicolas Grekas @@ -20,9 +20,9 @@ class EnvPlaceholderParameterBag extends ParameterBag { private $envPlaceholderUniquePrefix; - private $envPlaceholders = array(); - private $unusedEnvPlaceholders = array(); - private $providedTypes = array(); + private $envPlaceholders = []; + private $unusedEnvPlaceholders = []; + private $providedTypes = []; /** * {@inheritdoc} @@ -50,7 +50,7 @@ public function get($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)); + throw new RuntimeException(sprintf('The default value of an env() parameter must be scalar or null, but "%s" given to "%s".', \gettype($defaultValue), $name)); } } @@ -89,7 +89,7 @@ public function getUnusedEnvPlaceholders(): array public function clearUnusedEnvPlaceholders() { - $this->unusedEnvPlaceholders = array(); + $this->unusedEnvPlaceholders = []; } /** @@ -149,7 +149,7 @@ public function resolve() 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))); + throw new RuntimeException(sprintf('The default value of env parameter "%s" must be scalar or null, %s given.', $env, \gettype($default))); } } } diff --git a/ParameterBag/FrozenParameterBag.php b/ParameterBag/FrozenParameterBag.php index ad65ad960..a5199937e 100644 --- a/ParameterBag/FrozenParameterBag.php +++ b/ParameterBag/FrozenParameterBag.php @@ -28,7 +28,7 @@ class FrozenParameterBag extends ParameterBag * * @param array $parameters An array of parameters */ - public function __construct(array $parameters = array()) + public function __construct(array $parameters = []) { $this->parameters = $parameters; $this->resolved = true; diff --git a/ParameterBag/ParameterBag.php b/ParameterBag/ParameterBag.php index dc5a4be29..84170577f 100644 --- a/ParameterBag/ParameterBag.php +++ b/ParameterBag/ParameterBag.php @@ -11,8 +11,8 @@ namespace Symfony\Component\DependencyInjection\ParameterBag; -use Symfony\Component\DependencyInjection\Exception\ParameterNotFoundException; use Symfony\Component\DependencyInjection\Exception\ParameterCircularReferenceException; +use Symfony\Component\DependencyInjection\Exception\ParameterNotFoundException; use Symfony\Component\DependencyInjection\Exception\RuntimeException; /** @@ -22,13 +22,13 @@ */ class ParameterBag implements ParameterBagInterface { - protected $parameters = array(); + protected $parameters = []; protected $resolved = false; /** * @param array $parameters An array of parameters */ - public function __construct(array $parameters = array()) + public function __construct(array $parameters = []) { $this->add($parameters); } @@ -38,7 +38,7 @@ public function __construct(array $parameters = array()) */ public function clear() { - $this->parameters = array(); + $this->parameters = []; } /** @@ -73,21 +73,21 @@ public function get($name) throw new ParameterNotFoundException($name); } - $alternatives = array(); + $alternatives = []; foreach ($this->parameters as $key => $parameterValue) { $lev = levenshtein($name, $key); - if ($lev <= strlen($name) / 3 || false !== strpos($key, $name)) { + if ($lev <= \strlen($name) / 3 || false !== strpos($key, $name)) { $alternatives[] = $key; } } $nonNestedAlternative = null; - if (!count($alternatives) && false !== strpos($name, '.')) { + if (!\count($alternatives) && false !== strpos($name, '.')) { $namePartsLength = array_map('strlen', explode('.', $name)); $key = substr($name, 0, -1 * (1 + array_pop($namePartsLength))); - while (count($namePartsLength)) { + while (\count($namePartsLength)) { if ($this->has($key)) { - if (is_array($this->get($key))) { + if (\is_array($this->get($key))) { $nonNestedAlternative = $key; } break; @@ -141,7 +141,7 @@ public function resolve() return; } - $parameters = array(); + $parameters = []; foreach ($this->parameters as $key => $value) { try { $value = $this->resolveValue($value); @@ -169,10 +169,10 @@ public function resolve() * @throws ParameterCircularReferenceException if a circular reference if detected * @throws RuntimeException when a given parameter has a type problem */ - public function resolveValue($value, array $resolving = array()) + public function resolveValue($value, array $resolving = []) { if (\is_array($value)) { - $args = array(); + $args = []; foreach ($value as $k => $v) { $args[\is_string($k) ? $this->resolveValue($k, $resolving) : $k] = $this->resolveValue($v, $resolving); } @@ -199,7 +199,7 @@ public function resolveValue($value, array $resolving = array()) * @throws ParameterCircularReferenceException if a circular reference if detected * @throws RuntimeException when a given parameter has a type problem */ - public function resolveString($value, array $resolving = array()) + public function resolveString($value, array $resolving = []) { // we do this to deal with non string values (Boolean, integer, ...) // as the preg_replace_callback throw an exception when trying @@ -229,8 +229,8 @@ public function resolveString($value, array $resolving = array()) $resolved = $this->get($key); - 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 "%s" of type %s inside string value "%s".', $key, gettype($resolved), $value)); + 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 "%s" of type %s inside string value "%s".', $key, \gettype($resolved), $value)); } $resolved = (string) $resolved; @@ -250,12 +250,12 @@ public function isResolved() */ public function escapeValue($value) { - if (is_string($value)) { + if (\is_string($value)) { return str_replace('%', '%%', $value); } - if (is_array($value)) { - $result = array(); + if (\is_array($value)) { + $result = []; foreach ($value as $k => $v) { $result[$k] = $this->escapeValue($v); } @@ -271,12 +271,12 @@ public function escapeValue($value) */ public function unescapeValue($value) { - if (is_string($value)) { + if (\is_string($value)) { return str_replace('%%', '%', $value); } - if (is_array($value)) { - $result = array(); + if (\is_array($value)) { + $result = []; foreach ($value as $k => $v) { $result[$k] = $this->unescapeValue($v); } diff --git a/ServiceLocator.php b/ServiceLocator.php index 324cccab9..a4f5bf994 100644 --- a/ServiceLocator.php +++ b/ServiceLocator.php @@ -22,7 +22,7 @@ class ServiceLocator implements PsrContainerInterface { private $factories; - private $loading = array(); + private $loading = []; private $externalId; private $container; @@ -48,12 +48,12 @@ public function has($id) public function get($id) { if (!isset($this->factories[$id])) { - throw new ServiceNotFoundException($id, end($this->loading) ?: null, null, array(), $this->createServiceNotFoundMessage($id)); + throw new ServiceNotFoundException($id, end($this->loading) ?: null, null, [], $this->createServiceNotFoundMessage($id)); } if (isset($this->loading[$id])) { $ids = array_values($this->loading); - $ids = array_slice($this->loading, array_search($id, $ids)); + $ids = \array_slice($this->loading, array_search($id, $ids)); $ids[] = $id; throw new ServiceCircularReferenceException($id, $ids); @@ -91,42 +91,43 @@ private function createServiceNotFoundMessage($id) } $class = debug_backtrace(DEBUG_BACKTRACE_PROVIDE_OBJECT | DEBUG_BACKTRACE_IGNORE_ARGS, 3); - $class = isset($class[2]['object']) ? get_class($class[2]['object']) : null; + $class = isset($class[2]['object']) ? \get_class($class[2]['object']) : null; $externalId = $this->externalId ?: $class; - $msg = sprintf('Service "%s" not found: ', $id); + $msg = []; + $msg[] = sprintf('Service "%s" not found:', $id); if (!$this->container) { $class = null; } elseif ($this->container->has($id) || isset($this->container->getRemovedIds()[$id])) { - $msg .= 'even though it exists in the app\'s container, '; + $msg[] = 'even though it exists in the app\'s container,'; } else { try { $this->container->get($id); $class = null; } catch (ServiceNotFoundException $e) { if ($e->getAlternatives()) { - $msg .= sprintf(' did you mean %s? Anyway, ', $this->formatAlternatives($e->getAlternatives(), 'or')); + $msg[] = sprintf('did you mean %s? Anyway,', $this->formatAlternatives($e->getAlternatives(), 'or')); } else { $class = null; } } } if ($externalId) { - $msg .= sprintf('the container inside "%s" is a smaller service locator that %s', $externalId, $this->formatAlternatives()); + $msg[] = sprintf('the container inside "%s" is a smaller service locator that %s', $externalId, $this->formatAlternatives()); } else { - $msg .= sprintf('the current service locator %s', $this->formatAlternatives()); + $msg[] = sprintf('the current service locator %s', $this->formatAlternatives()); } if (!$class) { // no-op } elseif (is_subclass_of($class, ServiceSubscriberInterface::class)) { - $msg .= sprintf(' Unless you need extra laziness, try using dependency injection instead. Otherwise, you need to declare it using "%s::getSubscribedServices()".', preg_replace('/([^\\\\]++\\\\)++/', '', $class)); + $msg[] = sprintf('Unless you need extra laziness, try using dependency injection instead. Otherwise, you need to declare it using "%s::getSubscribedServices()".', preg_replace('/([^\\\\]++\\\\)++/', '', $class)); } else { - $msg .= 'Try using dependency injection instead.'; + $msg[] = 'Try using dependency injection instead.'; } - return $msg; + return implode(' ', $msg); } private function formatAlternatives(array $alternatives = null, $separator = 'and') @@ -136,7 +137,7 @@ private function formatAlternatives(array $alternatives = null, $separator = 'an if (!$alternatives = array_keys($this->factories)) { return 'is empty...'; } - $format = sprintf('only knows about the %s service%s.', $format, 1 < count($alternatives) ? 's' : ''); + $format = sprintf('only knows about the %s service%s.', $format, 1 < \count($alternatives) ? 's' : ''); } $last = array_pop($alternatives); diff --git a/ServiceSubscriberInterface.php b/ServiceSubscriberInterface.php index 7024484bd..10c238754 100644 --- a/ServiceSubscriberInterface.php +++ b/ServiceSubscriberInterface.php @@ -33,16 +33,16 @@ interface ServiceSubscriberInterface * * For mandatory dependencies: * - * * array('logger' => 'Psr\Log\LoggerInterface') means the objects use the "logger" name + * * ['logger' => 'Psr\Log\LoggerInterface'] means the objects use the "logger" name * internally to fetch a service which must implement Psr\Log\LoggerInterface. - * * array('Psr\Log\LoggerInterface') is a shortcut for - * * array('Psr\Log\LoggerInterface' => 'Psr\Log\LoggerInterface') + * * ['Psr\Log\LoggerInterface'] is a shortcut for + * * ['Psr\Log\LoggerInterface' => 'Psr\Log\LoggerInterface'] * * otherwise: * - * * array('logger' => '?Psr\Log\LoggerInterface') denotes an optional dependency - * * array('?Psr\Log\LoggerInterface') is a shortcut for - * * array('Psr\Log\LoggerInterface' => '?Psr\Log\LoggerInterface') + * * ['logger' => '?Psr\Log\LoggerInterface'] denotes an optional dependency + * * ['?Psr\Log\LoggerInterface'] is a shortcut for + * * ['Psr\Log\LoggerInterface' => '?Psr\Log\LoggerInterface'] * * @return array The required service types, optionally keyed by service names */ diff --git a/Tests/Argument/RewindableGeneratorTest.php b/Tests/Argument/RewindableGeneratorTest.php index 1415869a4..31e3f11fe 100644 --- a/Tests/Argument/RewindableGeneratorTest.php +++ b/Tests/Argument/RewindableGeneratorTest.php @@ -46,7 +46,7 @@ public function testCountUsesProvidedValueAsCallback() $this->assertSame(0, $called, 'Count callback is called lazily'); $this->assertCount(3, $generator); - count($generator); + \count($generator); $this->assertSame(1, $called, 'Count callback is called only once'); } diff --git a/Tests/ChildDefinitionTest.php b/Tests/ChildDefinitionTest.php index 7f359b94f..b1eef8d24 100644 --- a/Tests/ChildDefinitionTest.php +++ b/Tests/ChildDefinitionTest.php @@ -21,7 +21,7 @@ public function testConstructor() $def = new ChildDefinition('foo'); $this->assertSame('foo', $def->getParent()); - $this->assertSame(array(), $def->getChanges()); + $this->assertSame([], $def->getChanges()); } /** @@ -37,17 +37,17 @@ public function testSetProperty($property, $changeKey) $this->assertNull($def->$getter()); $this->assertSame($def, $def->$setter('foo')); $this->assertSame('foo', $def->$getter()); - $this->assertSame(array($changeKey => true), $def->getChanges()); + $this->assertSame([$changeKey => true], $def->getChanges()); } public function getPropertyTests() { - return array( - array('class', 'class'), - array('factory', 'factory'), - array('configurator', 'configurator'), - array('file', 'file'), - ); + return [ + ['class', 'class'], + ['factory', 'factory'], + ['configurator', 'configurator'], + ['file', 'file'], + ]; } public function testSetPublic() @@ -57,7 +57,7 @@ public function testSetPublic() $this->assertTrue($def->isPublic()); $this->assertSame($def, $def->setPublic(false)); $this->assertFalse($def->isPublic()); - $this->assertSame(array('public' => true), $def->getChanges()); + $this->assertSame(['public' => true], $def->getChanges()); } public function testSetLazy() @@ -67,7 +67,7 @@ public function testSetLazy() $this->assertFalse($def->isLazy()); $this->assertSame($def, $def->setLazy(false)); $this->assertFalse($def->isLazy()); - $this->assertSame(array('lazy' => true), $def->getChanges()); + $this->assertSame(['lazy' => true], $def->getChanges()); } public function testSetAutowired() @@ -77,16 +77,16 @@ public function testSetAutowired() $this->assertFalse($def->isAutowired()); $this->assertSame($def, $def->setAutowired(true)); $this->assertTrue($def->isAutowired()); - $this->assertSame(array('autowired' => true), $def->getChanges()); + $this->assertSame(['autowired' => true], $def->getChanges()); } public function testSetArgument() { $def = new ChildDefinition('foo'); - $this->assertSame(array(), $def->getArguments()); + $this->assertSame([], $def->getArguments()); $this->assertSame($def, $def->replaceArgument(0, 'foo')); - $this->assertSame(array('index_0' => 'foo'), $def->getArguments()); + $this->assertSame(['index_0' => 'foo'], $def->getArguments()); } /** @@ -103,7 +103,7 @@ public function testReplaceArgument() { $def = new ChildDefinition('foo'); - $def->setArguments(array(0 => 'foo', 1 => 'bar')); + $def->setArguments([0 => 'foo', 1 => 'bar']); $this->assertSame('foo', $def->getArgument(0)); $this->assertSame('bar', $def->getArgument(1)); @@ -111,11 +111,11 @@ public function testReplaceArgument() $this->assertSame('foo', $def->getArgument(0)); $this->assertSame('baz', $def->getArgument(1)); - $this->assertSame(array(0 => 'foo', 1 => 'bar', 'index_1' => 'baz'), $def->getArguments()); + $this->assertSame([0 => 'foo', 1 => 'bar', 'index_1' => 'baz'], $def->getArguments()); $this->assertSame($def, $def->replaceArgument('$bar', 'val')); $this->assertSame('val', $def->getArgument('$bar')); - $this->assertSame(array(0 => 'foo', 1 => 'bar', 'index_1' => 'baz', '$bar' => 'val'), $def->getArguments()); + $this->assertSame([0 => 'foo', 1 => 'bar', 'index_1' => 'baz', '$bar' => 'val'], $def->getArguments()); } /** @@ -125,7 +125,7 @@ public function testGetArgumentShouldCheckBounds() { $def = new ChildDefinition('foo'); - $def->setArguments(array(0 => 'foo')); + $def->setArguments([0 => 'foo']); $def->replaceArgument(0, 'foo'); $def->getArgument(1); @@ -146,6 +146,6 @@ public function testCannotCallSetAutoconfigured() public function testCannotCallSetInstanceofConditionals() { $def = new ChildDefinition('foo'); - $def->setInstanceofConditionals(array('Foo' => new ChildDefinition(''))); + $def->setInstanceofConditionals(['Foo' => new ChildDefinition('')]); } } diff --git a/Tests/Compiler/AnalyzeServiceReferencesPassTest.php b/Tests/Compiler/AnalyzeServiceReferencesPassTest.php index 7a06e10d9..0bd94a3e6 100644 --- a/Tests/Compiler/AnalyzeServiceReferencesPassTest.php +++ b/Tests/Compiler/AnalyzeServiceReferencesPassTest.php @@ -13,11 +13,11 @@ use PHPUnit\Framework\TestCase; use Symfony\Component\DependencyInjection\Argument\IteratorArgument; -use Symfony\Component\DependencyInjection\Definition; use Symfony\Component\DependencyInjection\Compiler\AnalyzeServiceReferencesPass; use Symfony\Component\DependencyInjection\Compiler\RepeatedPass; -use Symfony\Component\DependencyInjection\Reference; use Symfony\Component\DependencyInjection\ContainerBuilder; +use Symfony\Component\DependencyInjection\Definition; +use Symfony\Component\DependencyInjection\Reference; class AnalyzeServiceReferencesPassTest extends TestCase { @@ -32,7 +32,7 @@ public function testProcess() $b = $container ->register('b') - ->addMethodCall('setA', array($ref2 = new Reference('a'))) + ->addMethodCall('setA', [$ref2 = new Reference('a')]) ; $c = $container @@ -48,7 +48,7 @@ public function testProcess() $e = $container ->register('e') - ->setConfigurator(array($ref6 = new Reference('b'), 'methodName')) + ->setConfigurator([$ref6 = new Reference('b'), 'methodName']) ; $graph = $this->process($container); @@ -94,7 +94,7 @@ public function testProcessMarksEdgesLazyWhenReferencedFromIteratorArgument() $container ->register('c') ->addArgument($ref1 = new Reference('a')) - ->addArgument(new IteratorArgument(array($ref2 = new Reference('b')))) + ->addArgument(new IteratorArgument([$ref2 = new Reference('b')])) ; $graph = $this->process($container); @@ -119,7 +119,7 @@ public function testProcessDetectsReferencesFromInlinedDefinitions() $container ->register('b') - ->addArgument(new Definition(null, array($ref = new Reference('a')))) + ->addArgument(new Definition(null, [$ref = new Reference('a')])) ; $graph = $this->process($container); @@ -138,7 +138,7 @@ public function testProcessDetectsReferencesFromIteratorArguments() $container ->register('b') - ->addArgument(new IteratorArgument(array($ref = new Reference('a')))) + ->addArgument(new IteratorArgument([$ref = new Reference('a')])) ; $graph = $this->process($container); @@ -156,7 +156,7 @@ public function testProcessDetectsReferencesFromInlinedFactoryDefinitions() ; $factory = new Definition(); - $factory->setFactory(array(new Reference('a'), 'a')); + $factory->setFactory([new Reference('a'), 'a']); $container ->register('b') @@ -178,8 +178,8 @@ public function testProcessDoesNotSaveDuplicateReferences() ; $container ->register('b') - ->addArgument(new Definition(null, array($ref1 = new Reference('a')))) - ->addArgument(new Definition(null, array($ref2 = new Reference('a')))) + ->addArgument(new Definition(null, [$ref1 = new Reference('a')])) + ->addArgument(new Definition(null, [$ref2 = new Reference('a')])) ; $graph = $this->process($container); @@ -193,11 +193,11 @@ public function testProcessDetectsFactoryReferences() $container ->register('foo', 'stdClass') - ->setFactory(array('stdClass', 'getInstance')); + ->setFactory(['stdClass', 'getInstance']); $container ->register('bar', 'stdClass') - ->setFactory(array(new Reference('foo'), 'getInstance')); + ->setFactory([new Reference('foo'), 'getInstance']); $graph = $this->process($container); @@ -207,7 +207,7 @@ public function testProcessDetectsFactoryReferences() protected function process(ContainerBuilder $container) { - $pass = new RepeatedPass(array(new AnalyzeServiceReferencesPass())); + $pass = new RepeatedPass([new AnalyzeServiceReferencesPass()]); $pass->process($container); return $container->getCompiler()->getServiceReferenceGraph(); diff --git a/Tests/Compiler/AutoAliasServicePassTest.php b/Tests/Compiler/AutoAliasServicePassTest.php index f76001a11..d029636a7 100644 --- a/Tests/Compiler/AutoAliasServicePassTest.php +++ b/Tests/Compiler/AutoAliasServicePassTest.php @@ -25,7 +25,7 @@ public function testProcessWithMissingParameter() $container = new ContainerBuilder(); $container->register('example') - ->addTag('auto_alias', array('format' => '%non_existing%.example')); + ->addTag('auto_alias', ['format' => '%non_existing%.example']); $pass = new AutoAliasServicePass(); $pass->process($container); @@ -39,7 +39,7 @@ public function testProcessWithMissingFormat() $container = new ContainerBuilder(); $container->register('example') - ->addTag('auto_alias', array()); + ->addTag('auto_alias', []); $container->setParameter('existing', 'mysql'); $pass = new AutoAliasServicePass(); @@ -51,7 +51,7 @@ public function testProcessWithNonExistingAlias() $container = new ContainerBuilder(); $container->register('example', 'Symfony\Component\DependencyInjection\Tests\Compiler\ServiceClassDefault') - ->addTag('auto_alias', array('format' => '%existing%.example')); + ->addTag('auto_alias', ['format' => '%existing%.example']); $container->setParameter('existing', 'mysql'); $pass = new AutoAliasServicePass(); @@ -65,7 +65,7 @@ public function testProcessWithExistingAlias() $container = new ContainerBuilder(); $container->register('example', 'Symfony\Component\DependencyInjection\Tests\Compiler\ServiceClassDefault') - ->addTag('auto_alias', array('format' => '%existing%.example')); + ->addTag('auto_alias', ['format' => '%existing%.example']); $container->register('mysql.example', 'Symfony\Component\DependencyInjection\Tests\Compiler\ServiceClassMysql'); $container->setParameter('existing', 'mysql'); @@ -83,7 +83,7 @@ public function testProcessWithManualAlias() $container = new ContainerBuilder(); $container->register('example', 'Symfony\Component\DependencyInjection\Tests\Compiler\ServiceClassDefault') - ->addTag('auto_alias', array('format' => '%existing%.example')); + ->addTag('auto_alias', ['format' => '%existing%.example']); $container->register('mysql.example', 'Symfony\Component\DependencyInjection\Tests\Compiler\ServiceClassMysql'); $container->register('mariadb.example', 'Symfony\Component\DependencyInjection\Tests\Compiler\ServiceClassMariaDb'); diff --git a/Tests/Compiler/AutowirePassTest.php b/Tests/Compiler/AutowirePassTest.php index 63440e9bc..ec3f224a2 100644 --- a/Tests/Compiler/AutowirePassTest.php +++ b/Tests/Compiler/AutowirePassTest.php @@ -15,8 +15,8 @@ use Psr\Log\LoggerInterface; use Psr\Log\NullLogger; use Symfony\Component\Config\FileLocator; -use Symfony\Component\DependencyInjection\Compiler\AutowireRequiredMethodsPass; use Symfony\Component\DependencyInjection\Compiler\AutowirePass; +use Symfony\Component\DependencyInjection\Compiler\AutowireRequiredMethodsPass; use Symfony\Component\DependencyInjection\Compiler\DecoratorServicePass; use Symfony\Component\DependencyInjection\Compiler\ResolveClassPass; use Symfony\Component\DependencyInjection\ContainerBuilder; @@ -375,22 +375,22 @@ public function testSomeSpecificArgumentsAreSet() ->setAutowired(true) // set the 2nd (index 1) argument only: autowire the first and third // args are: A, Foo, Dunglas - ->setArguments(array( + ->setArguments([ 1 => new Reference('foo'), - 3 => array('bar'), - )); + 3 => ['bar'], + ]); (new ResolveClassPass())->process($container); (new AutowirePass())->process($container); $definition = $container->getDefinition('multiple'); $this->assertEquals( - array( + [ new TypedReference(A::class, A::class), new Reference('foo'), new TypedReference(Dunglas::class, Dunglas::class), - array('bar'), - ), + ['bar'], + ], $definition->getArguments() ); } @@ -406,7 +406,7 @@ public function testScalarArgsCannotBeAutowired() $container->register(A::class); $container->register(Dunglas::class); $container->register('arg_no_type_hint', __NAMESPACE__.'\MultipleArguments') - ->setArguments(array(1 => 'foo')) + ->setArguments([1 => 'foo']) ->setAutowired(true); (new ResolveClassPass())->process($container); @@ -459,12 +459,12 @@ public function testOptionalScalarArgsDontMessUpOrder() $definition = $container->getDefinition('with_optional_scalar'); $this->assertEquals( - array( + [ new TypedReference(A::class, A::class), // use the default value 'default_val', new TypedReference(Lille::class, Lille::class), - ), + ], $definition->getArguments() ); } @@ -483,10 +483,10 @@ public function testOptionalScalarArgsNotPassedIfLast() $definition = $container->getDefinition('with_optional_scalar_last'); $this->assertEquals( - array( + [ new TypedReference(A::class, A::class), new TypedReference(Lille::class, Lille::class), - ), + ], $definition->getArguments() ); } @@ -503,7 +503,7 @@ public function testOptionalArgsNoRequiredForCoreClasses() $definition = $container->getDefinition('foo'); $this->assertEquals( - array('foo.txt'), + ['foo.txt'], $definition->getArguments() ); } @@ -520,7 +520,7 @@ public function testSetterInjection() $container ->register('setter_injection', SetterInjection::class) ->setAutowired(true) - ->addMethodCall('setWithCallsConfigured', array('manual_arg1', 'manual_arg2')) + ->addMethodCall('setWithCallsConfigured', ['manual_arg1', 'manual_arg2']) ; (new ResolveClassPass())->process($container); @@ -530,18 +530,18 @@ public function testSetterInjection() $methodCalls = $container->getDefinition('setter_injection')->getMethodCalls(); $this->assertEquals( - array('setWithCallsConfigured', 'setFoo', 'setDependencies', 'setChildMethodWithoutDocBlock'), + ['setWithCallsConfigured', 'setFoo', 'setDependencies', 'setChildMethodWithoutDocBlock'], array_column($methodCalls, 0) ); // test setWithCallsConfigured args $this->assertEquals( - array('manual_arg1', 'manual_arg2'), + ['manual_arg1', 'manual_arg2'], $methodCalls[0][1] ); // test setFoo args $this->assertEquals( - array(new TypedReference(Foo::class, Foo::class)), + [new TypedReference(Foo::class, Foo::class)], $methodCalls[1][1] ); } @@ -557,7 +557,7 @@ public function testExplicitMethodInjection() $container ->register('setter_injection', SetterInjection::class) ->setAutowired(true) - ->addMethodCall('notASetter', array()) + ->addMethodCall('notASetter', []) ; (new ResolveClassPass())->process($container); @@ -567,21 +567,21 @@ public function testExplicitMethodInjection() $methodCalls = $container->getDefinition('setter_injection')->getMethodCalls(); $this->assertEquals( - array('notASetter', 'setFoo', 'setDependencies', 'setWithCallsConfigured', 'setChildMethodWithoutDocBlock'), + ['notASetter', 'setFoo', 'setDependencies', 'setWithCallsConfigured', 'setChildMethodWithoutDocBlock'], array_column($methodCalls, 0) ); $this->assertEquals( - array(new TypedReference(A::class, A::class)), + [new TypedReference(A::class, A::class)], $methodCalls[0][1] ); } public function getCreateResourceTests() { - return array( - array('IdenticalClassResource', true), - array('ClassChangedConstructorArgs', false), - ); + return [ + ['IdenticalClassResource', true], + ['ClassChangedConstructorArgs', false], + ]; } public function testIgnoreServiceWithClassNotExisting() @@ -667,12 +667,12 @@ public function testEmptyStringIsKept() $container->register(Lille::class); $container->register('foo', __NAMESPACE__.'\MultipleArgumentsOptionalScalar') ->setAutowired(true) - ->setArguments(array('', '')); + ->setArguments(['', '']); (new ResolveClassPass())->process($container); (new AutowirePass())->process($container); - $this->assertEquals(array(new TypedReference(A::class, A::class), '', new TypedReference(Lille::class, Lille::class)), $container->getDefinition('foo')->getArguments()); + $this->assertEquals([new TypedReference(A::class, A::class), '', new TypedReference(Lille::class, Lille::class)], $container->getDefinition('foo')->getArguments()); } public function testWithFactory() @@ -681,13 +681,13 @@ public function testWithFactory() $container->register(Foo::class); $definition = $container->register('a', A::class) - ->setFactory(array(A::class, 'create')) + ->setFactory([A::class, 'create']) ->setAutowired(true); (new ResolveClassPass())->process($container); (new AutowirePass())->process($container); - $this->assertEquals(array(new TypedReference(Foo::class, Foo::class)), $definition->getArguments()); + $this->assertEquals([new TypedReference(Foo::class, Foo::class)], $definition->getArguments()); } /** @@ -699,14 +699,14 @@ public function testNotWireableCalls($method, $expectedMsg) $container = new ContainerBuilder(); $foo = $container->register('foo', NotWireable::class)->setAutowired(true) - ->addMethodCall('setBar', array()) - ->addMethodCall('setOptionalNotAutowireable', array()) - ->addMethodCall('setOptionalNoTypeHint', array()) - ->addMethodCall('setOptionalArgNoAutowireable', array()) + ->addMethodCall('setBar', []) + ->addMethodCall('setOptionalNotAutowireable', []) + ->addMethodCall('setOptionalNoTypeHint', []) + ->addMethodCall('setOptionalArgNoAutowireable', []) ; if ($method) { - $foo->addMethodCall($method, array()); + $foo->addMethodCall($method, []); } if (method_exists($this, 'expectException')) { @@ -723,11 +723,11 @@ public function testNotWireableCalls($method, $expectedMsg) public function provideNotWireableCalls() { - return array( - array('setNotAutowireable', 'Cannot autowire service "foo": argument "$n" of method "Symfony\Component\DependencyInjection\Tests\Compiler\NotWireable::setNotAutowireable()" has type "Symfony\Component\DependencyInjection\Tests\Compiler\NotARealClass" but this class was not found.'), - array('setDifferentNamespace', 'Cannot autowire service "foo": argument "$n" of method "Symfony\Component\DependencyInjection\Tests\Compiler\NotWireable::setDifferentNamespace()" references class "stdClass" but no such service exists.'), - array(null, 'Invalid service "foo": method "Symfony\Component\DependencyInjection\Tests\Compiler\NotWireable::setProtectedMethod()" must be public.'), - ); + return [ + ['setNotAutowireable', 'Cannot autowire service "foo": argument "$n" of method "Symfony\Component\DependencyInjection\Tests\Compiler\NotWireable::setNotAutowireable()" has type "Symfony\Component\DependencyInjection\Tests\Compiler\NotARealClass" but this class was not found.'], + ['setDifferentNamespace', 'Cannot autowire service "foo": argument "$n" of method "Symfony\Component\DependencyInjection\Tests\Compiler\NotWireable::setDifferentNamespace()" references class "stdClass" but no such service exists.'], + [null, 'Invalid service "foo": method "Symfony\Component\DependencyInjection\Tests\Compiler\NotWireable::setProtectedMethod()" must be public.'], + ]; } /** @@ -740,7 +740,7 @@ public function testSuggestRegisteredServicesWithSimilarCase() $container->register(LesTilleuls::class, LesTilleuls::class); $container->register('foo', NotWireable::class)->setAutowired(true) - ->addMethodCall('setNotAutowireableBecauseOfATypo', array()) + ->addMethodCall('setNotAutowireableBecauseOfATypo', []) ; (new ResolveClassPass())->process($container); @@ -813,7 +813,7 @@ public function testInlineServicesAreNotCandidates() $pass = new AutowirePass(); $pass->process($container); - $this->assertSame(array(), $container->getDefinition('autowired')->getArguments()); + $this->assertSame([], $container->getDefinition('autowired')->getArguments()); } public function testAutowireDecorator() @@ -834,6 +834,29 @@ public function testAutowireDecorator() $this->assertSame(Decorator::class.'.inner', (string) $definition->getArgument(1)); } + public function testAutowireDecoratorChain() + { + $container = new ContainerBuilder(); + $container->register(LoggerInterface::class, NullLogger::class); + $container->register(Decorated::class, Decorated::class); + $container + ->register(Decorator::class, Decorator::class) + ->setDecoratedService(Decorated::class) + ->setAutowired(true) + ; + $container + ->register(DecoratedDecorator::class, DecoratedDecorator::class) + ->setDecoratedService(Decorated::class) + ->setAutowired(true) + ; + + (new DecoratorServicePass())->process($container); + (new AutowirePass())->process($container); + + $definition = $container->getDefinition(DecoratedDecorator::class); + $this->assertSame(DecoratedDecorator::class.'.inner', (string) $definition->getArgument(0)); + } + public function testAutowireDecoratorRenamedId() { $container = new ContainerBuilder(); diff --git a/Tests/Compiler/AutowireRequiredMethodsPassTest.php b/Tests/Compiler/AutowireRequiredMethodsPassTest.php index 3b067150f..644b32d20 100644 --- a/Tests/Compiler/AutowireRequiredMethodsPassTest.php +++ b/Tests/Compiler/AutowireRequiredMethodsPassTest.php @@ -12,8 +12,8 @@ namespace Symfony\Component\DependencyInjection\Tests\Compiler; use PHPUnit\Framework\TestCase; -use Symfony\Component\DependencyInjection\Compiler\ResolveClassPass; use Symfony\Component\DependencyInjection\Compiler\AutowireRequiredMethodsPass; +use Symfony\Component\DependencyInjection\Compiler\ResolveClassPass; use Symfony\Component\DependencyInjection\ContainerBuilder; require_once __DIR__.'/../Fixtures/includes/autowiring_classes.php'; @@ -32,7 +32,7 @@ public function testSetterInjection() $container ->register('setter_injection', SetterInjection::class) ->setAutowired(true) - ->addMethodCall('setWithCallsConfigured', array('manual_arg1', 'manual_arg2')); + ->addMethodCall('setWithCallsConfigured', ['manual_arg1', 'manual_arg2']); (new ResolveClassPass())->process($container); (new AutowireRequiredMethodsPass())->process($container); @@ -40,17 +40,17 @@ public function testSetterInjection() $methodCalls = $container->getDefinition('setter_injection')->getMethodCalls(); $this->assertEquals( - array('setWithCallsConfigured', 'setFoo', 'setDependencies', 'setChildMethodWithoutDocBlock'), + ['setWithCallsConfigured', 'setFoo', 'setDependencies', 'setChildMethodWithoutDocBlock'], array_column($methodCalls, 0) ); // test setWithCallsConfigured args $this->assertEquals( - array('manual_arg1', 'manual_arg2'), + ['manual_arg1', 'manual_arg2'], $methodCalls[0][1] ); // test setFoo args - $this->assertEquals(array(), $methodCalls[1][1]); + $this->assertEquals([], $methodCalls[1][1]); } public function testExplicitMethodInjection() @@ -64,7 +64,7 @@ public function testExplicitMethodInjection() $container ->register('setter_injection', SetterInjection::class) ->setAutowired(true) - ->addMethodCall('notASetter', array()); + ->addMethodCall('notASetter', []); (new ResolveClassPass())->process($container); (new AutowireRequiredMethodsPass())->process($container); @@ -72,9 +72,9 @@ public function testExplicitMethodInjection() $methodCalls = $container->getDefinition('setter_injection')->getMethodCalls(); $this->assertEquals( - array('notASetter', 'setFoo', 'setDependencies', 'setWithCallsConfigured', 'setChildMethodWithoutDocBlock'), + ['notASetter', 'setFoo', 'setDependencies', 'setWithCallsConfigured', 'setChildMethodWithoutDocBlock'], array_column($methodCalls, 0) ); - $this->assertEquals(array(), $methodCalls[0][1]); + $this->assertEquals([], $methodCalls[0][1]); } } diff --git a/Tests/Compiler/CheckArgumentsValidityPassTest.php b/Tests/Compiler/CheckArgumentsValidityPassTest.php index d121689ff..c1e47b308 100644 --- a/Tests/Compiler/CheckArgumentsValidityPassTest.php +++ b/Tests/Compiler/CheckArgumentsValidityPassTest.php @@ -24,20 +24,20 @@ public function testProcess() { $container = new ContainerBuilder(); $definition = $container->register('foo'); - $definition->setArguments(array(null, 1, 'a')); - $definition->setMethodCalls(array( - array('bar', array('a', 'b')), - array('baz', array('c', 'd')), - )); + $definition->setArguments([null, 1, 'a']); + $definition->setMethodCalls([ + ['bar', ['a', 'b']], + ['baz', ['c', 'd']], + ]); $pass = new CheckArgumentsValidityPass(); $pass->process($container); - $this->assertEquals(array(null, 1, 'a'), $container->getDefinition('foo')->getArguments()); - $this->assertEquals(array( - array('bar', array('a', 'b')), - array('baz', array('c', 'd')), - ), $container->getDefinition('foo')->getMethodCalls()); + $this->assertEquals([null, 1, 'a'], $container->getDefinition('foo')->getArguments()); + $this->assertEquals([ + ['bar', ['a', 'b']], + ['baz', ['c', 'd']], + ], $container->getDefinition('foo')->getMethodCalls()); } /** @@ -57,19 +57,19 @@ public function testException(array $arguments, array $methodCalls) public function definitionProvider() { - return array( - array(array(null, 'a' => 'a'), array()), - array(array(1 => 1), array()), - array(array(), array(array('baz', array(null, 'a' => 'a')))), - array(array(), array(array('baz', array(1 => 1)))), - ); + return [ + [[null, 'a' => 'a'], []], + [[1 => 1], []], + [[], [['baz', [null, 'a' => 'a']]]], + [[], [['baz', [1 => 1]]]], + ]; } public function testNoException() { $container = new ContainerBuilder(); $definition = $container->register('foo'); - $definition->setArguments(array(null, 'a' => 'a')); + $definition->setArguments([null, 'a' => 'a']); $pass = new CheckArgumentsValidityPass(false); $pass->process($container); diff --git a/Tests/Compiler/CheckCircularReferencesPassTest.php b/Tests/Compiler/CheckCircularReferencesPassTest.php index e8a526e72..8423c5616 100644 --- a/Tests/Compiler/CheckCircularReferencesPassTest.php +++ b/Tests/Compiler/CheckCircularReferencesPassTest.php @@ -13,11 +13,11 @@ use PHPUnit\Framework\TestCase; use Symfony\Component\DependencyInjection\Argument\IteratorArgument; -use Symfony\Component\DependencyInjection\Reference; -use Symfony\Component\DependencyInjection\Compiler\CheckCircularReferencesPass; use Symfony\Component\DependencyInjection\Compiler\AnalyzeServiceReferencesPass; +use Symfony\Component\DependencyInjection\Compiler\CheckCircularReferencesPass; use Symfony\Component\DependencyInjection\Compiler\Compiler; use Symfony\Component\DependencyInjection\ContainerBuilder; +use Symfony\Component\DependencyInjection\Reference; class CheckCircularReferencesPassTest extends TestCase { @@ -55,11 +55,11 @@ public function testProcessWithFactory() $container ->register('a', 'stdClass') - ->setFactory(array(new Reference('b'), 'getInstance')); + ->setFactory([new Reference('b'), 'getInstance']); $container ->register('b', 'stdClass') - ->setFactory(array(new Reference('a'), 'getInstance')); + ->setFactory([new Reference('a'), 'getInstance']); $this->process($container); } @@ -88,7 +88,7 @@ public function testProcessDetectsIndirectCircularReferenceWithFactory() $container ->register('b', 'stdClass') - ->setFactory(array(new Reference('c'), 'getInstance')); + ->setFactory([new Reference('c'), 'getInstance']); $container->register('c')->addArgument(new Reference('a')); @@ -112,7 +112,7 @@ public function testProcessIgnoresMethodCalls() { $container = new ContainerBuilder(); $container->register('a')->addArgument(new Reference('b')); - $container->register('b')->addMethodCall('setA', array(new Reference('a'))); + $container->register('b')->addMethodCall('setA', [new Reference('a')]); $this->process($container); @@ -135,7 +135,7 @@ public function testProcessIgnoresIteratorArguments() { $container = new ContainerBuilder(); $container->register('a')->addArgument(new Reference('b')); - $container->register('b')->addArgument(new IteratorArgument(array(new Reference('a')))); + $container->register('b')->addArgument(new IteratorArgument([new Reference('a')])); $this->process($container); @@ -147,11 +147,11 @@ protected function process(ContainerBuilder $container) { $compiler = new Compiler(); $passConfig = $compiler->getPassConfig(); - $passConfig->setOptimizationPasses(array( + $passConfig->setOptimizationPasses([ new AnalyzeServiceReferencesPass(true), new CheckCircularReferencesPass(), - )); - $passConfig->setRemovingPasses(array()); + ]); + $passConfig->setRemovingPasses([]); $compiler->compile($container); } diff --git a/Tests/Compiler/CheckDefinitionValidityPassTest.php b/Tests/Compiler/CheckDefinitionValidityPassTest.php index f698ed02d..e1dd60b66 100644 --- a/Tests/Compiler/CheckDefinitionValidityPassTest.php +++ b/Tests/Compiler/CheckDefinitionValidityPassTest.php @@ -55,10 +55,10 @@ public function testProcess() public function testValidTags() { $container = new ContainerBuilder(); - $container->register('a', 'class')->addTag('foo', array('bar' => 'baz')); - $container->register('b', 'class')->addTag('foo', array('bar' => null)); - $container->register('c', 'class')->addTag('foo', array('bar' => 1)); - $container->register('d', 'class')->addTag('foo', array('bar' => 1.1)); + $container->register('a', 'class')->addTag('foo', ['bar' => 'baz']); + $container->register('b', 'class')->addTag('foo', ['bar' => null]); + $container->register('c', 'class')->addTag('foo', ['bar' => 1]); + $container->register('d', 'class')->addTag('foo', ['bar' => 1.1]); $this->process($container); @@ -71,7 +71,7 @@ public function testValidTags() public function testInvalidTags() { $container = new ContainerBuilder(); - $container->register('a', 'class')->addTag('foo', array('bar' => array('baz' => 'baz'))); + $container->register('a', 'class')->addTag('foo', ['bar' => ['baz' => 'baz']]); $this->process($container); } diff --git a/Tests/Compiler/CheckExceptionOnInvalidReferenceBehaviorPassTest.php b/Tests/Compiler/CheckExceptionOnInvalidReferenceBehaviorPassTest.php index a3fbfcf10..38717eaf1 100644 --- a/Tests/Compiler/CheckExceptionOnInvalidReferenceBehaviorPassTest.php +++ b/Tests/Compiler/CheckExceptionOnInvalidReferenceBehaviorPassTest.php @@ -13,10 +13,10 @@ use PHPUnit\Framework\TestCase; use Symfony\Component\DependencyInjection\Argument\BoundArgument; -use Symfony\Component\DependencyInjection\Definition; use Symfony\Component\DependencyInjection\Compiler\CheckExceptionOnInvalidReferenceBehaviorPass; -use Symfony\Component\DependencyInjection\Reference; use Symfony\Component\DependencyInjection\ContainerBuilder; +use Symfony\Component\DependencyInjection\Definition; +use Symfony\Component\DependencyInjection\Reference; class CheckExceptionOnInvalidReferenceBehaviorPassTest extends TestCase { @@ -74,7 +74,7 @@ public function testProcessDefinitionWithBindings() $container ->register('b') - ->setBindings(array(new BoundArgument(new Reference('a')))) + ->setBindings([new BoundArgument(new Reference('a'))]) ; $this->process($container); diff --git a/Tests/Compiler/CheckReferenceValidityPassTest.php b/Tests/Compiler/CheckReferenceValidityPassTest.php index 231520cd7..22b6fd154 100644 --- a/Tests/Compiler/CheckReferenceValidityPassTest.php +++ b/Tests/Compiler/CheckReferenceValidityPassTest.php @@ -13,8 +13,8 @@ use PHPUnit\Framework\TestCase; use Symfony\Component\DependencyInjection\Compiler\CheckReferenceValidityPass; -use Symfony\Component\DependencyInjection\Reference; use Symfony\Component\DependencyInjection\ContainerBuilder; +use Symfony\Component\DependencyInjection\Reference; class CheckReferenceValidityPassTest extends TestCase { diff --git a/Tests/Compiler/DecoratorServicePassTest.php b/Tests/Compiler/DecoratorServicePassTest.php index 8c51df86f..d8d7587c8 100644 --- a/Tests/Compiler/DecoratorServicePassTest.php +++ b/Tests/Compiler/DecoratorServicePassTest.php @@ -13,8 +13,8 @@ use PHPUnit\Framework\TestCase; use Symfony\Component\DependencyInjection\Alias; -use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Compiler\DecoratorServicePass; +use Symfony\Component\DependencyInjection\ContainerBuilder; class DecoratorServicePassTest extends TestCase { @@ -130,18 +130,41 @@ public function testProcessMovesTagsFromDecoratedDefinitionToDecoratingDefinitio $container = new ContainerBuilder(); $container ->register('foo') - ->setTags(array('bar' => array('attr' => 'baz'))) + ->setTags(['bar' => ['attr' => 'baz']]) ; $container ->register('baz') - ->setTags(array('foobar' => array('attr' => 'bar'))) + ->setTags(['foobar' => ['attr' => 'bar']]) ->setDecoratedService('foo') ; $this->process($container); $this->assertEmpty($container->getDefinition('baz.inner')->getTags()); - $this->assertEquals(array('bar' => array('attr' => 'baz'), 'foobar' => array('attr' => 'bar')), $container->getDefinition('baz')->getTags()); + $this->assertEquals(['bar' => ['attr' => 'baz'], 'foobar' => ['attr' => 'bar']], $container->getDefinition('baz')->getTags()); + } + + public function testProcessMovesTagsFromDecoratedDefinitionToDecoratingDefinitionMultipleTimes() + { + $container = new ContainerBuilder(); + $container + ->register('foo') + ->setPublic(true) + ->setTags(['bar' => ['attr' => 'baz']]) + ; + $container + ->register('deco1') + ->setDecoratedService('foo', null, 50) + ; + $container + ->register('deco2') + ->setDecoratedService('foo', null, 2) + ; + + $this->process($container); + + $this->assertEmpty($container->getDefinition('deco1')->getTags()); + $this->assertEquals(['bar' => ['attr' => 'baz']], $container->getDefinition('deco2')->getTags()); } protected function process(ContainerBuilder $container) diff --git a/Tests/Compiler/DefinitionErrorExceptionPassTest.php b/Tests/Compiler/DefinitionErrorExceptionPassTest.php index e0585e213..ce6f0496e 100644 --- a/Tests/Compiler/DefinitionErrorExceptionPassTest.php +++ b/Tests/Compiler/DefinitionErrorExceptionPassTest.php @@ -29,9 +29,9 @@ public function testThrowsException() $def->addError('Things went wrong!'); $def->addError('Now something else!'); $container->register('foo_service_id') - ->setArguments(array( + ->setArguments([ $def, - )); + ]); $pass = new DefinitionErrorExceptionPass(); $pass->process($container); @@ -42,9 +42,9 @@ public function testNoExceptionThrown() $container = new ContainerBuilder(); $def = new Definition(); $container->register('foo_service_id') - ->setArguments(array( + ->setArguments([ $def, - )); + ]); $pass = new DefinitionErrorExceptionPass(); $pass->process($container); diff --git a/Tests/Compiler/InlineServiceDefinitionsPassTest.php b/Tests/Compiler/InlineServiceDefinitionsPassTest.php index 78556b2ed..adc6498da 100644 --- a/Tests/Compiler/InlineServiceDefinitionsPassTest.php +++ b/Tests/Compiler/InlineServiceDefinitionsPassTest.php @@ -12,14 +12,14 @@ namespace Symfony\Component\DependencyInjection\Tests\Compiler; use PHPUnit\Framework\TestCase; -use Symfony\Component\DependencyInjection\Definition; +use Symfony\Component\DependencyInjection\Argument\IteratorArgument; +use Symfony\Component\DependencyInjection\Argument\ServiceClosureArgument; use Symfony\Component\DependencyInjection\Compiler\AnalyzeServiceReferencesPass; -use Symfony\Component\DependencyInjection\Compiler\RepeatedPass; use Symfony\Component\DependencyInjection\Compiler\InlineServiceDefinitionsPass; -use Symfony\Component\DependencyInjection\Reference; +use Symfony\Component\DependencyInjection\Compiler\RepeatedPass; use Symfony\Component\DependencyInjection\ContainerBuilder; -use Symfony\Component\DependencyInjection\Argument\ServiceClosureArgument; -use Symfony\Component\DependencyInjection\Argument\IteratorArgument; +use Symfony\Component\DependencyInjection\Definition; +use Symfony\Component\DependencyInjection\Reference; class InlineServiceDefinitionsPassTest extends TestCase { @@ -33,7 +33,7 @@ public function testProcess() $container ->register('service') - ->setArguments(array(new Reference('inlinable.service'))) + ->setArguments([new Reference('inlinable.service')]) ; $this->process($container); @@ -54,7 +54,7 @@ public function testProcessDoesNotInlinesWhenAliasedServiceIsShared() $container ->register('service') - ->setArguments(array($ref = new Reference('foo'))) + ->setArguments([$ref = new Reference('foo')]) ; $this->process($container); @@ -79,7 +79,7 @@ public function testProcessDoesInlineNonSharedService() $container ->register('service') - ->setArguments(array(new Reference('foo'), $ref = new Reference('moo'), new Reference('bar'))) + ->setArguments([new Reference('foo'), $ref = new Reference('moo'), new Reference('bar')]) ; $this->process($container); @@ -103,7 +103,7 @@ public function testProcessDoesNotInlineMixedServicesLoop() $container ->register('bar') ->setPublic(false) - ->addMethodCall('setFoo', array(new Reference('foo'))) + ->addMethodCall('setFoo', [new Reference('foo')]) ; $this->process($container); @@ -126,7 +126,7 @@ public function testProcessThrowsOnNonSharedLoops() $container ->register('bar') ->setShared(false) - ->addMethodCall('setFoo', array(new Reference('foo'))) + ->addMethodCall('setFoo', [new Reference('foo')]) ; $this->process($container); @@ -173,7 +173,7 @@ public function testProcessInlinesIfMultipleReferencesButAllFromTheSameDefinitio $b = $container ->register('b') ->addArgument(new Reference('a')) - ->addArgument(new Definition(null, array(new Reference('a')))) + ->addArgument(new Definition(null, [new Reference('a')])) ; $this->process($container); @@ -193,14 +193,14 @@ public function testProcessInlinesPrivateFactoryReference() $b = $container ->register('b') ->setPublic(false) - ->setFactory(array(new Reference('a'), 'a')) + ->setFactory([new Reference('a'), 'a']) ; $container ->register('foo') - ->setArguments(array( + ->setArguments([ $ref = new Reference('b'), - )); + ]); $this->process($container); @@ -217,15 +217,15 @@ public function testProcessDoesNotInlinePrivateFactoryIfReferencedMultipleTimesW $container ->register('b') ->setPublic(false) - ->setFactory(array(new Reference('a'), 'a')) + ->setFactory([new Reference('a'), 'a']) ; $container ->register('foo') - ->setArguments(array( + ->setArguments([ $ref1 = new Reference('b'), $ref2 = new Reference('b'), - )) + ]) ; $this->process($container); @@ -243,19 +243,19 @@ public function testProcessDoesNotInlineReferenceWhenUsedByInlineFactory() $container ->register('b') ->setPublic(false) - ->setFactory(array(new Reference('a'), 'a')) + ->setFactory([new Reference('a'), 'a']) ; $inlineFactory = new Definition(); $inlineFactory->setPublic(false); - $inlineFactory->setFactory(array(new Reference('b'), 'b')); + $inlineFactory->setFactory([new Reference('b'), 'b']); $container ->register('foo') - ->setArguments(array( + ->setArguments([ $ref = new Reference('b'), $inlineFactory, - )) + ]) ; $this->process($container); @@ -274,7 +274,7 @@ public function testProcessDoesNotInlineWhenServiceIsPrivateButLazy() $container ->register('service') - ->setArguments(array($ref = new Reference('foo'))) + ->setArguments([$ref = new Reference('foo')]) ; $this->process($container); @@ -289,7 +289,7 @@ public function testProcessDoesNotInlineWhenServiceReferencesItself() $container ->register('foo') ->setPublic(false) - ->addMethodCall('foo', array($ref = new Reference('foo'))) + ->addMethodCall('foo', [$ref = new Reference('foo')]) ; $this->process($container); @@ -307,11 +307,11 @@ public function testProcessDoesNotSetLazyArgumentValuesAfterInlining() ; $container ->register('service-closure') - ->setArguments(array(new ServiceClosureArgument(new Reference('inline')))) + ->setArguments([new ServiceClosureArgument(new Reference('inline'))]) ; $container ->register('iterator') - ->setArguments(array(new IteratorArgument(array(new Reference('inline'))))) + ->setArguments([new IteratorArgument([new Reference('inline')])]) ; $this->process($container); @@ -327,7 +327,7 @@ public function testProcessDoesNotSetLazyArgumentValuesAfterInlining() protected function process(ContainerBuilder $container) { - $repeatedPass = new RepeatedPass(array(new AnalyzeServiceReferencesPass(), new InlineServiceDefinitionsPass())); + $repeatedPass = new RepeatedPass([new AnalyzeServiceReferencesPass(), new InlineServiceDefinitionsPass()]); $repeatedPass->process($container); } } diff --git a/Tests/Compiler/IntegrationTest.php b/Tests/Compiler/IntegrationTest.php index a1efc60ab..b9f9d7bf3 100644 --- a/Tests/Compiler/IntegrationTest.php +++ b/Tests/Compiler/IntegrationTest.php @@ -14,9 +14,10 @@ use PHPUnit\Framework\TestCase; use Symfony\Component\Config\FileLocator; use Symfony\Component\DependencyInjection\Alias; +use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Loader\YamlFileLoader; use Symfony\Component\DependencyInjection\Reference; -use Symfony\Component\DependencyInjection\ContainerBuilder; +use Symfony\Component\DependencyInjection\ServiceSubscriberInterface; /** * This class tests the integration of the different compiler passes. @@ -98,7 +99,7 @@ public function testProcessInlinesWhenThereAreMultipleReferencesButFromTheSameDe $container ->register('a', '\stdClass') ->addArgument(new Reference('b')) - ->addMethodCall('setC', array(new Reference('c'))) + ->addMethodCall('setC', [new Reference('c')]) ->setPublic(true) ; @@ -120,6 +121,21 @@ public function testProcessInlinesWhenThereAreMultipleReferencesButFromTheSameDe $this->assertFalse($container->hasDefinition('c'), 'Service C was not inlined.'); } + public function testCanDecorateServiceSubscriber() + { + $container = new ContainerBuilder(); + $container->register(ServiceSubscriberStub::class) + ->addTag('container.service_subscriber') + ->setPublic(true); + + $container->register(DecoratedServiceSubscriber::class) + ->setDecoratedService(ServiceSubscriberStub::class); + + $container->compile(); + + $this->assertInstanceOf(DecoratedServiceSubscriber::class, $container->get(ServiceSubscriberStub::class)); + } + /** * @dataProvider getYamlCompileTests */ @@ -142,8 +158,8 @@ public function testYamlContainerCompiles($directory, $actualServiceId, $expecte $expectedService = $container->getDefinition($expectedServiceId); // reset changes, we don't care if these differ - $actualService->setChanges(array()); - $expectedService->setChanges(array()); + $actualService->setChanges([]); + $expectedService->setChanges([]); $this->assertEquals($expectedService, $actualService); } @@ -152,74 +168,86 @@ public function getYamlCompileTests() { $container = new ContainerBuilder(); $container->registerForAutoconfiguration(IntegrationTestStub::class); - yield array( + yield [ 'autoconfigure_child_not_applied', 'child_service', 'child_service_expected', $container, - ); + ]; $container = new ContainerBuilder(); $container->registerForAutoconfiguration(IntegrationTestStub::class); - yield array( + yield [ 'autoconfigure_parent_child', 'child_service', 'child_service_expected', $container, - ); + ]; $container = new ContainerBuilder(); $container->registerForAutoconfiguration(IntegrationTestStub::class) ->addTag('from_autoconfigure'); - yield array( + yield [ 'autoconfigure_parent_child_tags', 'child_service', 'child_service_expected', $container, - ); + ]; - yield array( + yield [ 'child_parent', 'child_service', 'child_service_expected', - ); + ]; - yield array( + yield [ 'defaults_child_tags', 'child_service', 'child_service_expected', - ); + ]; - yield array( + yield [ 'defaults_instanceof_importance', 'main_service', 'main_service_expected', - ); + ]; - yield array( + yield [ 'defaults_parent_child', 'child_service', 'child_service_expected', - ); + ]; - yield array( + yield [ 'instanceof_parent_child', 'child_service', 'child_service_expected', - ); + ]; $container = new ContainerBuilder(); $container->registerForAutoconfiguration(IntegrationTestStub::class) - ->addMethodCall('setSunshine', array('supernova')); - yield array( + ->addMethodCall('setSunshine', ['supernova']); + yield [ 'instanceof_and_calls', 'main_service', 'main_service_expected', $container, - ); + ]; } } +class ServiceSubscriberStub implements ServiceSubscriberInterface +{ + public static function getSubscribedServices() + { + return []; + } +} + +class DecoratedServiceSubscriber +{ +} + class IntegrationTestStub extends IntegrationTestStubParent { } diff --git a/Tests/Compiler/MergeExtensionConfigurationPassTest.php b/Tests/Compiler/MergeExtensionConfigurationPassTest.php index 77872720a..667ae3886 100644 --- a/Tests/Compiler/MergeExtensionConfigurationPassTest.php +++ b/Tests/Compiler/MergeExtensionConfigurationPassTest.php @@ -15,8 +15,8 @@ use Symfony\Component\Config\Definition\Builder\TreeBuilder; use Symfony\Component\Config\Definition\ConfigurationInterface; use Symfony\Component\Config\Resource\FileResource; -use Symfony\Component\DependencyInjection\Compiler\MergeExtensionConfigurationPass; use Symfony\Component\DependencyInjection\Compiler\MergeExtensionConfigurationContainerBuilder; +use Symfony\Component\DependencyInjection\Compiler\MergeExtensionConfigurationPass; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Extension\Extension; use Symfony\Component\DependencyInjection\ParameterBag\ParameterBag; @@ -25,7 +25,7 @@ class MergeExtensionConfigurationPassTest extends TestCase { public function testExpressionLanguageProviderForwarding() { - $tmpProviders = array(); + $tmpProviders = []; $extension = $this->getMockBuilder('Symfony\\Component\\DependencyInjection\\Extension\\ExtensionInterface')->getMock(); $extension->expects($this->any()) @@ -46,18 +46,18 @@ public function testExpressionLanguageProviderForwarding() $provider = $this->getMockBuilder('Symfony\\Component\\ExpressionLanguage\\ExpressionFunctionProviderInterface')->getMock(); $container = new ContainerBuilder(new ParameterBag()); $container->registerExtension($extension); - $container->prependExtensionConfig('foo', array('bar' => true)); + $container->prependExtensionConfig('foo', ['bar' => true]); $container->addExpressionLanguageProvider($provider); $pass = new MergeExtensionConfigurationPass(); $pass->process($container); - $this->assertEquals(array($provider), $tmpProviders); + $this->assertEquals([$provider], $tmpProviders); } public function testExtensionLoadGetAMergeExtensionConfigurationContainerBuilderInstance() { - $extension = $this->getMockBuilder(FooExtension::class)->setMethods(array('load'))->getMock(); + $extension = $this->getMockBuilder(FooExtension::class)->setMethods(['load'])->getMock(); $extension->expects($this->once()) ->method('load') ->with($this->isType('array'), $this->isInstanceOf(MergeExtensionConfigurationContainerBuilder::class)) @@ -65,7 +65,7 @@ public function testExtensionLoadGetAMergeExtensionConfigurationContainerBuilder $container = new ContainerBuilder(new ParameterBag()); $container->registerExtension($extension); - $container->prependExtensionConfig('foo', array()); + $container->prependExtensionConfig('foo', []); $pass = new MergeExtensionConfigurationPass(); $pass->process($container); @@ -73,14 +73,14 @@ public function testExtensionLoadGetAMergeExtensionConfigurationContainerBuilder public function testExtensionConfigurationIsTrackedByDefault() { - $extension = $this->getMockBuilder(FooExtension::class)->setMethods(array('getConfiguration'))->getMock(); + $extension = $this->getMockBuilder(FooExtension::class)->setMethods(['getConfiguration'])->getMock(); $extension->expects($this->exactly(2)) ->method('getConfiguration') ->will($this->returnValue(new FooConfiguration())); $container = new ContainerBuilder(new ParameterBag()); $container->registerExtension($extension); - $container->prependExtensionConfig('foo', array('bar' => true)); + $container->prependExtensionConfig('foo', ['bar' => true]); $pass = new MergeExtensionConfigurationPass(); $pass->process($container); @@ -92,14 +92,14 @@ public function testOverriddenEnvsAreMerged() { $container = new ContainerBuilder(); $container->registerExtension(new FooExtension()); - $container->prependExtensionConfig('foo', array('bar' => '%env(FOO)%')); - $container->prependExtensionConfig('foo', array('bar' => '%env(BAR)%', 'baz' => '%env(BAZ)%')); + $container->prependExtensionConfig('foo', ['bar' => '%env(FOO)%']); + $container->prependExtensionConfig('foo', ['bar' => '%env(BAR)%', 'baz' => '%env(BAZ)%']); $pass = new MergeExtensionConfigurationPass(); $pass->process($container); - $this->assertSame(array('BAZ', 'FOO'), array_keys($container->getParameterBag()->getEnvPlaceholders())); - $this->assertSame(array('BAZ' => 1, 'FOO' => 0), $container->getEnvCounters()); + $this->assertSame(['BAZ', 'FOO'], array_keys($container->getParameterBag()->getEnvPlaceholders())); + $this->assertSame(['BAZ' => 1, 'FOO' => 0], $container->getEnvCounters()); } /** @@ -110,7 +110,7 @@ public function testProcessedEnvsAreIncompatibleWithResolve() { $container = new ContainerBuilder(); $container->registerExtension(new BarExtension()); - $container->prependExtensionConfig('bar', array()); + $container->prependExtensionConfig('bar', []); (new MergeExtensionConfigurationPass())->process($container); } @@ -119,7 +119,7 @@ public function testThrowingExtensionsGetMergedBag() { $container = new ContainerBuilder(); $container->registerExtension(new ThrowingExtension()); - $container->prependExtensionConfig('throwing', array('bar' => '%env(FOO)%')); + $container->prependExtensionConfig('throwing', ['bar' => '%env(FOO)%']); try { $pass = new MergeExtensionConfigurationPass(); @@ -128,7 +128,7 @@ public function testThrowingExtensionsGetMergedBag() } catch (\Exception $e) { } - $this->assertSame(array('FOO'), array_keys($container->getParameterBag()->getEnvPlaceholders())); + $this->assertSame(['FOO'], array_keys($container->getParameterBag()->getEnvPlaceholders())); } } diff --git a/Tests/Compiler/PassConfigTest.php b/Tests/Compiler/PassConfigTest.php index 46ec1ab12..f8556d3e0 100644 --- a/Tests/Compiler/PassConfigTest.php +++ b/Tests/Compiler/PassConfigTest.php @@ -12,8 +12,8 @@ namespace Symfony\Component\DependencyInjection\Tests\Compiler; use PHPUnit\Framework\TestCase; -use Symfony\Component\DependencyInjection\Compiler\PassConfig; use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface; +use Symfony\Component\DependencyInjection\Compiler\PassConfig; /** * @author Guilhem N @@ -23,7 +23,7 @@ class PassConfigTest extends TestCase public function testPassOrdering() { $config = new PassConfig(); - $config->setBeforeOptimizationPasses(array()); + $config->setBeforeOptimizationPasses([]); $pass1 = $this->getMockBuilder(CompilerPassInterface::class)->getMock(); $config->addPass($pass1, PassConfig::TYPE_BEFORE_OPTIMIZATION, 10); @@ -39,11 +39,11 @@ public function testPassOrdering() public function testPassOrderingWithoutPasses() { $config = new PassConfig(); - $config->setBeforeOptimizationPasses(array()); - $config->setAfterRemovingPasses(array()); - $config->setBeforeRemovingPasses(array()); - $config->setOptimizationPasses(array()); - $config->setRemovingPasses(array()); + $config->setBeforeOptimizationPasses([]); + $config->setAfterRemovingPasses([]); + $config->setBeforeRemovingPasses([]); + $config->setOptimizationPasses([]); + $config->setRemovingPasses([]); $this->assertEmpty($config->getBeforeOptimizationPasses()); $this->assertEmpty($config->getAfterRemovingPasses()); diff --git a/Tests/Compiler/PriorityTaggedServiceTraitTest.php b/Tests/Compiler/PriorityTaggedServiceTraitTest.php index dffc9b97e..57ca9af42 100644 --- a/Tests/Compiler/PriorityTaggedServiceTraitTest.php +++ b/Tests/Compiler/PriorityTaggedServiceTraitTest.php @@ -20,27 +20,27 @@ class PriorityTaggedServiceTraitTest extends TestCase { public function testThatCacheWarmersAreProcessedInPriorityOrder() { - $services = array( - 'my_service1' => array('my_custom_tag' => array('priority' => 100)), - 'my_service2' => array('my_custom_tag' => array('priority' => 200)), - 'my_service3' => array('my_custom_tag' => array('priority' => -501)), - 'my_service4' => array('my_custom_tag' => array()), - 'my_service5' => array('my_custom_tag' => array('priority' => -1)), - 'my_service6' => array('my_custom_tag' => array('priority' => -500)), - 'my_service7' => array('my_custom_tag' => array('priority' => -499)), - 'my_service8' => array('my_custom_tag' => array('priority' => 1)), - 'my_service9' => array('my_custom_tag' => array('priority' => -2)), - 'my_service10' => array('my_custom_tag' => array('priority' => -1000)), - 'my_service11' => array('my_custom_tag' => array('priority' => -1001)), - 'my_service12' => array('my_custom_tag' => array('priority' => -1002)), - 'my_service13' => array('my_custom_tag' => array('priority' => -1003)), - 'my_service14' => array('my_custom_tag' => array('priority' => -1000)), - 'my_service15' => array('my_custom_tag' => array('priority' => 1)), - 'my_service16' => array('my_custom_tag' => array('priority' => -1)), - 'my_service17' => array('my_custom_tag' => array('priority' => 200)), - 'my_service18' => array('my_custom_tag' => array('priority' => 100)), - 'my_service19' => array('my_custom_tag' => array()), - ); + $services = [ + 'my_service1' => ['my_custom_tag' => ['priority' => 100]], + 'my_service2' => ['my_custom_tag' => ['priority' => 200]], + 'my_service3' => ['my_custom_tag' => ['priority' => -501]], + 'my_service4' => ['my_custom_tag' => []], + 'my_service5' => ['my_custom_tag' => ['priority' => -1]], + 'my_service6' => ['my_custom_tag' => ['priority' => -500]], + 'my_service7' => ['my_custom_tag' => ['priority' => -499]], + 'my_service8' => ['my_custom_tag' => ['priority' => 1]], + 'my_service9' => ['my_custom_tag' => ['priority' => -2]], + 'my_service10' => ['my_custom_tag' => ['priority' => -1000]], + 'my_service11' => ['my_custom_tag' => ['priority' => -1001]], + 'my_service12' => ['my_custom_tag' => ['priority' => -1002]], + 'my_service13' => ['my_custom_tag' => ['priority' => -1003]], + 'my_service14' => ['my_custom_tag' => ['priority' => -1000]], + 'my_service15' => ['my_custom_tag' => ['priority' => 1]], + 'my_service16' => ['my_custom_tag' => ['priority' => -1]], + 'my_service17' => ['my_custom_tag' => ['priority' => 200]], + 'my_service18' => ['my_custom_tag' => ['priority' => 100]], + 'my_service19' => ['my_custom_tag' => []], + ]; $container = new ContainerBuilder(); @@ -52,7 +52,7 @@ public function testThatCacheWarmersAreProcessedInPriorityOrder() } } - $expected = array( + $expected = [ new Reference('my_service2'), new Reference('my_service17'), new Reference('my_service1'), @@ -72,7 +72,7 @@ public function testThatCacheWarmersAreProcessedInPriorityOrder() new Reference('my_service11'), new Reference('my_service12'), new Reference('my_service13'), - ); + ]; $priorityTaggedServiceTraitImplementation = new PriorityTaggedServiceTraitImplementation(); @@ -83,7 +83,7 @@ public function testWithEmptyArray() { $container = new ContainerBuilder(); $priorityTaggedServiceTraitImplementation = new PriorityTaggedServiceTraitImplementation(); - $this->assertEquals(array(), $priorityTaggedServiceTraitImplementation->test('my_custom_tag', $container)); + $this->assertEquals([], $priorityTaggedServiceTraitImplementation->test('my_custom_tag', $container)); } } diff --git a/Tests/Compiler/RegisterEnvVarProcessorsPassTest.php b/Tests/Compiler/RegisterEnvVarProcessorsPassTest.php index e330017bc..73fd8f79d 100644 --- a/Tests/Compiler/RegisterEnvVarProcessorsPassTest.php +++ b/Tests/Compiler/RegisterEnvVarProcessorsPassTest.php @@ -28,19 +28,19 @@ public function testSimpleProcessor() $this->assertTrue($container->has('container.env_var_processors_locator')); $this->assertInstanceOf(SimpleProcessor::class, $container->get('container.env_var_processors_locator')->get('foo')); - $expected = array( - 'foo' => array('string'), - 'base64' => array('string'), - 'bool' => array('bool'), - 'const' => array('bool', 'int', 'float', 'string', 'array'), - 'csv' => array('array'), - 'file' => array('string'), - 'float' => array('float'), - 'int' => array('int'), - 'json' => array('array'), - 'resolve' => array('string'), - 'string' => array('string'), - ); + $expected = [ + 'foo' => ['string'], + 'base64' => ['string'], + 'bool' => ['bool'], + 'const' => ['bool', 'int', 'float', 'string', 'array'], + 'csv' => ['array'], + 'file' => ['string'], + 'float' => ['float'], + 'int' => ['int'], + 'json' => ['array'], + 'resolve' => ['string'], + 'string' => ['string'], + ]; $this->assertSame($expected, $container->getParameterBag()->getProvidedTypes()); } @@ -76,7 +76,7 @@ public function getEnv($prefix, $name, \Closure $getEnv) public static function getProvidedTypes() { - return array('foo' => 'string'); + return ['foo' => 'string']; } } @@ -84,6 +84,6 @@ class BadProcessor extends SimpleProcessor { public static function getProvidedTypes() { - return array('foo' => 'string|foo'); + return ['foo' => 'string|foo']; } } diff --git a/Tests/Compiler/RegisterServiceSubscribersPassTest.php b/Tests/Compiler/RegisterServiceSubscribersPassTest.php index f7314948a..75342aa70 100644 --- a/Tests/Compiler/RegisterServiceSubscribersPassTest.php +++ b/Tests/Compiler/RegisterServiceSubscribersPassTest.php @@ -53,7 +53,7 @@ public function testInvalidAttributes() $container = new ContainerBuilder(); $container->register('foo', TestServiceSubscriber::class) - ->addTag('container.service_subscriber', array('bar' => '123')) + ->addTag('container.service_subscriber', ['bar' => '123']) ; (new RegisterServiceSubscribersPass())->process($container); @@ -78,12 +78,12 @@ public function testNoAttributes() $this->assertFalse($locator->isPublic()); $this->assertSame(ServiceLocator::class, $locator->getClass()); - $expected = array( + $expected = [ TestServiceSubscriber::class => new ServiceClosureArgument(new TypedReference(TestServiceSubscriber::class, TestServiceSubscriber::class)), CustomDefinition::class => new ServiceClosureArgument(new TypedReference(CustomDefinition::class, CustomDefinition::class, ContainerInterface::IGNORE_ON_INVALID_REFERENCE)), 'bar' => new ServiceClosureArgument(new TypedReference(CustomDefinition::class, CustomDefinition::class)), 'baz' => new ServiceClosureArgument(new TypedReference(CustomDefinition::class, CustomDefinition::class, ContainerInterface::IGNORE_ON_INVALID_REFERENCE)), - ); + ]; $this->assertEquals($expected, $container->getDefinition((string) $locator->getFactory()[0])->getArgument(0)); } @@ -95,8 +95,8 @@ public function testWithAttributes() $container->register('foo', TestServiceSubscriber::class) ->setAutowired(true) ->addArgument(new Reference(PsrContainerInterface::class)) - ->addTag('container.service_subscriber', array('key' => 'bar', 'id' => 'bar')) - ->addTag('container.service_subscriber', array('key' => 'bar', 'id' => 'baz')) // should be ignored: the first wins + ->addTag('container.service_subscriber', ['key' => 'bar', 'id' => 'bar']) + ->addTag('container.service_subscriber', ['key' => 'bar', 'id' => 'baz']) // should be ignored: the first wins ; (new RegisterServiceSubscribersPass())->process($container); @@ -108,12 +108,12 @@ public function testWithAttributes() $this->assertFalse($locator->isPublic()); $this->assertSame(ServiceLocator::class, $locator->getClass()); - $expected = array( + $expected = [ TestServiceSubscriber::class => new ServiceClosureArgument(new TypedReference(TestServiceSubscriber::class, TestServiceSubscriber::class)), CustomDefinition::class => new ServiceClosureArgument(new TypedReference(CustomDefinition::class, CustomDefinition::class, ContainerInterface::IGNORE_ON_INVALID_REFERENCE)), 'bar' => new ServiceClosureArgument(new TypedReference('bar', CustomDefinition::class)), 'baz' => new ServiceClosureArgument(new TypedReference(CustomDefinition::class, CustomDefinition::class, ContainerInterface::IGNORE_ON_INVALID_REFERENCE)), - ); + ]; $this->assertEquals($expected, $container->getDefinition((string) $locator->getFactory()[0])->getArgument(0)); } @@ -128,10 +128,10 @@ public function testExtraServiceSubscriber() $container->register('foo_service', TestServiceSubscriber::class) ->setAutowired(true) ->addArgument(new Reference(PsrContainerInterface::class)) - ->addTag('container.service_subscriber', array( + ->addTag('container.service_subscriber', [ 'key' => 'test', 'id' => TestServiceSubscriber::class, - )) + ]) ; $container->register(TestServiceSubscriber::class, TestServiceSubscriber::class); $container->compile(); diff --git a/Tests/Compiler/RemoveUnusedDefinitionsPassTest.php b/Tests/Compiler/RemoveUnusedDefinitionsPassTest.php index c6f4e5e79..1dfdd9dde 100644 --- a/Tests/Compiler/RemoveUnusedDefinitionsPassTest.php +++ b/Tests/Compiler/RemoveUnusedDefinitionsPassTest.php @@ -13,12 +13,12 @@ use PHPUnit\Framework\TestCase; use Symfony\Component\DependencyInjection\Compiler\AnalyzeServiceReferencesPass; -use Symfony\Component\DependencyInjection\Compiler\RepeatedPass; use Symfony\Component\DependencyInjection\Compiler\RemoveUnusedDefinitionsPass; +use Symfony\Component\DependencyInjection\Compiler\RepeatedPass; use Symfony\Component\DependencyInjection\Compiler\ResolveParameterPlaceHoldersPass; +use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Definition; use Symfony\Component\DependencyInjection\Reference; -use Symfony\Component\DependencyInjection\ContainerBuilder; class RemoveUnusedDefinitionsPassTest extends TestCase { @@ -35,7 +35,7 @@ public function testProcess() ; $container ->register('moo') - ->setArguments(array(new Reference('bar'))) + ->setArguments([new Reference('bar')]) ; $this->process($container); @@ -54,7 +54,7 @@ public function testProcessRemovesUnusedDefinitionsRecursively() ; $container ->register('bar') - ->setArguments(array(new Reference('foo'))) + ->setArguments([new Reference('foo')]) ->setPublic(false) ; @@ -73,7 +73,7 @@ public function testProcessWorksWithInlinedDefinitions() ; $container ->register('bar') - ->setArguments(array(new Definition(null, array(new Reference('foo'))))) + ->setArguments([new Definition(null, [new Reference('foo')])]) ; $this->process($container); @@ -88,12 +88,12 @@ public function testProcessWontRemovePrivateFactory() $container ->register('foo', 'stdClass') - ->setFactory(array('stdClass', 'getInstance')) + ->setFactory(['stdClass', 'getInstance']) ->setPublic(false); $container ->register('bar', 'stdClass') - ->setFactory(array(new Reference('foo'), 'getInstance')) + ->setFactory([new Reference('foo'), 'getInstance']) ->setPublic(false); $container @@ -113,7 +113,7 @@ public function testProcessConsiderEnvVariablesAsUsedEvenInPrivateServices() $container->setParameter('env(FOOBAR)', 'test'); $container ->register('foo') - ->setArguments(array('%env(FOOBAR)%')) + ->setArguments(['%env(FOOBAR)%']) ->setPublic(false) ; @@ -131,7 +131,7 @@ public function testProcessConsiderEnvVariablesAsUsedEvenInPrivateServices() protected function process(ContainerBuilder $container) { - $repeatedPass = new RepeatedPass(array(new AnalyzeServiceReferencesPass(), new RemoveUnusedDefinitionsPass())); + $repeatedPass = new RepeatedPass([new AnalyzeServiceReferencesPass(), new RemoveUnusedDefinitionsPass()]); $repeatedPass->process($container); } } diff --git a/Tests/Compiler/ReplaceAliasByActualDefinitionPassTest.php b/Tests/Compiler/ReplaceAliasByActualDefinitionPassTest.php index 7574e7943..f9c755c35 100644 --- a/Tests/Compiler/ReplaceAliasByActualDefinitionPassTest.php +++ b/Tests/Compiler/ReplaceAliasByActualDefinitionPassTest.php @@ -26,7 +26,7 @@ public function testProcess() $container = new ContainerBuilder(); $aDefinition = $container->register('a', '\stdClass'); - $aDefinition->setFactory(array(new Reference('b'), 'createA')); + $aDefinition->setFactory([new Reference('b'), 'createA']); $bDefinition = new Definition('\stdClass'); $bDefinition->setPublic(false); diff --git a/Tests/Compiler/ResolveBindingsPassTest.php b/Tests/Compiler/ResolveBindingsPassTest.php index 65f5ceb80..5118b416f 100644 --- a/Tests/Compiler/ResolveBindingsPassTest.php +++ b/Tests/Compiler/ResolveBindingsPassTest.php @@ -17,9 +17,9 @@ use Symfony\Component\DependencyInjection\Compiler\ResolveBindingsPass; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Reference; +use Symfony\Component\DependencyInjection\Tests\Fixtures\CaseSensitiveClass; use Symfony\Component\DependencyInjection\Tests\Fixtures\NamedArgumentsDummy; use Symfony\Component\DependencyInjection\Tests\Fixtures\ParentNotExists; -use Symfony\Component\DependencyInjection\Tests\Fixtures\CaseSensitiveClass; use Symfony\Component\DependencyInjection\TypedReference; require_once __DIR__.'/../Fixtures/includes/autowiring_classes.php'; @@ -30,10 +30,10 @@ public function testProcess() { $container = new ContainerBuilder(); - $bindings = array(CaseSensitiveClass::class => new BoundArgument(new Reference('foo'))); + $bindings = [CaseSensitiveClass::class => new BoundArgument(new Reference('foo'))]; $definition = $container->register(NamedArgumentsDummy::class, NamedArgumentsDummy::class); - $definition->setArguments(array(1 => '123')); + $definition->setArguments([1 => '123']); $definition->addMethodCall('setSensitiveClass'); $definition->setBindings($bindings); @@ -43,8 +43,8 @@ public function testProcess() $pass = new ResolveBindingsPass(); $pass->process($container); - $this->assertEquals(array(new Reference('foo'), '123'), $definition->getArguments()); - $this->assertEquals(array(array('setSensitiveClass', array(new Reference('foo')))), $definition->getMethodCalls()); + $this->assertEquals([new Reference('foo'), '123'], $definition->getArguments()); + $this->assertEquals([['setSensitiveClass', [new Reference('foo')]]], $definition->getMethodCalls()); } /** @@ -56,7 +56,7 @@ public function testUnusedBinding() $container = new ContainerBuilder(); $definition = $container->register(NamedArgumentsDummy::class, NamedArgumentsDummy::class); - $definition->setBindings(array('$quz' => '123')); + $definition->setBindings(['$quz' => '123']); $pass = new ResolveBindingsPass(); $pass->process($container); @@ -71,7 +71,7 @@ public function testMissingParent() $container = new ContainerBuilder(); $definition = $container->register(ParentNotExists::class, ParentNotExists::class); - $definition->setBindings(array('$quz' => '123')); + $definition->setBindings(['$quz' => '123']); $pass = new ResolveBindingsPass(); $pass->process($container); @@ -81,7 +81,7 @@ public function testTypedReferenceSupport() { $container = new ContainerBuilder(); - $bindings = array(CaseSensitiveClass::class => new BoundArgument(new Reference('foo'))); + $bindings = [CaseSensitiveClass::class => new BoundArgument(new Reference('foo'))]; // Explicit service id $definition1 = $container->register('def1', NamedArgumentsDummy::class); @@ -95,8 +95,8 @@ public function testTypedReferenceSupport() $pass = new ResolveBindingsPass(); $pass->process($container); - $this->assertEquals(array($typedRef), $container->getDefinition('def1')->getArguments()); - $this->assertEquals(array(new Reference('foo')), $container->getDefinition('def2')->getArguments()); + $this->assertEquals([$typedRef], $container->getDefinition('def1')->getArguments()); + $this->assertEquals([new Reference('foo')], $container->getDefinition('def2')->getArguments()); } public function testScalarSetter() @@ -104,11 +104,11 @@ public function testScalarSetter() $container = new ContainerBuilder(); $definition = $container->autowire('foo', ScalarSetter::class); - $definition->setBindings(array('$defaultLocale' => 'fr')); + $definition->setBindings(['$defaultLocale' => 'fr']); (new AutowireRequiredMethodsPass())->process($container); (new ResolveBindingsPass())->process($container); - $this->assertEquals(array(array('setDefaultLocale', array('fr'))), $definition->getMethodCalls()); + $this->assertEquals([['setDefaultLocale', ['fr']]], $definition->getMethodCalls()); } } diff --git a/Tests/Compiler/ResolveChildDefinitionsPassTest.php b/Tests/Compiler/ResolveChildDefinitionsPassTest.php index e633f8431..07c1abdf5 100644 --- a/Tests/Compiler/ResolveChildDefinitionsPassTest.php +++ b/Tests/Compiler/ResolveChildDefinitionsPassTest.php @@ -21,7 +21,7 @@ class ResolveChildDefinitionsPassTest extends TestCase public function testProcess() { $container = new ContainerBuilder(); - $container->register('parent', 'foo')->setArguments(array('moo', 'b'))->setProperty('foo', 'moo'); + $container->register('parent', 'foo')->setArguments(['moo', 'b'])->setProperty('foo', 'moo'); $container->setDefinition('child', new ChildDefinition('parent')) ->replaceArgument(0, 'a') ->setProperty('foo', 'bar') @@ -33,8 +33,8 @@ public function testProcess() $def = $container->getDefinition('child'); $this->assertNotInstanceOf(ChildDefinition::class, $def); $this->assertEquals('bar', $def->getClass()); - $this->assertEquals(array('a', 'b'), $def->getArguments()); - $this->assertEquals(array('foo' => 'bar'), $def->getProperties()); + $this->assertEquals(['a', 'b'], $def->getArguments()); + $this->assertEquals(['foo' => 'bar'], $def->getProperties()); } public function testProcessAppendsMethodCallsAlways() @@ -43,21 +43,21 @@ public function testProcessAppendsMethodCallsAlways() $container ->register('parent') - ->addMethodCall('foo', array('bar')) + ->addMethodCall('foo', ['bar']) ; $container ->setDefinition('child', new ChildDefinition('parent')) - ->addMethodCall('bar', array('foo')) + ->addMethodCall('bar', ['foo']) ; $this->process($container); $def = $container->getDefinition('child'); - $this->assertEquals(array( - array('foo', array('bar')), - array('bar', array('foo')), - ), $def->getMethodCalls()); + $this->assertEquals([ + ['foo', ['bar']], + ['bar', ['foo']], + ], $def->getMethodCalls()); } public function testProcessDoesNotCopyAbstract() @@ -114,7 +114,7 @@ public function testProcessDoesNotCopyTags() $this->process($container); $def = $container->getDefinition('child'); - $this->assertEquals(array(), $def->getTags()); + $this->assertEquals([], $def->getTags()); } public function testProcessDoesNotCopyDecoratedService() @@ -161,7 +161,7 @@ public function testProcessHandlesMultipleInheritance() $container ->register('parent', 'foo') - ->setArguments(array('foo', 'bar', 'c')) + ->setArguments(['foo', 'bar', 'c']) ; $container @@ -177,7 +177,7 @@ public function testProcessHandlesMultipleInheritance() $this->process($container); $def = $container->getDefinition('child2'); - $this->assertEquals(array('a', 'b', 'c'), $def->getArguments()); + $this->assertEquals(['a', 'b', 'c'], $def->getArguments()); $this->assertEquals('foo', $def->getClass()); } @@ -250,32 +250,32 @@ public function testDeepDefinitionsResolving() $container->register('parent', 'parentClass'); $container->register('sibling', 'siblingClass') ->setConfigurator(new ChildDefinition('parent'), 'foo') - ->setFactory(array(new ChildDefinition('parent'), 'foo')) + ->setFactory([new ChildDefinition('parent'), 'foo']) ->addArgument(new ChildDefinition('parent')) ->setProperty('prop', new ChildDefinition('parent')) - ->addMethodCall('meth', array(new ChildDefinition('parent'))) + ->addMethodCall('meth', [new ChildDefinition('parent')]) ; $this->process($container); $configurator = $container->getDefinition('sibling')->getConfigurator(); - $this->assertSame('Symfony\Component\DependencyInjection\Definition', get_class($configurator)); + $this->assertSame('Symfony\Component\DependencyInjection\Definition', \get_class($configurator)); $this->assertSame('parentClass', $configurator->getClass()); $factory = $container->getDefinition('sibling')->getFactory(); - $this->assertSame('Symfony\Component\DependencyInjection\Definition', get_class($factory[0])); + $this->assertSame('Symfony\Component\DependencyInjection\Definition', \get_class($factory[0])); $this->assertSame('parentClass', $factory[0]->getClass()); $argument = $container->getDefinition('sibling')->getArgument(0); - $this->assertSame('Symfony\Component\DependencyInjection\Definition', get_class($argument)); + $this->assertSame('Symfony\Component\DependencyInjection\Definition', \get_class($argument)); $this->assertSame('parentClass', $argument->getClass()); $properties = $container->getDefinition('sibling')->getProperties(); - $this->assertSame('Symfony\Component\DependencyInjection\Definition', get_class($properties['prop'])); + $this->assertSame('Symfony\Component\DependencyInjection\Definition', \get_class($properties['prop'])); $this->assertSame('parentClass', $properties['prop']->getClass()); $methodCalls = $container->getDefinition('sibling')->getMethodCalls(); - $this->assertSame('Symfony\Component\DependencyInjection\Definition', get_class($methodCalls[0][1][0])); + $this->assertSame('Symfony\Component\DependencyInjection\Definition', \get_class($methodCalls[0][1][0])); $this->assertSame('parentClass', $methodCalls[0][1][0]->getClass()); } @@ -291,7 +291,7 @@ public function testSetDecoratedServiceOnServiceHasParent() $this->process($container); - $this->assertEquals(array('foo', 'foo_inner', 5), $container->getDefinition('child1')->getDecoratedService()); + $this->assertEquals(['foo', 'foo_inner', 5], $container->getDefinition('child1')->getDecoratedService()); } public function testDecoratedServiceCopiesDeprecatedStatusFromParent() @@ -342,17 +342,17 @@ public function testProcessSetsArguments() { $container = new ContainerBuilder(); - $container->register('parent', 'ParentClass')->setArguments(array(0)); - $container->setDefinition('child', (new ChildDefinition('parent'))->setArguments(array( + $container->register('parent', 'ParentClass')->setArguments([0]); + $container->setDefinition('child', (new ChildDefinition('parent'))->setArguments([ 1, 'index_0' => 2, 'foo' => 3, - ))); + ])); $this->process($container); $def = $container->getDefinition('child'); - $this->assertSame(array(2, 1, 'foo' => 3), $def->getArguments()); + $this->assertSame([2, 1, 'foo' => 3], $def->getArguments()); } public function testBindings() @@ -360,20 +360,20 @@ public function testBindings() $container = new ContainerBuilder(); $container->register('parent', 'stdClass') - ->setBindings(array('a' => '1', 'b' => '2')) + ->setBindings(['a' => '1', 'b' => '2']) ; $child = $container->setDefinition('child', new ChildDefinition('parent')) - ->setBindings(array('b' => 'B', 'c' => 'C')) + ->setBindings(['b' => 'B', 'c' => 'C']) ; $this->process($container); - $bindings = array(); + $bindings = []; foreach ($container->getDefinition('child')->getBindings() as $k => $v) { $bindings[$k] = $v->getValues()[0]; } - $this->assertEquals(array('b' => 'B', 'c' => 'C', 'a' => '1'), $bindings); + $this->assertEquals(['b' => 'B', 'c' => 'C', 'a' => '1'], $bindings); } public function testSetAutoconfiguredOnServiceIsParent() @@ -396,4 +396,21 @@ protected function process(ContainerBuilder $container) $pass = new ResolveChildDefinitionsPass(); $pass->process($container); } + + /** + * @expectedException \Symfony\Component\DependencyInjection\Exception\ServiceCircularReferenceException + * @expectedExceptionMessageRegExp /^Circular reference detected for service "c", path: "c -> b -> a -> c"./ + */ + public function testProcessDetectsChildDefinitionIndirectCircularReference() + { + $container = new ContainerBuilder(); + + $container->register('a'); + + $container->setDefinition('b', new ChildDefinition('a')); + $container->setDefinition('c', new ChildDefinition('b')); + $container->setDefinition('a', new ChildDefinition('c')); + + $this->process($container); + } } diff --git a/Tests/Compiler/ResolveClassPassTest.php b/Tests/Compiler/ResolveClassPassTest.php index acbcf1dda..48df3843d 100644 --- a/Tests/Compiler/ResolveClassPassTest.php +++ b/Tests/Compiler/ResolveClassPassTest.php @@ -34,8 +34,8 @@ public function testResolveClassFromId($serviceId) public function provideValidClassId() { - yield array('Acme\UnknownClass'); - yield array(CaseSensitiveClass::class); + yield ['Acme\UnknownClass']; + yield [CaseSensitiveClass::class]; } /** @@ -53,9 +53,9 @@ public function testWontResolveClassFromId($serviceId) public function provideInvalidClassId() { - yield array(\stdClass::class); - yield array('bar'); - yield array('\DateTime'); + yield [\stdClass::class]; + yield ['bar']; + yield ['\DateTime']; } public function testNonFqcnChildDefinition() diff --git a/Tests/Compiler/ResolveFactoryClassPassTest.php b/Tests/Compiler/ResolveFactoryClassPassTest.php index 96453c303..3438fad06 100644 --- a/Tests/Compiler/ResolveFactoryClassPassTest.php +++ b/Tests/Compiler/ResolveFactoryClassPassTest.php @@ -24,12 +24,12 @@ public function testProcess() $container = new ContainerBuilder(); $factory = $container->register('factory', 'Foo\Bar'); - $factory->setFactory(array(null, 'create')); + $factory->setFactory([null, 'create']); $pass = new ResolveFactoryClassPass(); $pass->process($container); - $this->assertSame(array('Foo\Bar', 'create'), $factory->getFactory()); + $this->assertSame(['Foo\Bar', 'create'], $factory->getFactory()); } public function testInlinedDefinitionFactoryIsProcessed() @@ -37,21 +37,21 @@ public function testInlinedDefinitionFactoryIsProcessed() $container = new ContainerBuilder(); $factory = $container->register('factory'); - $factory->setFactory(array((new Definition('Baz\Qux'))->setFactory(array(null, 'getInstance')), 'create')); + $factory->setFactory([(new Definition('Baz\Qux'))->setFactory([null, 'getInstance']), 'create']); $pass = new ResolveFactoryClassPass(); $pass->process($container); - $this->assertSame(array('Baz\Qux', 'getInstance'), $factory->getFactory()[0]->getFactory()); + $this->assertSame(['Baz\Qux', 'getInstance'], $factory->getFactory()[0]->getFactory()); } public function provideFulfilledFactories() { - return array( - array(array('Foo\Bar', 'create')), - array(array(new Reference('foo'), 'create')), - array(array(new Definition('Baz'), 'create')), - ); + return [ + [['Foo\Bar', 'create']], + [[new Reference('foo'), 'create']], + [[new Definition('Baz'), 'create']], + ]; } /** @@ -80,7 +80,7 @@ public function testNotAnyClassThrowsException() $container = new ContainerBuilder(); $factory = $container->register('factory'); - $factory->setFactory(array(null, 'create')); + $factory->setFactory([null, 'create']); $pass = new ResolveFactoryClassPass(); $pass->process($container); diff --git a/Tests/Compiler/ResolveHotPathPassTest.php b/Tests/Compiler/ResolveHotPathPassTest.php index d2ba59004..a2fece058 100644 --- a/Tests/Compiler/ResolveHotPathPassTest.php +++ b/Tests/Compiler/ResolveHotPathPassTest.php @@ -26,9 +26,9 @@ public function testProcess() $container->register('foo') ->addTag('container.hot_path') - ->addArgument(new IteratorArgument(array(new Reference('lazy')))) + ->addArgument(new IteratorArgument([new Reference('lazy')])) ->addArgument(new Reference('service_container')) - ->addArgument(new Definition('', array(new Reference('bar')))) + ->addArgument(new Definition('', [new Reference('bar')])) ->addArgument(new Reference('baz', ContainerBuilder::IGNORE_ON_UNINITIALIZED_REFERENCE)) ->addArgument(new Reference('missing')) ; diff --git a/Tests/Compiler/ResolveInstanceofConditionalsPassTest.php b/Tests/Compiler/ResolveInstanceofConditionalsPassTest.php index 38164fc10..6bc0043c4 100644 --- a/Tests/Compiler/ResolveInstanceofConditionalsPassTest.php +++ b/Tests/Compiler/ResolveInstanceofConditionalsPassTest.php @@ -12,9 +12,10 @@ namespace Symfony\Component\DependencyInjection\Tests\Compiler; use PHPUnit\Framework\TestCase; +use Symfony\Component\DependencyInjection\Argument\BoundArgument; use Symfony\Component\DependencyInjection\ChildDefinition; -use Symfony\Component\DependencyInjection\Compiler\ResolveInstanceofConditionalsPass; use Symfony\Component\DependencyInjection\Compiler\ResolveChildDefinitionsPass; +use Symfony\Component\DependencyInjection\Compiler\ResolveInstanceofConditionalsPass; use Symfony\Component\DependencyInjection\ContainerBuilder; class ResolveInstanceofConditionalsPassTest extends TestCase @@ -22,10 +23,10 @@ class ResolveInstanceofConditionalsPassTest extends TestCase public function testProcess() { $container = new ContainerBuilder(); - $def = $container->register('foo', self::class)->addTag('tag')->setAutowired(true)->setChanges(array()); - $def->setInstanceofConditionals(array( - parent::class => (new ChildDefinition(''))->setProperty('foo', 'bar')->addTag('baz', array('attr' => 123)), - )); + $def = $container->register('foo', self::class)->addTag('tag')->setAutowired(true)->setChanges([]); + $def->setInstanceofConditionals([ + parent::class => (new ChildDefinition(''))->setProperty('foo', 'bar')->addTag('baz', ['attr' => 123]), + ]); (new ResolveInstanceofConditionalsPass())->process($container); @@ -35,11 +36,11 @@ public function testProcess() $this->assertInstanceOf(ChildDefinition::class, $def); $this->assertTrue($def->isAutowired()); $this->assertSame($parent, $def->getParent()); - $this->assertSame(array('tag' => array(array()), 'baz' => array(array('attr' => 123))), $def->getTags()); + $this->assertSame(['tag' => [[]], 'baz' => [['attr' => 123]]], $def->getTags()); $parent = $container->getDefinition($parent); - $this->assertSame(array('foo' => 'bar'), $parent->getProperties()); - $this->assertSame(array(), $parent->getTags()); + $this->assertSame(['foo' => 'bar'], $parent->getProperties()); + $this->assertSame([], $parent->getTags()); } public function testProcessInheritance() @@ -48,10 +49,10 @@ public function testProcessInheritance() $def = $container ->register('parent', parent::class) - ->addMethodCall('foo', array('foo')); - $def->setInstanceofConditionals(array( - parent::class => (new ChildDefinition(''))->addMethodCall('foo', array('bar')), - )); + ->addMethodCall('foo', ['foo']); + $def->setInstanceofConditionals([ + parent::class => (new ChildDefinition(''))->addMethodCall('foo', ['bar']), + ]); $def = (new ChildDefinition('parent'))->setClass(self::class); $container->setDefinition('child', $def); @@ -59,10 +60,10 @@ public function testProcessInheritance() (new ResolveInstanceofConditionalsPass())->process($container); (new ResolveChildDefinitionsPass())->process($container); - $expected = array( - array('foo', array('bar')), - array('foo', array('foo')), - ); + $expected = [ + ['foo', ['bar']], + ['foo', ['foo']], + ]; $this->assertSame($expected, $container->getDefinition('parent')->getMethodCalls()); $this->assertSame($expected, $container->getDefinition('child')->getMethodCalls()); @@ -73,9 +74,9 @@ public function testProcessDoesReplaceShared() $container = new ContainerBuilder(); $def = $container->register('foo', 'stdClass'); - $def->setInstanceofConditionals(array( + $def->setInstanceofConditionals([ 'stdClass' => (new ChildDefinition(''))->setShared(false), - )); + ]); (new ResolveInstanceofConditionalsPass())->process($container); @@ -89,10 +90,10 @@ public function testProcessHandlesMultipleInheritance() $def = $container->register('foo', self::class)->setShared(true); - $def->setInstanceofConditionals(array( + $def->setInstanceofConditionals([ parent::class => (new ChildDefinition(''))->setLazy(true)->setShared(false), self::class => (new ChildDefinition(''))->setAutowired(true), - )); + ]); (new ResolveInstanceofConditionalsPass())->process($container); (new ResolveChildDefinitionsPass())->process($container); @@ -107,11 +108,11 @@ public function testProcessUsesAutoconfiguredInstanceof() { $container = new ContainerBuilder(); $def = $container->register('normal_service', self::class); - $def->setInstanceofConditionals(array( + $def->setInstanceofConditionals([ parent::class => (new ChildDefinition('')) ->addTag('local_instanceof_tag') ->setFactory('locally_set_factory'), - )); + ]); $def->setAutoconfigured(true); $container->registerForAutoconfiguration(parent::class) ->addTag('autoconfigured_tag') @@ -127,7 +128,7 @@ public function testProcessUsesAutoconfiguredInstanceof() // factory from the specific instanceof overrides global one $this->assertEquals('locally_set_factory', $def->getFactory()); // tags are merged, the locally set one is first - $this->assertSame(array('local_instanceof_tag' => array(array()), 'autoconfigured_tag' => array(array())), $def->getTags()); + $this->assertSame(['local_instanceof_tag' => [[]], 'autoconfigured_tag' => [[]]], $def->getTags()); } public function testAutoconfigureInstanceofDoesNotDuplicateTags() @@ -136,31 +137,31 @@ public function testAutoconfigureInstanceofDoesNotDuplicateTags() $def = $container->register('normal_service', self::class); $def ->addTag('duplicated_tag') - ->addTag('duplicated_tag', array('and_attributes' => 1)) + ->addTag('duplicated_tag', ['and_attributes' => 1]) ; - $def->setInstanceofConditionals(array( + $def->setInstanceofConditionals([ parent::class => (new ChildDefinition(''))->addTag('duplicated_tag'), - )); + ]); $def->setAutoconfigured(true); $container->registerForAutoconfiguration(parent::class) - ->addTag('duplicated_tag', array('and_attributes' => 1)) + ->addTag('duplicated_tag', ['and_attributes' => 1]) ; (new ResolveInstanceofConditionalsPass())->process($container); (new ResolveChildDefinitionsPass())->process($container); $def = $container->getDefinition('normal_service'); - $this->assertSame(array('duplicated_tag' => array(array(), array('and_attributes' => 1))), $def->getTags()); + $this->assertSame(['duplicated_tag' => [[], ['and_attributes' => 1]]], $def->getTags()); } public function testProcessDoesNotUseAutoconfiguredInstanceofIfNotEnabled() { $container = new ContainerBuilder(); $def = $container->register('normal_service', self::class); - $def->setInstanceofConditionals(array( + $def->setInstanceofConditionals([ parent::class => (new ChildDefinition('')) ->addTag('foo_tag'), - )); + ]); $container->registerForAutoconfiguration(parent::class) ->setAutowired(true); @@ -179,10 +180,10 @@ public function testBadInterfaceThrowsException() { $container = new ContainerBuilder(); $def = $container->register('normal_service', self::class); - $def->setInstanceofConditionals(array( + $def->setInstanceofConditionals([ 'App\\FakeInterface' => (new ChildDefinition('')) ->addTag('foo_tag'), - )); + ]); (new ResolveInstanceofConditionalsPass())->process($container); } @@ -206,21 +207,21 @@ public function testProcessForAutoconfiguredCalls() { $container = new ContainerBuilder(); - $expected = array( - array('setFoo', array( + $expected = [ + ['setFoo', [ 'plain_value', '%some_parameter%', - )), - array('callBar', array()), - array('isBaz', array()), - ); + ]], + ['callBar', []], + ['isBaz', []], + ]; $container->registerForAutoconfiguration(parent::class)->addMethodCall('setFoo', $expected[0][1]); $container->registerForAutoconfiguration(self::class)->addMethodCall('callBar'); $def = $container->register('foo', self::class)->setAutoconfigured(true)->addMethodCall('isBaz'); $this->assertEquals( - array(array('isBaz', array())), + [['isBaz', []]], $def->getMethodCalls(), 'Definition shouldn\'t have only one method call.' ); @@ -253,9 +254,9 @@ public function testMergeReset() ->addMethodCall('setB') ->setDecoratedService('foo') ->addTag('t') - ->setInstanceofConditionals(array( + ->setInstanceofConditionals([ parent::class => (new ChildDefinition(''))->addTag('bar'), - )) + ]) ; (new ResolveInstanceofConditionalsPass())->process($container); @@ -268,4 +269,18 @@ public function testMergeReset() $this->assertEmpty($abstract->getTags()); $this->assertTrue($abstract->isAbstract()); } + + public function testBindings() + { + $container = new ContainerBuilder(); + $def = $container->register('foo', self::class)->setBindings(['$toto' => 123]); + $def->setInstanceofConditionals([parent::class => new ChildDefinition('')]); + + (new ResolveInstanceofConditionalsPass())->process($container); + + $bindings = $container->getDefinition('foo')->getBindings(); + $this->assertSame(['$toto'], array_keys($bindings)); + $this->assertInstanceOf(BoundArgument::class, $bindings['$toto']); + $this->assertSame(123, $bindings['$toto']->getValues()[0]); + } } diff --git a/Tests/Compiler/ResolveInvalidReferencesPassTest.php b/Tests/Compiler/ResolveInvalidReferencesPassTest.php index 00613ba5c..817cc64ce 100644 --- a/Tests/Compiler/ResolveInvalidReferencesPassTest.php +++ b/Tests/Compiler/ResolveInvalidReferencesPassTest.php @@ -13,10 +13,10 @@ use PHPUnit\Framework\TestCase; use Symfony\Component\DependencyInjection\Argument\ServiceClosureArgument; -use Symfony\Component\DependencyInjection\ContainerInterface; -use Symfony\Component\DependencyInjection\Reference; use Symfony\Component\DependencyInjection\Compiler\ResolveInvalidReferencesPass; use Symfony\Component\DependencyInjection\ContainerBuilder; +use Symfony\Component\DependencyInjection\ContainerInterface; +use Symfony\Component\DependencyInjection\Reference; class ResolveInvalidReferencesPassTest extends TestCase { @@ -25,17 +25,17 @@ public function testProcess() $container = new ContainerBuilder(); $def = $container ->register('foo') - ->setArguments(array( + ->setArguments([ new Reference('bar', ContainerInterface::NULL_ON_INVALID_REFERENCE), new Reference('baz', ContainerInterface::IGNORE_ON_INVALID_REFERENCE), - )) - ->addMethodCall('foo', array(new Reference('moo', ContainerInterface::IGNORE_ON_INVALID_REFERENCE))) + ]) + ->addMethodCall('foo', [new Reference('moo', ContainerInterface::IGNORE_ON_INVALID_REFERENCE)]) ; $this->process($container); $arguments = $def->getArguments(); - $this->assertSame(array(null, null), $arguments); + $this->assertSame([null, null], $arguments); $this->assertCount(0, $def->getMethodCalls()); } @@ -45,19 +45,19 @@ public function testProcessIgnoreInvalidArgumentInCollectionArgument() $container->register('baz'); $def = $container ->register('foo') - ->setArguments(array( - array( + ->setArguments([ + [ new Reference('bar', ContainerInterface::IGNORE_ON_INVALID_REFERENCE), $baz = new Reference('baz', ContainerInterface::IGNORE_ON_INVALID_REFERENCE), new Reference('moo', ContainerInterface::NULL_ON_INVALID_REFERENCE), - ), - )) + ], + ]) ; $this->process($container); $arguments = $def->getArguments(); - $this->assertSame(array($baz, null), $arguments[0]); + $this->assertSame([$baz, null], $arguments[0]); } public function testProcessKeepMethodCallOnInvalidArgumentInCollectionArgument() @@ -66,20 +66,20 @@ public function testProcessKeepMethodCallOnInvalidArgumentInCollectionArgument() $container->register('baz'); $def = $container ->register('foo') - ->addMethodCall('foo', array( - array( + ->addMethodCall('foo', [ + [ new Reference('bar', ContainerInterface::IGNORE_ON_INVALID_REFERENCE), $baz = new Reference('baz', ContainerInterface::IGNORE_ON_INVALID_REFERENCE), new Reference('moo', ContainerInterface::NULL_ON_INVALID_REFERENCE), - ), - )) + ], + ]) ; $this->process($container); $calls = $def->getMethodCalls(); $this->assertCount(1, $def->getMethodCalls()); - $this->assertSame(array($baz, null), $calls[0][1][0]); + $this->assertSame([$baz, null], $calls[0][1][0]); } public function testProcessIgnoreNonExistentServices() @@ -87,7 +87,7 @@ public function testProcessIgnoreNonExistentServices() $container = new ContainerBuilder(); $def = $container ->register('foo') - ->setArguments(array(new Reference('bar'))) + ->setArguments([new Reference('bar')]) ; $this->process($container); @@ -106,7 +106,7 @@ public function testProcessRemovesPropertiesOnInvalid() $this->process($container); - $this->assertEquals(array(), $def->getProperties()); + $this->assertEquals([], $def->getProperties()); } public function testProcessRemovesArgumentsOnInvalid() @@ -114,17 +114,17 @@ public function testProcessRemovesArgumentsOnInvalid() $container = new ContainerBuilder(); $def = $container ->register('foo') - ->addArgument(array( - array( + ->addArgument([ + [ new Reference('bar', ContainerInterface::IGNORE_ON_INVALID_REFERENCE), new ServiceClosureArgument(new Reference('baz', ContainerInterface::IGNORE_ON_INVALID_REFERENCE)), - ), - )) + ], + ]) ; $this->process($container); - $this->assertSame(array(array(array())), $def->getArguments()); + $this->assertSame([[[]]], $def->getArguments()); } protected function process(ContainerBuilder $container) diff --git a/Tests/Compiler/ResolveNamedArgumentsPassTest.php b/Tests/Compiler/ResolveNamedArgumentsPassTest.php index 4665ee96f..024f7adb4 100644 --- a/Tests/Compiler/ResolveNamedArgumentsPassTest.php +++ b/Tests/Compiler/ResolveNamedArgumentsPassTest.php @@ -16,9 +16,11 @@ use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Reference; use Symfony\Component\DependencyInjection\Tests\Fixtures\CaseSensitiveClass; +use Symfony\Component\DependencyInjection\Tests\Fixtures\FactoryDummyWithoutReturnTypes; use Symfony\Component\DependencyInjection\Tests\Fixtures\NamedArgumentsDummy; use Symfony\Component\DependencyInjection\Tests\Fixtures\NamedArgumentsVariadicsDummy; use Symfony\Component\DependencyInjection\Tests\Fixtures\SimilarArgumentsDummy; +use Symfony\Component\DependencyInjection\Tests\Fixtures\TestDefinition1; /** * @author Kévin Dunglas @@ -30,18 +32,18 @@ public function testProcess() $container = new ContainerBuilder(); $definition = $container->register(NamedArgumentsDummy::class, NamedArgumentsDummy::class); - $definition->setArguments(array( + $definition->setArguments([ 2 => 'http://api.example.com', '$apiKey' => '123', 0 => new Reference('foo'), - )); - $definition->addMethodCall('setApiKey', array('$apiKey' => '123')); + ]); + $definition->addMethodCall('setApiKey', ['$apiKey' => '123']); $pass = new ResolveNamedArgumentsPass(); $pass->process($container); - $this->assertEquals(array(0 => new Reference('foo'), 1 => '123', 2 => 'http://api.example.com'), $definition->getArguments()); - $this->assertEquals(array(array('setApiKey', array('123'))), $definition->getMethodCalls()); + $this->assertEquals([0 => new Reference('foo'), 1 => '123', 2 => 'http://api.example.com'], $definition->getArguments()); + $this->assertEquals([['setApiKey', ['123']]], $definition->getMethodCalls()); } public function testWithFactory() @@ -50,13 +52,13 @@ public function testWithFactory() $container->register('factory', NoConstructor::class); $definition = $container->register('foo', NoConstructor::class) - ->setFactory(array(new Reference('factory'), 'create')) - ->setArguments(array('$apiKey' => '123')); + ->setFactory([new Reference('factory'), 'create']) + ->setArguments(['$apiKey' => '123']); $pass = new ResolveNamedArgumentsPass(); $pass->process($container); - $this->assertSame(array(0 => '123'), $definition->getArguments()); + $this->assertSame([0 => '123'], $definition->getArguments()); } /** @@ -67,7 +69,7 @@ public function testClassNull() $container = new ContainerBuilder(); $definition = $container->register(NamedArgumentsDummy::class); - $definition->setArguments(array('$apiKey' => '123')); + $definition->setArguments(['$apiKey' => '123']); $pass = new ResolveNamedArgumentsPass(); $pass->process($container); @@ -81,7 +83,7 @@ public function testClassNotExist() $container = new ContainerBuilder(); $definition = $container->register(NotExist::class, NotExist::class); - $definition->setArguments(array('$apiKey' => '123')); + $definition->setArguments(['$apiKey' => '123']); $pass = new ResolveNamedArgumentsPass(); $pass->process($container); @@ -95,7 +97,7 @@ public function testClassNoConstructor() $container = new ContainerBuilder(); $definition = $container->register(NoConstructor::class, NoConstructor::class); - $definition->setArguments(array('$apiKey' => '123')); + $definition->setArguments(['$apiKey' => '123']); $pass = new ResolveNamedArgumentsPass(); $pass->process($container); @@ -103,13 +105,32 @@ public function testClassNoConstructor() /** * @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException + * @expectedExceptionMessage Invalid service "Symfony\Component\DependencyInjection\Tests\Fixtures\NamedArgumentsDummy": method "__construct()" has no argument named "$notFound". Check your service definition. */ public function testArgumentNotFound() { $container = new ContainerBuilder(); $definition = $container->register(NamedArgumentsDummy::class, NamedArgumentsDummy::class); - $definition->setArguments(array('$notFound' => '123')); + $definition->setArguments(['$notFound' => '123']); + + $pass = new ResolveNamedArgumentsPass(); + $pass->process($container); + } + + /** + * @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException + * @expectedExceptionMessage Invalid service "Symfony\Component\DependencyInjection\Tests\Fixtures\TestDefinition1": method "Symfony\Component\DependencyInjection\Tests\Fixtures\FactoryDummyWithoutReturnTypes::createTestDefinition1()" has no argument named "$notFound". Check your service definition. + */ + public function testCorrectMethodReportedInException() + { + $container = new ContainerBuilder(); + + $container->register(FactoryDummyWithoutReturnTypes::class, FactoryDummyWithoutReturnTypes::class); + + $definition = $container->register(TestDefinition1::class, TestDefinition1::class); + $definition->setFactory([FactoryDummyWithoutReturnTypes::class, 'createTestDefinition1']); + $definition->setArguments(['$notFound' => '123']); $pass = new ResolveNamedArgumentsPass(); $pass->process($container); @@ -120,12 +141,12 @@ public function testTypedArgument() $container = new ContainerBuilder(); $definition = $container->register(NamedArgumentsDummy::class, NamedArgumentsDummy::class); - $definition->setArguments(array('$apiKey' => '123', CaseSensitiveClass::class => new Reference('foo'))); + $definition->setArguments(['$apiKey' => '123', CaseSensitiveClass::class => new Reference('foo')]); $pass = new ResolveNamedArgumentsPass(); $pass->process($container); - $this->assertEquals(array(new Reference('foo'), '123'), $definition->getArguments()); + $this->assertEquals([new Reference('foo'), '123'], $definition->getArguments()); } public function testResolvesMultipleArgumentsOfTheSameType() @@ -133,12 +154,12 @@ public function testResolvesMultipleArgumentsOfTheSameType() $container = new ContainerBuilder(); $definition = $container->register(SimilarArgumentsDummy::class, SimilarArgumentsDummy::class); - $definition->setArguments(array(CaseSensitiveClass::class => new Reference('foo'), '$token' => 'qwerty')); + $definition->setArguments([CaseSensitiveClass::class => new Reference('foo'), '$token' => 'qwerty']); $pass = new ResolveNamedArgumentsPass(); $pass->process($container); - $this->assertEquals(array(new Reference('foo'), 'qwerty', new Reference('foo')), $definition->getArguments()); + $this->assertEquals([new Reference('foo'), 'qwerty', new Reference('foo')], $definition->getArguments()); } public function testResolvePrioritizeNamedOverType() @@ -146,12 +167,12 @@ public function testResolvePrioritizeNamedOverType() $container = new ContainerBuilder(); $definition = $container->register(SimilarArgumentsDummy::class, SimilarArgumentsDummy::class); - $definition->setArguments(array(CaseSensitiveClass::class => new Reference('foo'), '$token' => 'qwerty', '$class1' => new Reference('bar'))); + $definition->setArguments([CaseSensitiveClass::class => new Reference('foo'), '$token' => 'qwerty', '$class1' => new Reference('bar')]); $pass = new ResolveNamedArgumentsPass(); $pass->process($container); - $this->assertEquals(array(new Reference('bar'), 'qwerty', new Reference('foo')), $definition->getArguments()); + $this->assertEquals([new Reference('bar'), 'qwerty', new Reference('foo')], $definition->getArguments()); } public function testVariadics() @@ -160,26 +181,26 @@ public function testVariadics() $definition = $container->register(NamedArgumentsVariadicsDummy::class, NamedArgumentsVariadicsDummy::class); $definition->setArguments( - array( + [ '$class' => new \stdClass(), - '$variadics' => array( + '$variadics' => [ new Reference('foo'), new Reference('bar'), new Reference('baz'), - ), - ) + ], + ] ); $pass = new ResolveNamedArgumentsPass(); $pass->process($container); $this->assertEquals( - array( + [ 0 => new \stdClass(), 1 => new Reference('foo'), 2 => new Reference('bar'), 3 => new Reference('baz'), - ), + ], $definition->getArguments() ); } diff --git a/Tests/Compiler/ResolveParameterPlaceHoldersPassTest.php b/Tests/Compiler/ResolveParameterPlaceHoldersPassTest.php index a34e007de..5aa647175 100644 --- a/Tests/Compiler/ResolveParameterPlaceHoldersPassTest.php +++ b/Tests/Compiler/ResolveParameterPlaceHoldersPassTest.php @@ -36,22 +36,22 @@ public function testClassParametersShouldBeResolved() public function testFactoryParametersShouldBeResolved() { - $this->assertSame(array('FooFactory', 'getFoo'), $this->fooDefinition->getFactory()); + $this->assertSame(['FooFactory', 'getFoo'], $this->fooDefinition->getFactory()); } public function testArgumentParametersShouldBeResolved() { - $this->assertSame(array('bar', array('bar' => 'baz')), $this->fooDefinition->getArguments()); + $this->assertSame(['bar', ['bar' => 'baz']], $this->fooDefinition->getArguments()); } public function testMethodCallParametersShouldBeResolved() { - $this->assertSame(array(array('foobar', array('bar', array('bar' => 'baz')))), $this->fooDefinition->getMethodCalls()); + $this->assertSame([['foobar', ['bar', ['bar' => 'baz']]]], $this->fooDefinition->getMethodCalls()); } public function testPropertyParametersShouldBeResolved() { - $this->assertSame(array('bar' => 'baz'), $this->fooDefinition->getProperties()); + $this->assertSame(['bar' => 'baz'], $this->fooDefinition->getProperties()); } public function testFileParametersShouldBeResolved() @@ -78,7 +78,7 @@ private function createContainerBuilder() $containerBuilder->setParameter('foo.class', 'Foo'); $containerBuilder->setParameter('foo.factory.class', 'FooFactory'); $containerBuilder->setParameter('foo.arg1', 'bar'); - $containerBuilder->setParameter('foo.arg2', array('%foo.arg1%' => 'baz')); + $containerBuilder->setParameter('foo.arg2', ['%foo.arg1%' => 'baz']); $containerBuilder->setParameter('foo.method', 'foobar'); $containerBuilder->setParameter('foo.property.name', 'bar'); $containerBuilder->setParameter('foo.property.value', 'baz'); @@ -86,12 +86,12 @@ private function createContainerBuilder() $containerBuilder->setParameter('alias.id', 'bar'); $fooDefinition = $containerBuilder->register('foo', '%foo.class%'); - $fooDefinition->setFactory(array('%foo.factory.class%', 'getFoo')); - $fooDefinition->setArguments(array('%foo.arg1%', array('%foo.arg1%' => 'baz'))); - $fooDefinition->addMethodCall('%foo.method%', array('%foo.arg1%', '%foo.arg2%')); + $fooDefinition->setFactory(['%foo.factory.class%', 'getFoo']); + $fooDefinition->setArguments(['%foo.arg1%', ['%foo.arg1%' => 'baz']]); + $fooDefinition->addMethodCall('%foo.method%', ['%foo.arg1%', '%foo.arg2%']); $fooDefinition->setProperty('%foo.property.name%', '%foo.property.value%'); $fooDefinition->setFile('%foo.file%'); - $fooDefinition->setBindings(array('$baz' => '%env(BAZ)%')); + $fooDefinition->setBindings(['$baz' => '%env(BAZ)%']); $containerBuilder->setAlias('%alias.id%', 'foo'); diff --git a/Tests/Compiler/ResolveReferencesToAliasesPassTest.php b/Tests/Compiler/ResolveReferencesToAliasesPassTest.php index c22ab59ea..55b47057b 100644 --- a/Tests/Compiler/ResolveReferencesToAliasesPassTest.php +++ b/Tests/Compiler/ResolveReferencesToAliasesPassTest.php @@ -13,10 +13,10 @@ use PHPUnit\Framework\TestCase; use Symfony\Component\DependencyInjection\Alias; -use Symfony\Component\DependencyInjection\Definition; -use Symfony\Component\DependencyInjection\Reference; use Symfony\Component\DependencyInjection\Compiler\ResolveReferencesToAliasesPass; use Symfony\Component\DependencyInjection\ContainerBuilder; +use Symfony\Component\DependencyInjection\Definition; +use Symfony\Component\DependencyInjection\Reference; class ResolveReferencesToAliasesPassTest extends TestCase { @@ -26,7 +26,7 @@ public function testProcess() $container->setAlias('bar', 'foo'); $def = $container ->register('moo') - ->setArguments(array(new Reference('bar'))) + ->setArguments([new Reference('bar')]) ; $this->process($container); @@ -42,7 +42,7 @@ public function testProcessRecursively() $container->setAlias('moo', 'bar'); $def = $container ->register('foobar') - ->setArguments(array(new Reference('moo'))) + ->setArguments([new Reference('moo')]) ; $this->process($container); @@ -68,10 +68,10 @@ public function testResolveFactory() $container->register('factory', 'Factory'); $container->setAlias('factory_alias', new Alias('factory')); $foo = new Definition(); - $foo->setFactory(array(new Reference('factory_alias'), 'createFoo')); + $foo->setFactory([new Reference('factory_alias'), 'createFoo']); $container->setDefinition('foo', $foo); $bar = new Definition(); - $bar->setFactory(array('Factory', 'createFoo')); + $bar->setFactory(['Factory', 'createFoo']); $container->setDefinition('bar', $bar); $this->process($container); diff --git a/Tests/Compiler/ResolveTaggedIteratorArgumentPassTest.php b/Tests/Compiler/ResolveTaggedIteratorArgumentPassTest.php index a219f8600..2322817e8 100644 --- a/Tests/Compiler/ResolveTaggedIteratorArgumentPassTest.php +++ b/Tests/Compiler/ResolveTaggedIteratorArgumentPassTest.php @@ -26,15 +26,15 @@ public function testProcess() { $container = new ContainerBuilder(); $container->register('a', 'stdClass')->addTag('foo'); - $container->register('b', 'stdClass')->addTag('foo', array('priority' => 20)); - $container->register('c', 'stdClass')->addTag('foo', array('priority' => 10)); + $container->register('b', 'stdClass')->addTag('foo', ['priority' => 20]); + $container->register('c', 'stdClass')->addTag('foo', ['priority' => 10]); $container->register('d', 'stdClass')->setProperty('foos', new TaggedIteratorArgument('foo')); (new ResolveTaggedIteratorArgumentPass())->process($container); $properties = $container->getDefinition('d')->getProperties(); $expected = new TaggedIteratorArgument('foo'); - $expected->setValues(array(new Reference('b'), new Reference('c'), new Reference('a'))); + $expected->setValues([new Reference('b'), new Reference('c'), new Reference('a')]); $this->assertEquals($expected, $properties['foos']); } } diff --git a/Tests/Compiler/ValidateEnvPlaceholdersPassTest.php b/Tests/Compiler/ValidateEnvPlaceholdersPassTest.php index b5841f343..fa51898b5 100644 --- a/Tests/Compiler/ValidateEnvPlaceholdersPassTest.php +++ b/Tests/Compiler/ValidateEnvPlaceholdersPassTest.php @@ -29,12 +29,12 @@ public function testEnvsAreValidatedInConfig() $container->setParameter('env(NULLED)', null); $container->setParameter('env(FLOATISH)', 3.2); $container->registerExtension($ext = new EnvExtension()); - $container->prependExtensionConfig('env_extension', $expected = array( + $container->prependExtensionConfig('env_extension', $expected = [ 'scalar_node' => '%env(NULLED)%', 'scalar_node_not_empty' => '%env(FLOATISH)%', 'int_node' => '%env(int:FOO)%', 'float_node' => '%env(float:BAR)%', - )); + ]); $this->doProcess($container); @@ -46,9 +46,10 @@ public function testDefaultEnvWithoutPrefixIsValidatedInConfig() $container = new ContainerBuilder(); $container->setParameter('env(FLOATISH)', 3.2); $container->registerExtension($ext = new EnvExtension()); - $container->prependExtensionConfig('env_extension', $expected = array( + $container->prependExtensionConfig('env_extension', $expected = [ 'float_node' => '%env(FLOATISH)%', - )); + 'string_node' => '%env(UNDEFINED)%', + ]); $this->doProcess($container); @@ -63,9 +64,9 @@ public function testEnvsAreValidatedInConfigWithInvalidPlaceholder() { $container = new ContainerBuilder(); $container->registerExtension($ext = new EnvExtension()); - $container->prependExtensionConfig('env_extension', $expected = array( + $container->prependExtensionConfig('env_extension', $expected = [ 'bool_node' => '%env(const:BAZ)%', - )); + ]); $this->doProcess($container); @@ -80,9 +81,9 @@ public function testInvalidEnvInConfig() { $container = new ContainerBuilder(); $container->registerExtension(new EnvExtension()); - $container->prependExtensionConfig('env_extension', array( + $container->prependExtensionConfig('env_extension', [ 'int_node' => '%env(json:FOO)%', - )); + ]); $this->doProcess($container); } @@ -96,9 +97,9 @@ public function testNulledEnvInConfig() $container = new ContainerBuilder(); $container->setParameter('env(NULLED)', null); $container->registerExtension(new EnvExtension()); - $container->prependExtensionConfig('env_extension', array( + $container->prependExtensionConfig('env_extension', [ 'int_node' => '%env(NULLED)%', - )); + ]); $this->doProcess($container); } @@ -107,23 +108,23 @@ public function testValidateEnvOnMerge() { $container = new ContainerBuilder(); $container->registerExtension($ext = new EnvExtension()); - $container->prependExtensionConfig('env_extension', array( + $container->prependExtensionConfig('env_extension', [ 'int_node' => '%env(int:const:FOO)%', 'bool_node' => true, - )); - $container->prependExtensionConfig('env_extension', array( + ]); + $container->prependExtensionConfig('env_extension', [ 'int_node' => '%env(int:BAR)%', 'bool_node' => '%env(bool:int:BAZ)%', 'scalar_node' => '%env(BAZ)%', - )); + ]); $this->doProcess($container); - $expected = array( + $expected = [ 'int_node' => '%env(int:const:FOO)%', 'bool_node' => true, 'scalar_node' => '%env(BAZ)%', - ); + ]; $this->assertSame($expected, $container->resolveEnvPlaceholders($ext->getConfig())); } @@ -132,13 +133,13 @@ public function testConcatenatedEnvInConfig() { $container = new ContainerBuilder(); $container->registerExtension($ext = new EnvExtension()); - $container->prependExtensionConfig('env_extension', array( + $container->prependExtensionConfig('env_extension', [ 'scalar_node' => $expected = 'foo %env(BAR)% baz', - )); + ]); $this->doProcess($container); - $this->assertSame(array('scalar_node' => $expected), $container->resolveEnvPlaceholders($ext->getConfig())); + $this->assertSame(['scalar_node' => $expected], $container->resolveEnvPlaceholders($ext->getConfig())); } /** @@ -149,9 +150,9 @@ public function testEnvIsIncompatibleWithEnumNode() { $container = new ContainerBuilder(); $container->registerExtension(new EnvExtension()); - $container->prependExtensionConfig('env_extension', array( + $container->prependExtensionConfig('env_extension', [ 'enum_node' => '%env(FOO)%', - )); + ]); $this->doProcess($container); } @@ -164,9 +165,9 @@ public function testEnvIsIncompatibleWithArrayNode() { $container = new ContainerBuilder(); $container->registerExtension(new EnvExtension()); - $container->prependExtensionConfig('env_extension', array( + $container->prependExtensionConfig('env_extension', [ 'simple_array_node' => '%env(json:FOO)%', - )); + ]); $this->doProcess($container); } @@ -175,22 +176,22 @@ public function testNormalizedEnvIsCompatibleWithArrayNode() { $container = new ContainerBuilder(); $container->registerExtension($ext = new EnvExtension()); - $container->prependExtensionConfig('env_extension', array( + $container->prependExtensionConfig('env_extension', [ 'array_node' => $expected = '%env(CHILD)%', - )); + ]); $this->doProcess($container); - $this->assertSame(array('array_node' => array('child_node' => $expected)), $container->resolveEnvPlaceholders($ext->getConfig())); + $this->assertSame(['array_node' => ['child_node' => $expected]], $container->resolveEnvPlaceholders($ext->getConfig())); } public function testEnvIsNotUnset() { $container = new ContainerBuilder(); $container->registerExtension($ext = new EnvExtension()); - $container->prependExtensionConfig('env_extension', $expected = array( - 'array_node' => array('int_unset_at_zero' => '%env(int:CHILD)%'), - )); + $container->prependExtensionConfig('env_extension', $expected = [ + 'array_node' => ['int_unset_at_zero' => '%env(int:CHILD)%'], + ]); $this->doProcess($container); @@ -201,9 +202,9 @@ public function testEmptyEnvWhichCannotBeEmptyForScalarNode(): void { $container = new ContainerBuilder(); $container->registerExtension($ext = new EnvExtension()); - $container->prependExtensionConfig('env_extension', $expected = array( + $container->prependExtensionConfig('env_extension', $expected = [ 'scalar_node_not_empty' => '%env(SOME)%', - )); + ]); $this->doProcess($container); @@ -214,9 +215,9 @@ public function testEnvWithVariableNode(): void { $container = new ContainerBuilder(); $container->registerExtension($ext = new EnvExtension()); - $container->prependExtensionConfig('env_extension', $expected = array( + $container->prependExtensionConfig('env_extension', $expected = [ 'variable_node' => '%env(SOME)%', - )); + ]); $this->doProcess($container); @@ -234,15 +235,27 @@ public function testConfigurationWithoutRootNode(): void $this->addToAssertionCount(1); } + public function testEmptyConfigFromMoreThanOneSource() + { + $container = new ContainerBuilder(); + $container->registerExtension(new EnvExtension(new ConfigurationWithArrayNodeRequiringOneElement())); + $container->loadFromExtension('env_extension', []); + $container->loadFromExtension('env_extension', []); + + $this->doProcess($container); + + $this->addToAssertionCount(1); + } + public function testDiscardedEnvInConfig(): void { $container = new ContainerBuilder(); $container->setParameter('env(BOOLISH)', '1'); $container->setParameter('boolish', '%env(BOOLISH)%'); $container->registerExtension(new EnvExtension()); - $container->prependExtensionConfig('env_extension', array( - 'array_node' => array('bool_force_cast' => '%boolish%'), - )); + $container->prependExtensionConfig('env_extension', [ + 'array_node' => ['bool_force_cast' => '%boolish%'], + ]); $container->compile(true); @@ -272,8 +285,8 @@ public function getConfigTreeBuilder() ->booleanNode('bool_node')->end() ->arrayNode('array_node') ->beforeNormalization() - ->ifTrue(function ($value) { return !is_array($value); }) - ->then(function ($value) { return array('child_node' => $value); }) + ->ifTrue(function ($value) { return !\is_array($value); }) + ->then(function ($value) { return ['child_node' => $value]; }) ->end() ->beforeNormalization() ->ifArray() @@ -297,8 +310,16 @@ public function getConfigTreeBuilder() ->end() ->end() ->arrayNode('simple_array_node')->end() - ->enumNode('enum_node')->values(array('a', 'b'))->end() + ->enumNode('enum_node')->values(['a', 'b'])->end() ->variableNode('variable_node')->end() + ->scalarNode('string_node') + ->validate() + ->ifTrue(function ($value) { + return !\is_string($value); + }) + ->thenInvalid('%s is not a string') + ->end() + ->end() ->end(); return $treeBuilder; @@ -313,6 +334,24 @@ public function getConfigTreeBuilder() } } +class ConfigurationWithArrayNodeRequiringOneElement implements ConfigurationInterface +{ + public function getConfigTreeBuilder() + { + $treeBuilder = new TreeBuilder(); + $treeBuilder->root('env_extension') + ->children() + ->arrayNode('nodes') + ->isRequired() + ->requiresAtLeastOneElement() + ->scalarPrototype()->end() + ->end() + ->end(); + + return $treeBuilder; + } +} + class EnvExtension extends Extension { private $configuration; @@ -335,6 +374,10 @@ public function getConfiguration(array $config, ContainerBuilder $container) public function load(array $configs, ContainerBuilder $container) { + if (!array_filter($configs)) { + return; + } + try { $this->config = $this->processConfiguration($this->getConfiguration($configs, $container), $configs); } catch (TreeWithoutRootNodeException $e) { diff --git a/Tests/Config/ContainerParametersResourceCheckerTest.php b/Tests/Config/ContainerParametersResourceCheckerTest.php index a91934b3e..fc2d85ecf 100644 --- a/Tests/Config/ContainerParametersResourceCheckerTest.php +++ b/Tests/Config/ContainerParametersResourceCheckerTest.php @@ -30,7 +30,7 @@ class ContainerParametersResourceCheckerTest extends TestCase protected function setUp() { - $this->resource = new ContainerParametersResource(array('locales' => array('fr', 'en'), 'default_locale' => 'fr')); + $this->resource = new ContainerParametersResource(['locales' => ['fr', 'en'], 'default_locale' => 'fr']); $this->container = $this->getMockBuilder(ContainerInterface::class)->getMock(); $this->resourceChecker = new ContainerParametersResourceChecker($this->container); } @@ -52,26 +52,26 @@ public function testIsFresh(callable $mockContainer, $expected) public function isFreshProvider() { - yield 'not fresh on missing parameter' => array(function (\PHPUnit_Framework_MockObject_MockObject $container) { + yield 'not fresh on missing parameter' => [function (\PHPUnit_Framework_MockObject_MockObject $container) { $container->method('hasParameter')->with('locales')->willReturn(false); - }, false); + }, false]; - yield 'not fresh on different value' => array(function (\PHPUnit_Framework_MockObject_MockObject $container) { - $container->method('getParameter')->with('locales')->willReturn(array('nl', 'es')); - }, false); + yield 'not fresh on different value' => [function (\PHPUnit_Framework_MockObject_MockObject $container) { + $container->method('getParameter')->with('locales')->willReturn(['nl', 'es']); + }, false]; - yield 'fresh on every identical parameters' => array(function (\PHPUnit_Framework_MockObject_MockObject $container) { + yield 'fresh on every identical parameters' => [function (\PHPUnit_Framework_MockObject_MockObject $container) { $container->expects($this->exactly(2))->method('hasParameter')->willReturn(true); $container->expects($this->exactly(2))->method('getParameter') ->withConsecutive( - array($this->equalTo('locales')), - array($this->equalTo('default_locale')) + [$this->equalTo('locales')], + [$this->equalTo('default_locale')] ) - ->will($this->returnValueMap(array( - array('locales', array('fr', 'en')), - array('default_locale', 'fr'), - ))) + ->will($this->returnValueMap([ + ['locales', ['fr', 'en']], + ['default_locale', 'fr'], + ])) ; - }, true); + }, true]; } } diff --git a/Tests/Config/ContainerParametersResourceTest.php b/Tests/Config/ContainerParametersResourceTest.php index 4da4766f2..e177ac16b 100644 --- a/Tests/Config/ContainerParametersResourceTest.php +++ b/Tests/Config/ContainerParametersResourceTest.php @@ -21,7 +21,7 @@ class ContainerParametersResourceTest extends TestCase protected function setUp() { - $this->resource = new ContainerParametersResource(array('locales' => array('fr', 'en'), 'default_locale' => 'fr')); + $this->resource = new ContainerParametersResource(['locales' => ['fr', 'en'], 'default_locale' => 'fr']); } public function testToString() @@ -38,6 +38,6 @@ public function testSerializeUnserialize() public function testGetParameters() { - $this->assertSame(array('locales' => array('fr', 'en'), 'default_locale' => 'fr'), $this->resource->getParameters()); + $this->assertSame(['locales' => ['fr', 'en'], 'default_locale' => 'fr'], $this->resource->getParameters()); } } diff --git a/Tests/ContainerBuilderTest.php b/Tests/ContainerBuilderTest.php index a84025699..655865945 100644 --- a/Tests/ContainerBuilderTest.php +++ b/Tests/ContainerBuilderTest.php @@ -17,8 +17,9 @@ use PHPUnit\Framework\TestCase; use Psr\Container\ContainerInterface as PsrContainerInterface; use Symfony\Component\Config\Resource\ComposerResource; -use Symfony\Component\Config\Resource\ResourceInterface; use Symfony\Component\Config\Resource\DirectoryResource; +use Symfony\Component\Config\Resource\FileResource; +use Symfony\Component\Config\Resource\ResourceInterface; use Symfony\Component\DependencyInjection\Alias; use Symfony\Component\DependencyInjection\Argument\IteratorArgument; use Symfony\Component\DependencyInjection\Argument\RewindableGenerator; @@ -31,15 +32,14 @@ use Symfony\Component\DependencyInjection\Exception\RuntimeException; use Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException; use Symfony\Component\DependencyInjection\Loader\ClosureLoader; -use Symfony\Component\DependencyInjection\Reference; -use Symfony\Component\DependencyInjection\Tests\Fixtures\SimilarArgumentsDummy; -use Symfony\Component\DependencyInjection\TypedReference; -use Symfony\Component\DependencyInjection\ParameterBag\ParameterBag; use Symfony\Component\DependencyInjection\ParameterBag\EnvPlaceholderParameterBag; -use Symfony\Component\Config\Resource\FileResource; +use Symfony\Component\DependencyInjection\ParameterBag\ParameterBag; +use Symfony\Component\DependencyInjection\Reference; use Symfony\Component\DependencyInjection\ServiceLocator; -use Symfony\Component\DependencyInjection\Tests\Fixtures\CustomDefinition; use Symfony\Component\DependencyInjection\Tests\Fixtures\CaseSensitiveClass; +use Symfony\Component\DependencyInjection\Tests\Fixtures\CustomDefinition; +use Symfony\Component\DependencyInjection\Tests\Fixtures\SimilarArgumentsDummy; +use Symfony\Component\DependencyInjection\TypedReference; use Symfony\Component\ExpressionLanguage\Expression; class ContainerBuilderTest extends TestCase @@ -62,10 +62,10 @@ public function testDefaultRegisteredDefinitions() public function testDefinitions() { $builder = new ContainerBuilder(); - $definitions = array( + $definitions = [ 'foo' => new Definition('Bar\FooClass'), 'bar' => new Definition('BarClass'), - ); + ]; $builder->setDefinitions($definitions); $this->assertEquals($definitions, $builder->getDefinitions(), '->setDefinitions() sets the service definitions'); $this->assertTrue($builder->hasDefinition('foo'), '->hasDefinition() returns true if a service definition exists'); @@ -75,7 +75,7 @@ public function testDefinitions() $this->assertEquals($foo, $builder->getDefinition('foobar'), '->getDefinition() returns a service definition if defined'); $this->assertSame($builder->setDefinition('foobar', $foo = new Definition('FooBarClass')), $foo, '->setDefinition() implements a fluid interface by returning the service reference'); - $builder->addDefinitions($defs = array('foobar' => new Definition('FooBarClass'))); + $builder->addDefinitions($defs = ['foobar' => new Definition('FooBarClass')]); $this->assertEquals(array_merge($definitions, $defs), $builder->getDefinitions(), '->addDefinitions() adds the service definitions'); try { @@ -150,7 +150,7 @@ public function testGetReturnsNullIfServiceDoesNotExistAndInvalidReferenceIsUsed public function testGetThrowsCircularReferenceExceptionIfServiceHasReferenceToItself() { $builder = new ContainerBuilder(); - $builder->register('baz', 'stdClass')->setArguments(array(new Reference('baz'))); + $builder->register('baz', 'stdClass')->setArguments([new Reference('baz')]); $builder->get('baz'); } @@ -195,6 +195,38 @@ public function testNonSharedServicesReturnsDifferentInstances() $this->assertNotSame($builder->get('bar'), $builder->get('bar')); } + /** + * @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException + * @dataProvider provideBadId + */ + public function testBadAliasId($id) + { + $builder = new ContainerBuilder(); + $builder->setAlias($id, 'foo'); + } + + /** + * @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException + * @dataProvider provideBadId + */ + public function testBadDefinitionId($id) + { + $builder = new ContainerBuilder(); + $builder->setDefinition($id, new Definition('Foo')); + } + + public function provideBadId() + { + return [ + [''], + ["\0"], + ["\r"], + ["\n"], + ["'"], + ['ab\\'], + ]; + } + /** * @expectedException \Symfony\Component\DependencyInjection\Exception\RuntimeException * @expectedExceptionMessage You have requested a synthetic service ("foo"). The DIC does not know how to construct this service. @@ -221,13 +253,13 @@ public function testGetServiceIds() $builder->bar = $bar = new \stdClass(); $builder->register('bar', 'stdClass'); $this->assertEquals( - array( + [ 'service_container', 'foo', 'bar', 'Psr\Container\ContainerInterface', 'Symfony\Component\DependencyInjection\ContainerInterface', - ), + ], $builder->getServiceIds(), '->getServiceIds() returns all defined service ids' ); @@ -284,7 +316,7 @@ public function testGetAliases() public function testSetAliases() { $builder = new ContainerBuilder(); - $builder->setAliases(array('bar' => 'foo', 'foobar' => 'foo')); + $builder->setAliases(['bar' => 'foo', 'foobar' => 'foo']); $aliases = $builder->getAliases(); $this->assertArrayHasKey('bar', $aliases); @@ -294,8 +326,8 @@ public function testSetAliases() public function testAddAliases() { $builder = new ContainerBuilder(); - $builder->setAliases(array('bar' => 'foo')); - $builder->addAliases(array('foobar' => 'foo')); + $builder->setAliases(['bar' => 'foo']); + $builder->addAliases(['foobar' => 'foo']); $aliases = $builder->getAliases(); $this->assertArrayHasKey('bar', $aliases); @@ -317,7 +349,7 @@ public function testAliasesKeepInvalidBehavior() $builder = new ContainerBuilder(); $aliased = new Definition('stdClass'); - $aliased->addMethodCall('setBar', array(new Reference('bar', ContainerInterface::IGNORE_ON_INVALID_REFERENCE))); + $aliased->addMethodCall('setBar', [new Reference('bar', ContainerInterface::IGNORE_ON_INVALID_REFERENCE)]); $builder->setDefinition('aliased', $aliased); $builder->setAlias('alias', 'aliased'); @@ -333,7 +365,7 @@ public function testAddGetCompilerPass() $builder->addCompilerPass($pass2 = $this->getMockBuilder('Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface')->getMock(), PassConfig::TYPE_BEFORE_OPTIMIZATION, 10); $passes = $builder->getCompiler()->getPassConfig()->getPasses(); - $this->assertCount(count($passes) - 2, $defaultPasses); + $this->assertCount(\count($passes) - 2, $defaultPasses); // Pass 1 is executed later $this->assertTrue(array_search($pass1, $passes, true) > array_search($pass2, $passes, true)); } @@ -358,7 +390,7 @@ public function testCreateProxyWithRealServiceInstantiator() $foo1 = $builder->get('foo1'); $this->assertSame($foo1, $builder->get('foo1'), 'The same proxy is retrieved on multiple subsequent calls'); - $this->assertSame('Bar\FooClass', get_class($foo1)); + $this->assertSame('Bar\FooClass', \get_class($foo1)); } public function testCreateServiceClass() @@ -373,18 +405,18 @@ public function testCreateServiceArguments() { $builder = new ContainerBuilder(); $builder->register('bar', 'stdClass'); - $builder->register('foo1', 'Bar\FooClass')->addArgument(array('foo' => '%value%', '%value%' => 'foo', new Reference('bar'), '%%unescape_it%%')); + $builder->register('foo1', 'Bar\FooClass')->addArgument(['foo' => '%value%', '%value%' => 'foo', new Reference('bar'), '%%unescape_it%%']); $builder->setParameter('value', 'bar'); - $this->assertEquals(array('foo' => 'bar', 'bar' => 'foo', $builder->get('bar'), '%unescape_it%'), $builder->get('foo1')->arguments, '->createService() replaces parameters and service references in the arguments provided by the service definition'); + $this->assertEquals(['foo' => 'bar', 'bar' => 'foo', $builder->get('bar'), '%unescape_it%'], $builder->get('foo1')->arguments, '->createService() replaces parameters and service references in the arguments provided by the service definition'); } public function testCreateServiceFactory() { $builder = new ContainerBuilder(); $builder->register('foo', 'Bar\FooClass')->setFactory('Bar\FooClass::getInstance'); - $builder->register('qux', 'Bar\FooClass')->setFactory(array('Bar\FooClass', 'getInstance')); - $builder->register('bar', 'Bar\FooClass')->setFactory(array(new Definition('Bar\FooClass'), 'getInstance')); - $builder->register('baz', 'Bar\FooClass')->setFactory(array(new Reference('bar'), 'getInstance')); + $builder->register('qux', 'Bar\FooClass')->setFactory(['Bar\FooClass', 'getInstance']); + $builder->register('bar', 'Bar\FooClass')->setFactory([new Definition('Bar\FooClass'), 'getInstance']); + $builder->register('baz', 'Bar\FooClass')->setFactory([new Reference('bar'), 'getInstance']); $this->assertTrue($builder->get('foo')->called, '->createService() calls the factory method to create the service instance'); $this->assertTrue($builder->get('qux')->called, '->createService() calls the factory method to create the service instance'); @@ -396,38 +428,38 @@ public function testCreateServiceMethodCalls() { $builder = new ContainerBuilder(); $builder->register('bar', 'stdClass'); - $builder->register('foo1', 'Bar\FooClass')->addMethodCall('setBar', array(array('%value%', new Reference('bar')))); + $builder->register('foo1', 'Bar\FooClass')->addMethodCall('setBar', [['%value%', new Reference('bar')]]); $builder->setParameter('value', 'bar'); - $this->assertEquals(array('bar', $builder->get('bar')), $builder->get('foo1')->bar, '->createService() replaces the values in the method calls arguments'); + $this->assertEquals(['bar', $builder->get('bar')], $builder->get('foo1')->bar, '->createService() replaces the values in the method calls arguments'); } public function testCreateServiceMethodCallsWithEscapedParam() { $builder = new ContainerBuilder(); $builder->register('bar', 'stdClass'); - $builder->register('foo1', 'Bar\FooClass')->addMethodCall('setBar', array(array('%%unescape_it%%'))); + $builder->register('foo1', 'Bar\FooClass')->addMethodCall('setBar', [['%%unescape_it%%']]); $builder->setParameter('value', 'bar'); - $this->assertEquals(array('%unescape_it%'), $builder->get('foo1')->bar, '->createService() replaces the values in the method calls arguments'); + $this->assertEquals(['%unescape_it%'], $builder->get('foo1')->bar, '->createService() replaces the values in the method calls arguments'); } public function testCreateServiceProperties() { $builder = new ContainerBuilder(); $builder->register('bar', 'stdClass'); - $builder->register('foo1', 'Bar\FooClass')->setProperty('bar', array('%value%', new Reference('bar'), '%%unescape_it%%')); + $builder->register('foo1', 'Bar\FooClass')->setProperty('bar', ['%value%', new Reference('bar'), '%%unescape_it%%']); $builder->setParameter('value', 'bar'); - $this->assertEquals(array('bar', $builder->get('bar'), '%unescape_it%'), $builder->get('foo1')->bar, '->createService() replaces the values in the properties'); + $this->assertEquals(['bar', $builder->get('bar'), '%unescape_it%'], $builder->get('foo1')->bar, '->createService() replaces the values in the properties'); } public function testCreateServiceConfigurator() { $builder = new ContainerBuilder(); $builder->register('foo1', 'Bar\FooClass')->setConfigurator('sc_configure'); - $builder->register('foo2', 'Bar\FooClass')->setConfigurator(array('%class%', 'configureStatic')); + $builder->register('foo2', 'Bar\FooClass')->setConfigurator(['%class%', 'configureStatic']); $builder->setParameter('class', 'BazClass'); $builder->register('baz', 'BazClass'); - $builder->register('foo3', 'Bar\FooClass')->setConfigurator(array(new Reference('baz'), 'configure')); - $builder->register('foo4', 'Bar\FooClass')->setConfigurator(array($builder->getDefinition('baz'), 'configure')); + $builder->register('foo3', 'Bar\FooClass')->setConfigurator([new Reference('baz'), 'configure']); + $builder->register('foo4', 'Bar\FooClass')->setConfigurator([$builder->getDefinition('baz'), 'configure']); $builder->register('foo5', 'Bar\FooClass')->setConfigurator('foo'); $this->assertTrue($builder->get('foo1')->configured, '->createService() calls the configurator'); @@ -449,10 +481,10 @@ public function testCreateServiceWithIteratorArgument() $builder->register('bar', 'stdClass'); $builder ->register('lazy_context', 'LazyContext') - ->setArguments(array( - new IteratorArgument(array('k1' => new Reference('bar'), new Reference('invalid', ContainerInterface::IGNORE_ON_INVALID_REFERENCE))), - new IteratorArgument(array()), - )) + ->setArguments([ + new IteratorArgument(['k1' => new Reference('bar'), new Reference('invalid', ContainerInterface::IGNORE_ON_INVALID_REFERENCE)]), + new IteratorArgument([]), + ]) ; $lazyContext = $builder->get('lazy_context'); @@ -494,7 +526,7 @@ public function testCreateServiceWithExpression() $builder = new ContainerBuilder(); $builder->setParameter('bar', 'bar'); $builder->register('bar', 'BarClass'); - $builder->register('foo', 'Bar\FooClass')->addArgument(array('foo' => new Expression('service("bar").foo ~ parameter("bar")'))); + $builder->register('foo', 'Bar\FooClass')->addArgument(['foo' => new Expression('service("bar").foo ~ parameter("bar")')]); $this->assertEquals('foobar', $builder->get('foo')->arguments['foo']); } @@ -503,7 +535,7 @@ public function testResolveServices() $builder = new ContainerBuilder(); $builder->register('foo', 'Bar\FooClass'); $this->assertEquals($builder->get('foo'), $builder->resolveServices(new Reference('foo')), '->resolveServices() resolves service references to service instances'); - $this->assertEquals(array('foo' => array('foo', $builder->get('foo'))), $builder->resolveServices(array('foo' => array('foo', new Reference('foo')))), '->resolveServices() resolves service references to service instances in nested arrays'); + $this->assertEquals(['foo' => ['foo', $builder->get('foo')]], $builder->resolveServices(['foo' => ['foo', new Reference('foo')]]), '->resolveServices() resolves service references to service instances in nested arrays'); $this->assertEquals($builder->get('foo'), $builder->resolveServices(new Expression('service("foo")')), '->resolveServices() resolves expressions'); } @@ -531,25 +563,25 @@ public function testResolveServicesWithCustomDefinitionClass() public function testMerge() { - $container = new ContainerBuilder(new ParameterBag(array('bar' => 'foo'))); + $container = new ContainerBuilder(new ParameterBag(['bar' => 'foo'])); $container->setResourceTracking(false); - $config = new ContainerBuilder(new ParameterBag(array('foo' => 'bar'))); + $config = new ContainerBuilder(new ParameterBag(['foo' => 'bar'])); $container->merge($config); - $this->assertEquals(array('bar' => 'foo', 'foo' => 'bar'), $container->getParameterBag()->all(), '->merge() merges current parameters with the loaded ones'); + $this->assertEquals(['bar' => 'foo', 'foo' => 'bar'], $container->getParameterBag()->all(), '->merge() merges current parameters with the loaded ones'); - $container = new ContainerBuilder(new ParameterBag(array('bar' => 'foo'))); + $container = new ContainerBuilder(new ParameterBag(['bar' => 'foo'])); $container->setResourceTracking(false); - $config = new ContainerBuilder(new ParameterBag(array('foo' => '%bar%'))); + $config = new ContainerBuilder(new ParameterBag(['foo' => '%bar%'])); $container->merge($config); $container->compile(); - $this->assertEquals(array('bar' => 'foo', 'foo' => 'foo'), $container->getParameterBag()->all(), '->merge() evaluates the values of the parameters towards already defined ones'); + $this->assertEquals(['bar' => 'foo', 'foo' => 'foo'], $container->getParameterBag()->all(), '->merge() evaluates the values of the parameters towards already defined ones'); - $container = new ContainerBuilder(new ParameterBag(array('bar' => 'foo'))); + $container = new ContainerBuilder(new ParameterBag(['bar' => 'foo'])); $container->setResourceTracking(false); - $config = new ContainerBuilder(new ParameterBag(array('foo' => '%bar%', 'baz' => '%foo%'))); + $config = new ContainerBuilder(new ParameterBag(['foo' => '%bar%', 'baz' => '%foo%'])); $container->merge($config); $container->compile(); - $this->assertEquals(array('bar' => 'foo', 'foo' => 'foo', 'baz' => 'foo'), $container->getParameterBag()->all(), '->merge() evaluates the values of the parameters towards already defined ones'); + $this->assertEquals(['bar' => 'foo', 'foo' => 'foo', 'baz' => 'foo'], $container->getParameterBag()->all(), '->merge() evaluates the values of the parameters towards already defined ones'); $container = new ContainerBuilder(); $container->setResourceTracking(false); @@ -559,7 +591,7 @@ public function testMerge() $config->setDefinition('baz', new Definition('BazClass')); $config->setAlias('alias_for_foo', 'foo'); $container->merge($config); - $this->assertEquals(array('service_container', 'foo', 'bar', 'baz'), array_keys($container->getDefinitions()), '->merge() merges definitions already defined ones'); + $this->assertEquals(['service_container', 'foo', 'bar', 'baz'], array_keys($container->getDefinitions()), '->merge() merges definitions already defined ones'); $aliases = $container->getAliases(); $this->assertArrayHasKey('alias_for_foo', $aliases); @@ -576,16 +608,16 @@ public function testMerge() $bag = new EnvPlaceholderParameterBag(); $bag->get('env(Foo)'); $config = new ContainerBuilder($bag); - $this->assertSame(array('%env(Bar)%'), $config->resolveEnvPlaceholders(array($bag->get('env(Bar)')))); + $this->assertSame(['%env(Bar)%'], $config->resolveEnvPlaceholders([$bag->get('env(Bar)')])); $container->merge($config); - $this->assertEquals(array('Foo' => 0, 'Bar' => 1), $container->getEnvCounters()); + $this->assertEquals(['Foo' => 0, 'Bar' => 1], $container->getEnvCounters()); $container = new ContainerBuilder(); $config = new ContainerBuilder(); $childDefA = $container->registerForAutoconfiguration('AInterface'); $childDefB = $config->registerForAutoconfiguration('BInterface'); $container->merge($config); - $this->assertSame(array('AInterface' => $childDefA, 'BInterface' => $childDefB), $container->getAutoconfiguredInstanceof()); + $this->assertSame(['AInterface' => $childDefA, 'BInterface' => $childDefB], $container->getAutoconfiguredInstanceof()); } /** @@ -620,7 +652,7 @@ public function testResolveEnvValuesWithArray() { $_ENV['ANOTHER_DUMMY_ENV_VAR'] = 'dummy'; - $dummyArray = array('1' => 'one', '2' => 'two'); + $dummyArray = ['1' => 'one', '2' => 'two']; $container = new ContainerBuilder(); $container->setParameter('dummy', '%env(ANOTHER_DUMMY_ENV_VAR)%'); @@ -673,7 +705,7 @@ public function testCompileWithArrayResolveEnv() $container->setParameter('foo', '%env(json:ARRAY)%'); $container->compile(true); - $this->assertSame(array('foo' => 'bar'), $container->getParameter('foo')); + $this->assertSame(['foo' => 'bar'], $container->getParameter('foo')); putenv('ARRAY'); } @@ -688,7 +720,7 @@ public function testCompileWithArrayAndAnotherResolveEnv() $container->setParameter('bar', '%env(DUMMY_ENV_VAR)%'); $container->compile(true); - $this->assertSame(array('foo' => 'bar'), $container->getParameter('foo')); + $this->assertSame(['foo' => 'bar'], $container->getParameter('foo')); $this->assertSame('abc', $container->getParameter('bar')); putenv('DUMMY_ENV_VAR'); @@ -745,9 +777,9 @@ public function testCastEnv() $container->register('foo', 'stdClass') ->setPublic(true) - ->setProperties(array( + ->setProperties([ 'fake' => '%env(int:FAKE)%', - )); + ]); $container->compile(true); @@ -761,9 +793,9 @@ public function testEnvAreNullable() $container->register('foo', 'stdClass') ->setPublic(true) - ->setProperties(array( + ->setProperties([ 'fake' => '%env(int:FAKE)%', - )); + ]); $container->compile(true); @@ -775,23 +807,23 @@ public function testEnvInId() $container = include __DIR__.'/Fixtures/containers/container_env_in_id.php'; $container->compile(true); - $expected = array( + $expected = [ 'service_container', 'foo', 'bar', 'bar_%env(BAR)%', - ); + ]; $this->assertSame($expected, array_keys($container->getDefinitions())); - $expected = array( + $expected = [ PsrContainerInterface::class => true, ContainerInterface::class => true, 'baz_%env(BAR)%' => true, 'bar_%env(BAR)%' => true, - ); + ]; $this->assertSame($expected, $container->getRemovedIds()); - $this->assertSame(array('baz_bar'), array_keys($container->getDefinition('foo')->getArgument(1))); + $this->assertSame(['baz_bar'], array_keys($container->getDefinition('foo')->getArgument(1))); } /** @@ -829,17 +861,17 @@ public function testfindTaggedServiceIds() $builder = new ContainerBuilder(); $builder ->register('foo', 'Bar\FooClass') - ->addTag('foo', array('foo' => 'foo')) - ->addTag('bar', array('bar' => 'bar')) - ->addTag('foo', array('foofoo' => 'foofoo')) + ->addTag('foo', ['foo' => 'foo']) + ->addTag('bar', ['bar' => 'bar']) + ->addTag('foo', ['foofoo' => 'foofoo']) ; - $this->assertEquals($builder->findTaggedServiceIds('foo'), array( - 'foo' => array( - array('foo' => 'foo'), - array('foofoo' => 'foofoo'), - ), - ), '->findTaggedServiceIds() returns an array of service ids and its tag attributes'); - $this->assertEquals(array(), $builder->findTaggedServiceIds('foobar'), '->findTaggedServiceIds() returns an empty array if there is annotated services'); + $this->assertEquals($builder->findTaggedServiceIds('foo'), [ + 'foo' => [ + ['foo' => 'foo'], + ['foofoo' => 'foofoo'], + ], + ], '->findTaggedServiceIds() returns an array of service ids and its tag attributes'); + $this->assertEquals([], $builder->findTaggedServiceIds('foobar'), '->findTaggedServiceIds() returns an empty array if there is annotated services'); } public function testFindUnusedTags() @@ -847,11 +879,11 @@ public function testFindUnusedTags() $builder = new ContainerBuilder(); $builder ->register('foo', 'Bar\FooClass') - ->addTag('kernel.event_listener', array('foo' => 'foo')) - ->addTag('kenrel.event_listener', array('bar' => 'bar')) + ->addTag('kernel.event_listener', ['foo' => 'foo']) + ->addTag('kenrel.event_listener', ['bar' => 'bar']) ; $builder->findTaggedServiceIds('kernel.event_listener'); - $this->assertEquals(array('kenrel.event_listener'), $builder->findUnusedTags(), '->findUnusedTags() returns an array with unused tags'); + $this->assertEquals(['kenrel.event_listener'], $builder->findUnusedTags(), '->findUnusedTags() returns an array with unused tags'); } public function testFindDefinition() @@ -955,15 +987,15 @@ public function testResources() $container = new ContainerBuilder(); $container->addResource($a = new FileResource(__DIR__.'/Fixtures/xml/services1.xml')); $container->addResource($b = new FileResource(__DIR__.'/Fixtures/xml/services2.xml')); - $resources = array(); + $resources = []; foreach ($container->getResources() as $resource) { if (false === strpos($resource, '.php')) { $resources[] = $resource; } } - $this->assertEquals(array($a, $b), $resources, '->getResources() returns an array of resources read for the current configuration'); - $this->assertSame($container, $container->setResources(array())); - $this->assertEquals(array(), $container->getResources()); + $this->assertEquals([$a, $b], $resources, '->getResources() returns an array of resources read for the current configuration'); + $this->assertSame($container, $container->setResources([])); + $this->assertEquals([], $container->getResources()); } public function testFileExists() @@ -972,18 +1004,18 @@ public function testFileExists() $A = new ComposerResource(); $a = new FileResource(__DIR__.'/Fixtures/xml/services1.xml'); $b = new FileResource(__DIR__.'/Fixtures/xml/services2.xml'); - $c = new DirectoryResource($dir = dirname($b)); + $c = new DirectoryResource($dir = \dirname($b)); $this->assertTrue($container->fileExists((string) $a) && $container->fileExists((string) $b) && $container->fileExists($dir)); - $resources = array(); + $resources = []; foreach ($container->getResources() as $resource) { if (false === strpos($resource, '.php')) { $resources[] = $resource; } } - $this->assertEquals(array($A, $a, $b, $c), $resources, '->getResources() returns an array of resources read for the current configuration'); + $this->assertEquals([$A, $a, $b, $c], $resources, '->getResources() returns an array of resources read for the current configuration'); } public function testExtension() @@ -1014,28 +1046,28 @@ public function testRegisteredAndLoadedExtension() { $extension = $this->getMockBuilder('Symfony\\Component\\DependencyInjection\\Extension\\ExtensionInterface')->getMock(); $extension->expects($this->exactly(2))->method('getAlias')->will($this->returnValue('project')); - $extension->expects($this->once())->method('load')->with(array(array('foo' => 'bar'))); + $extension->expects($this->once())->method('load')->with([['foo' => 'bar']]); $container = new ContainerBuilder(); $container->setResourceTracking(false); $container->registerExtension($extension); - $container->loadFromExtension('project', array('foo' => 'bar')); + $container->loadFromExtension('project', ['foo' => 'bar']); $container->compile(); } public function testPrivateServiceUser() { $fooDefinition = new Definition('BarClass'); - $fooUserDefinition = new Definition('BarUserClass', array(new Reference('bar'))); + $fooUserDefinition = new Definition('BarUserClass', [new Reference('bar')]); $container = new ContainerBuilder(); $container->setResourceTracking(false); $fooDefinition->setPublic(false); - $container->addDefinitions(array( + $container->addDefinitions([ 'bar' => $fooDefinition, 'bar_user' => $fooUserDefinition->setPublic(true), - )); + ]); $container->compile(); $this->assertInstanceOf('BarClass', $container->get('bar_user')->bar); @@ -1090,15 +1122,15 @@ public function testExtensionConfig() $configs = $container->getExtensionConfig('foo'); $this->assertEmpty($configs); - $first = array('foo' => 'bar'); + $first = ['foo' => 'bar']; $container->prependExtensionConfig('foo', $first); $configs = $container->getExtensionConfig('foo'); - $this->assertEquals(array($first), $configs); + $this->assertEquals([$first], $configs); - $second = array('ding' => 'dong'); + $second = ['ding' => 'dong']; $container->prependExtensionConfig('foo', $second); $configs = $container->getExtensionConfig('foo'); - $this->assertEquals(array($second, $first), $configs); + $this->assertEquals([$second, $first], $configs); } public function testAbstractAlias() @@ -1158,7 +1190,7 @@ public function testInlinedDefinitions() $container->register('bar', 'BarClass') ->setProperty('foo', $definition) - ->addMethodCall('setBaz', array($definition)); + ->addMethodCall('setBaz', [$definition]); $barUser = $container->get('bar_user'); $bar = $container->get('bar'); @@ -1176,11 +1208,11 @@ public function testThrowsCircularExceptionForCircularAliases() { $builder = new ContainerBuilder(); - $builder->setAliases(array( + $builder->setAliases([ 'foo' => new Alias('app.test_class'), 'app.test_class' => new Alias('App\\TestClass'), 'App\\TestClass' => new Alias('app.test_class'), - )); + ]); $builder->findDefinition('foo'); } @@ -1238,6 +1270,30 @@ public function testNoClassFromGlobalNamespaceClassId() $container->compile(); } + /** + * @expectedException \Symfony\Component\DependencyInjection\Exception\RuntimeException + * @expectedExceptionMessage The definition for "\DateTime" has no class attribute, and appears to reference a class or interface in the global namespace. + */ + public function testNoClassFromGlobalNamespaceClassIdWithLeadingSlash() + { + $container = new ContainerBuilder(); + + $container->register('\\'.\DateTime::class); + $container->compile(); + } + + /** + * @expectedException \Symfony\Component\DependencyInjection\Exception\RuntimeException + * @expectedExceptionMessage The definition for "\Symfony\Component\DependencyInjection\Tests\FooClass" has no class attribute, and appears to reference a class or interface. Please specify the class attribute explicitly or remove the leading backslash by renaming the service to "Symfony\Component\DependencyInjection\Tests\FooClass" to get rid of this error. + */ + public function testNoClassFromNamespaceClassIdWithLeadingSlash() + { + $container = new ContainerBuilder(); + + $container->register('\\'.FooClass::class); + $container->compile(); + } + /** * @expectedException \Symfony\Component\DependencyInjection\Exception\RuntimeException * @expectedExceptionMessage The definition for "123_abc" has no class. @@ -1267,12 +1323,12 @@ public function testServiceLocator() $container = new ContainerBuilder(); $container->register('foo_service', ServiceLocator::class) ->setPublic(true) - ->addArgument(array( + ->addArgument([ 'bar' => new ServiceClosureArgument(new Reference('bar_service')), 'baz' => new ServiceClosureArgument(new TypedReference('baz_service', 'stdClass')), - )) + ]) ; - $container->register('bar_service', 'stdClass')->setArguments(array(new Reference('baz_service')))->setPublic(true); + $container->register('bar_service', 'stdClass')->setArguments([new Reference('baz_service')])->setPublic(true); $container->register('baz_service', 'stdClass')->setPublic(false); $container->compile(); @@ -1293,7 +1349,7 @@ public function testUninitializedReference() $this->assertNull($bar->closures[0]()); $this->assertNull($bar->closures[1]()); $this->assertNull($bar->closures[2]()); - $this->assertSame(array(), iterator_to_array($bar->iter)); + $this->assertSame([], iterator_to_array($bar->iter)); $container = include __DIR__.'/Fixtures/containers/container_uninitialized_ref.php'; $container->compile(); @@ -1309,7 +1365,7 @@ public function testUninitializedReference() $this->assertEquals(new \stdClass(), $bar->closures[0]()); $this->assertNull($bar->closures[1]()); $this->assertEquals(new \stdClass(), $bar->closures[2]()); - $this->assertEquals(array('foo1' => new \stdClass(), 'foo3' => new \stdClass()), iterator_to_array($bar->iter)); + $this->assertEquals(['foo1' => new \stdClass(), 'foo3' => new \stdClass()], iterator_to_array($bar->iter)); } /** @@ -1325,16 +1381,27 @@ public function testAlmostCircular($visibility) $foo2 = $container->get('foo2'); $this->assertSame($foo2, $foo2->bar->foobar->foo); - $this->assertSame(array(), (array) $container->get('foobar4')); + $this->assertSame([], (array) $container->get('foobar4')); $foo5 = $container->get('foo5'); $this->assertSame($foo5, $foo5->bar->foo); + + $manager = $container->get('manager'); + $this->assertEquals(new \stdClass(), $manager); + + $manager = $container->get('manager2'); + $this->assertEquals(new \stdClass(), $manager); + + $foo6 = $container->get('foo6'); + $this->assertEquals((object) ['bar6' => (object) []], $foo6); + + $this->assertInstanceOf(\stdClass::class, $container->get('root')); } public function provideAlmostCircular() { - yield array('public'); - yield array('private'); + yield ['public']; + yield ['private']; } public function testRegisterForAutoconfiguration() @@ -1342,7 +1409,7 @@ public function testRegisterForAutoconfiguration() $container = new ContainerBuilder(); $childDefA = $container->registerForAutoconfiguration('AInterface'); $childDefB = $container->registerForAutoconfiguration('BInterface'); - $this->assertSame(array('AInterface' => $childDefA, 'BInterface' => $childDefB), $container->getAutoconfiguredInstanceof()); + $this->assertSame(['AInterface' => $childDefA, 'BInterface' => $childDefB], $container->getAutoconfiguredInstanceof()); // when called multiple times, the same instance is returned $this->assertSame($childDefA, $container->registerForAutoconfiguration('AInterface')); @@ -1355,7 +1422,7 @@ public function testCaseSensitivity() $container->register('Foo', 'stdClass')->setProperty('foo', new Reference('foo'))->setPublic(false); $container->register('fOO', 'stdClass')->setProperty('Foo', new Reference('Foo'))->setPublic(true); - $this->assertSame(array('service_container', 'foo', 'Foo', 'fOO', 'Psr\Container\ContainerInterface', 'Symfony\Component\DependencyInjection\ContainerInterface'), $container->getServiceIds()); + $this->assertSame(['service_container', 'foo', 'Foo', 'fOO', 'Psr\Container\ContainerInterface', 'Symfony\Component\DependencyInjection\ContainerInterface'], $container->getServiceIds()); $container->compile(); @@ -1365,7 +1432,7 @@ public function testCaseSensitivity() public function testParameterWithMixedCase() { - $container = new ContainerBuilder(new ParameterBag(array('foo' => 'bar', 'FOO' => 'BAR'))); + $container = new ContainerBuilder(new ParameterBag(['foo' => 'bar', 'FOO' => 'BAR'])); $container->register('foo', 'stdClass') ->setPublic(true) ->setProperty('foo', '%FOO%'); @@ -1378,20 +1445,20 @@ public function testParameterWithMixedCase() public function testArgumentsHaveHigherPriorityThanBindings() { $container = new ContainerBuilder(); - $container->register('class.via.bindings', CaseSensitiveClass::class)->setArguments(array( + $container->register('class.via.bindings', CaseSensitiveClass::class)->setArguments([ 'via-bindings', - )); - $container->register('class.via.argument', CaseSensitiveClass::class)->setArguments(array( + ]); + $container->register('class.via.argument', CaseSensitiveClass::class)->setArguments([ 'via-argument', - )); - $container->register('foo', SimilarArgumentsDummy::class)->setPublic(true)->setBindings(array( + ]); + $container->register('foo', SimilarArgumentsDummy::class)->setPublic(true)->setBindings([ CaseSensitiveClass::class => new Reference('class.via.bindings'), '$token' => '1234', - ))->setArguments(array( + ])->setArguments([ '$class1' => new Reference('class.via.argument'), - )); + ]); - $this->assertSame(array('service_container', 'class.via.bindings', 'class.via.argument', 'foo', 'Psr\Container\ContainerInterface', 'Symfony\Component\DependencyInjection\ContainerInterface'), $container->getServiceIds()); + $this->assertSame(['service_container', 'class.via.bindings', 'class.via.argument', 'foo', 'Psr\Container\ContainerInterface', 'Symfony\Component\DependencyInjection\ContainerInterface'], $container->getServiceIds()); $container->compile(); @@ -1399,6 +1466,21 @@ public function testArgumentsHaveHigherPriorityThanBindings() $this->assertSame('via-bindings', $container->get('foo')->class2->identifier); } + public function testUninitializedSyntheticReference() + { + $container = new ContainerBuilder(); + $container->register('foo', 'stdClass')->setPublic(true)->setSynthetic(true); + $container->register('bar', 'stdClass')->setPublic(true)->setShared(false) + ->setProperty('foo', new Reference('foo', ContainerInterface::IGNORE_ON_UNINITIALIZED_REFERENCE)); + + $container->compile(); + + $this->assertEquals((object) ['foo' => null], $container->get('bar')); + + $container->set('foo', (object) [123]); + $this->assertEquals((object) ['foo' => (object) [123]], $container->get('bar')); + } + public function testIdCanBeAnObjectAsLongAsItCanBeCastToString() { $id = new Reference('another_service'); @@ -1431,6 +1513,22 @@ public function testErroredDefinition() $container->get('errored_definition'); } + + public function testDecoratedSelfReferenceInvolvingPrivateServices() + { + $container = new ContainerBuilder(); + $container->register('foo', 'stdClass') + ->setPublic(false) + ->setProperty('bar', new Reference('foo')); + $container->register('baz', 'stdClass') + ->setPublic(false) + ->setProperty('inner', new Reference('baz.inner')) + ->setDecoratedService('foo'); + + $container->compile(); + + $this->assertSame(['service_container'], array_keys($container->getDefinitions())); + } } class FooClass diff --git a/Tests/ContainerTest.php b/Tests/ContainerTest.php index 2ad4ac34f..3089dc676 100644 --- a/Tests/ContainerTest.php +++ b/Tests/ContainerTest.php @@ -15,8 +15,8 @@ use Symfony\Component\DependencyInjection\Alias; use Symfony\Component\DependencyInjection\Container; use Symfony\Component\DependencyInjection\ContainerInterface; -use Symfony\Component\DependencyInjection\ParameterBag\ParameterBag; use Symfony\Component\DependencyInjection\ParameterBag\FrozenParameterBag; +use Symfony\Component\DependencyInjection\ParameterBag\ParameterBag; class ContainerTest extends TestCase { @@ -25,8 +25,8 @@ public function testConstructor() $sc = new Container(); $this->assertSame($sc, $sc->get('service_container'), '__construct() automatically registers itself as a service'); - $sc = new Container(new ParameterBag(array('foo' => 'bar'))); - $this->assertEquals(array('foo' => 'bar'), $sc->getParameterBag()->all(), '__construct() takes an array of parameters as its first argument'); + $sc = new Container(new ParameterBag(['foo' => 'bar'])); + $this->assertEquals(['foo' => 'bar'], $sc->getParameterBag()->all(), '__construct() takes an array of parameters as its first argument'); } /** @@ -39,18 +39,18 @@ public function testCamelize($id, $expected) public function dataForTestCamelize() { - return array( - array('foo_bar', 'FooBar'), - array('foo.bar', 'Foo_Bar'), - array('foo.bar_baz', 'Foo_BarBaz'), - array('foo._bar', 'Foo_Bar'), - array('foo_.bar', 'Foo_Bar'), - array('_foo', 'Foo'), - array('.foo', '_Foo'), - array('foo_', 'Foo'), - array('foo.', 'Foo_'), - array('foo\bar', 'Foo_Bar'), - ); + return [ + ['foo_bar', 'FooBar'], + ['foo.bar', 'Foo_Bar'], + ['foo.bar_baz', 'Foo_BarBaz'], + ['foo._bar', 'Foo_Bar'], + ['foo_.bar', 'Foo_Bar'], + ['_foo', 'Foo'], + ['.foo', '_Foo'], + ['foo_', 'Foo'], + ['foo.', 'Foo_'], + ['foo\bar', 'Foo_Bar'], + ]; } /** @@ -63,29 +63,29 @@ public function testUnderscore($id, $expected) public function dataForTestUnderscore() { - return array( - array('FooBar', 'foo_bar'), - array('Foo_Bar', 'foo.bar'), - array('Foo_BarBaz', 'foo.bar_baz'), - array('FooBar_BazQux', 'foo_bar.baz_qux'), - array('_Foo', '.foo'), - array('Foo_', 'foo.'), - ); + return [ + ['FooBar', 'foo_bar'], + ['Foo_Bar', 'foo.bar'], + ['Foo_BarBaz', 'foo.bar_baz'], + ['FooBar_BazQux', 'foo_bar.baz_qux'], + ['_Foo', '.foo'], + ['Foo_', 'foo.'], + ]; } public function testCompile() { - $sc = new Container(new ParameterBag(array('foo' => 'bar'))); + $sc = new Container(new ParameterBag(['foo' => 'bar'])); $this->assertFalse($sc->getParameterBag()->isResolved(), '->compile() resolves the parameter bag'); $sc->compile(); $this->assertTrue($sc->getParameterBag()->isResolved(), '->compile() resolves the parameter bag'); $this->assertInstanceOf('Symfony\Component\DependencyInjection\ParameterBag\FrozenParameterBag', $sc->getParameterBag(), '->compile() changes the parameter bag to a FrozenParameterBag instance'); - $this->assertEquals(array('foo' => 'bar'), $sc->getParameterBag()->all(), '->compile() copies the current parameters to the new parameter bag'); + $this->assertEquals(['foo' => 'bar'], $sc->getParameterBag()->all(), '->compile() copies the current parameters to the new parameter bag'); } public function testIsCompiled() { - $sc = new Container(new ParameterBag(array('foo' => 'bar'))); + $sc = new Container(new ParameterBag(['foo' => 'bar'])); $this->assertFalse($sc->isCompiled(), '->isCompiled() returns false if the container is not compiled'); $sc->compile(); $this->assertTrue($sc->isCompiled(), '->isCompiled() returns true if the container is compiled'); @@ -93,19 +93,19 @@ public function testIsCompiled() public function testIsCompiledWithFrozenParameters() { - $sc = new Container(new FrozenParameterBag(array('foo' => 'bar'))); + $sc = new Container(new FrozenParameterBag(['foo' => 'bar'])); $this->assertFalse($sc->isCompiled(), '->isCompiled() returns false if the container is not compiled but the parameter bag is already frozen'); } public function testGetParameterBag() { $sc = new Container(); - $this->assertEquals(array(), $sc->getParameterBag()->all(), '->getParameterBag() returns an empty array if no parameter has been defined'); + $this->assertEquals([], $sc->getParameterBag()->all(), '->getParameterBag() returns an empty array if no parameter has been defined'); } public function testGetSetParameter() { - $sc = new Container(new ParameterBag(array('foo' => 'bar'))); + $sc = new Container(new ParameterBag(['foo' => 'bar'])); $sc->setParameter('bar', 'foo'); $this->assertEquals('foo', $sc->getParameter('bar'), '->setParameter() sets the value of a new parameter'); @@ -123,7 +123,7 @@ public function testGetSetParameter() public function testGetSetParameterWithMixedCase() { - $sc = new Container(new ParameterBag(array('foo' => 'bar'))); + $sc = new Container(new ParameterBag(['foo' => 'bar'])); $sc->setParameter('Foo', 'baz1'); $this->assertEquals('bar', $sc->getParameter('foo')); @@ -135,11 +135,11 @@ public function testGetServiceIds() $sc = new Container(); $sc->set('foo', $obj = new \stdClass()); $sc->set('bar', $obj = new \stdClass()); - $this->assertEquals(array('service_container', 'foo', 'bar'), $sc->getServiceIds(), '->getServiceIds() returns all defined service ids'); + $this->assertEquals(['service_container', 'foo', 'bar'], $sc->getServiceIds(), '->getServiceIds() returns all defined service ids'); $sc = new ProjectServiceContainer(); $sc->set('foo', $obj = new \stdClass()); - $this->assertEquals(array('service_container', 'bar', 'foo_bar', 'foo.baz', 'circular', 'throw_exception', 'throws_exception_on_service_configuration', 'internal_dependency', 'foo'), $sc->getServiceIds(), '->getServiceIds() returns defined service ids by factory methods in the method map, followed by service ids defined by set()'); + $this->assertEquals(['service_container', 'bar', 'foo_bar', 'foo.baz', 'circular', 'throw_exception', 'throws_exception_on_service_configuration', 'internal_dependency', 'foo'], $sc->getServiceIds(), '->getServiceIds() returns defined service ids by factory methods in the method map, followed by service ids defined by set()'); } public function testSet() @@ -219,7 +219,7 @@ public function testCaseSensitivity() $sc->set('foo', $foo1 = new \stdClass()); $sc->set('Foo', $foo2 = new \stdClass()); - $this->assertSame(array('service_container', 'foo', 'Foo'), $sc->getServiceIds()); + $this->assertSame(['service_container', 'foo', 'Foo'], $sc->getServiceIds()); $this->assertSame($foo1, $sc->get('foo'), '->get() returns the service for the given id, case sensitively'); $this->assertSame($foo2, $sc->get('Foo'), '->get() returns the service for the given id, case sensitively'); } @@ -413,7 +413,7 @@ class ProjectServiceContainer extends Container public $__foo_baz; public $__internal; protected $privates; - protected $methodMap = array( + protected $methodMap = [ 'bar' => 'getBarService', 'foo_bar' => 'getFooBarService', 'foo.baz' => 'getFoo_BazService', @@ -421,7 +421,7 @@ class ProjectServiceContainer extends Container 'throw_exception' => 'getThrowExceptionService', 'throws_exception_on_service_configuration' => 'getThrowsExceptionOnServiceConfigurationService', 'internal_dependency' => 'getInternalDependencyService', - ); + ]; public function __construct() { @@ -431,8 +431,8 @@ public function __construct() $this->__foo_bar = new \stdClass(); $this->__foo_baz = new \stdClass(); $this->__internal = new \stdClass(); - $this->privates = array(); - $this->aliases = array('alias' => 'bar'); + $this->privates = []; + $this->aliases = ['alias' => 'bar']; } protected function getInternalService() diff --git a/Tests/CrossCheckTest.php b/Tests/CrossCheckTest.php index dbdbb7954..12e9ebe42 100644 --- a/Tests/CrossCheckTest.php +++ b/Tests/CrossCheckTest.php @@ -12,8 +12,8 @@ namespace Symfony\Component\DependencyInjection\Tests; use PHPUnit\Framework\TestCase; -use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\Config\FileLocator; +use Symfony\Component\DependencyInjection\ContainerBuilder; class CrossCheckTest extends TestCase { @@ -57,11 +57,11 @@ public function testCrossCheck($fixture, $type) $this->assertEquals($container2->getParameterBag()->all(), $container1->getParameterBag()->all(), '->getParameterBag() returns the same value for both containers'); $this->assertEquals(serialize($container2), serialize($container1), 'loading a dump from a previously loaded container returns the same container'); - $services1 = array(); + $services1 = []; foreach ($container1 as $id => $service) { $services1[$id] = serialize($service); } - $services2 = array(); + $services2 = []; foreach ($container2 as $id => $service) { $services2[$id] = serialize($service); } @@ -73,17 +73,17 @@ public function testCrossCheck($fixture, $type) public function crossCheckLoadersDumpers() { - return array( - array('services1.xml', 'xml'), - array('services2.xml', 'xml'), - array('services6.xml', 'xml'), - array('services8.xml', 'xml'), - array('services9.xml', 'xml'), - array('services1.yml', 'yaml'), - array('services2.yml', 'yaml'), - array('services6.yml', 'yaml'), - array('services8.yml', 'yaml'), - array('services9.yml', 'yaml'), - ); + return [ + ['services1.xml', 'xml'], + ['services2.xml', 'xml'], + ['services6.xml', 'xml'], + ['services8.xml', 'xml'], + ['services9.xml', 'xml'], + ['services1.yml', 'yaml'], + ['services2.yml', 'yaml'], + ['services6.yml', 'yaml'], + ['services8.yml', 'yaml'], + ['services9.yml', 'yaml'], + ]; } } diff --git a/Tests/DefinitionTest.php b/Tests/DefinitionTest.php index 0ed135915..67361753d 100644 --- a/Tests/DefinitionTest.php +++ b/Tests/DefinitionTest.php @@ -20,10 +20,10 @@ public function testConstructor() { $def = new Definition('stdClass'); $this->assertEquals('stdClass', $def->getClass(), '__construct() takes the class name as its first argument'); - $this->assertSame(array('class' => true), $def->getChanges()); + $this->assertSame(['class' => true], $def->getChanges()); - $def = new Definition('stdClass', array('foo')); - $this->assertEquals(array('foo'), $def->getArguments(), '__construct() takes an optional array of arguments as its second argument'); + $def = new Definition('stdClass', ['foo']); + $this->assertEquals(['foo'], $def->getArguments(), '__construct() takes an optional array of arguments as its second argument'); } public function testSetGetFactory() @@ -34,8 +34,8 @@ public function testSetGetFactory() $this->assertEquals('foo', $def->getFactory(), '->getFactory() returns the factory'); $def->setFactory('Foo::bar'); - $this->assertEquals(array('Foo', 'bar'), $def->getFactory(), '->setFactory() converts string static method call to the array'); - $this->assertSame(array('factory' => true), $def->getChanges()); + $this->assertEquals(['Foo', 'bar'], $def->getFactory(), '->setFactory() converts string static method call to the array'); + $this->assertSame(['factory' => true], $def->getChanges()); } public function testSetGetClass() @@ -50,20 +50,20 @@ public function testSetGetDecoratedService() $def = new Definition('stdClass'); $this->assertNull($def->getDecoratedService()); $def->setDecoratedService('foo', 'foo.renamed', 5); - $this->assertEquals(array('foo', 'foo.renamed', 5), $def->getDecoratedService()); + $this->assertEquals(['foo', 'foo.renamed', 5], $def->getDecoratedService()); $def->setDecoratedService(null); $this->assertNull($def->getDecoratedService()); $def = new Definition('stdClass'); $this->assertNull($def->getDecoratedService()); $def->setDecoratedService('foo', 'foo.renamed'); - $this->assertEquals(array('foo', 'foo.renamed', 0), $def->getDecoratedService()); + $this->assertEquals(['foo', 'foo.renamed', 0], $def->getDecoratedService()); $def->setDecoratedService(null); $this->assertNull($def->getDecoratedService()); $def = new Definition('stdClass'); $def->setDecoratedService('foo'); - $this->assertEquals(array('foo', null, 0), $def->getDecoratedService()); + $this->assertEquals(['foo', null, 0], $def->getDecoratedService()); $def->setDecoratedService(null); $this->assertNull($def->getDecoratedService()); @@ -82,23 +82,23 @@ public function testSetGetDecoratedService() public function testArguments() { $def = new Definition('stdClass'); - $this->assertSame($def, $def->setArguments(array('foo')), '->setArguments() implements a fluent interface'); - $this->assertEquals(array('foo'), $def->getArguments(), '->getArguments() returns the arguments'); + $this->assertSame($def, $def->setArguments(['foo']), '->setArguments() implements a fluent interface'); + $this->assertEquals(['foo'], $def->getArguments(), '->getArguments() returns the arguments'); $this->assertSame($def, $def->addArgument('bar'), '->addArgument() implements a fluent interface'); - $this->assertEquals(array('foo', 'bar'), $def->getArguments(), '->addArgument() adds an argument'); + $this->assertEquals(['foo', 'bar'], $def->getArguments(), '->addArgument() adds an argument'); } public function testMethodCalls() { $def = new Definition('stdClass'); - $this->assertSame($def, $def->setMethodCalls(array(array('foo', array('foo')))), '->setMethodCalls() implements a fluent interface'); - $this->assertEquals(array(array('foo', array('foo'))), $def->getMethodCalls(), '->getMethodCalls() returns the methods to call'); - $this->assertSame($def, $def->addMethodCall('bar', array('bar')), '->addMethodCall() implements a fluent interface'); - $this->assertEquals(array(array('foo', array('foo')), array('bar', array('bar'))), $def->getMethodCalls(), '->addMethodCall() adds a method to call'); + $this->assertSame($def, $def->setMethodCalls([['foo', ['foo']]]), '->setMethodCalls() implements a fluent interface'); + $this->assertEquals([['foo', ['foo']]], $def->getMethodCalls(), '->getMethodCalls() returns the methods to call'); + $this->assertSame($def, $def->addMethodCall('bar', ['bar']), '->addMethodCall() implements a fluent interface'); + $this->assertEquals([['foo', ['foo']], ['bar', ['bar']]], $def->getMethodCalls(), '->addMethodCall() adds a method to call'); $this->assertTrue($def->hasMethodCall('bar'), '->hasMethodCall() returns true if first argument is a method to call registered'); $this->assertFalse($def->hasMethodCall('no_registered'), '->hasMethodCall() returns false if first argument is not a method to call registered'); $this->assertSame($def, $def->removeMethodCall('bar'), '->removeMethodCall() implements a fluent interface'); - $this->assertEquals(array(array('foo', array('foo'))), $def->getMethodCalls(), '->removeMethodCall() removes a method to call'); + $this->assertEquals([['foo', ['foo']]], $def->getMethodCalls(), '->removeMethodCall() removes a method to call'); } /** @@ -179,12 +179,12 @@ public function testSetDeprecatedWithInvalidDeprecationTemplate($message) public function invalidDeprecationMessageProvider() { - return array( - "With \rs" => array("invalid \r message %service_id%"), - "With \ns" => array("invalid \n message %service_id%"), - 'With */s' => array('invalid */ message %service_id%'), - 'message not containing require %service_id% variable' => array('this is deprecated'), - ); + return [ + "With \rs" => ["invalid \r message %service_id%"], + "With \ns" => ["invalid \n message %service_id%"], + 'With */s' => ['invalid */ message %service_id%'], + 'message not containing require %service_id% variable' => ['this is deprecated'], + ]; } public function testSetGetConfigurator() @@ -198,18 +198,18 @@ public function testClearTags() { $def = new Definition('stdClass'); $this->assertSame($def, $def->clearTags(), '->clearTags() implements a fluent interface'); - $def->addTag('foo', array('foo' => 'bar')); + $def->addTag('foo', ['foo' => 'bar']); $def->clearTags(); - $this->assertEquals(array(), $def->getTags(), '->clearTags() removes all current tags'); + $this->assertEquals([], $def->getTags(), '->clearTags() removes all current tags'); } public function testClearTag() { $def = new Definition('stdClass'); $this->assertSame($def, $def->clearTags(), '->clearTags() implements a fluent interface'); - $def->addTag('1foo1', array('foo1' => 'bar1')); - $def->addTag('2foo2', array('foo2' => 'bar2')); - $def->addTag('3foo3', array('foo3' => 'bar3')); + $def->addTag('1foo1', ['foo1' => 'bar1']); + $def->addTag('2foo2', ['foo2' => 'bar2']); + $def->addTag('3foo3', ['foo3' => 'bar3']); $def->clearTag('2foo2'); $this->assertTrue($def->hasTag('1foo1')); $this->assertFalse($def->hasTag('2foo2')); @@ -222,18 +222,18 @@ public function testClearTag() public function testTags() { $def = new Definition('stdClass'); - $this->assertEquals(array(), $def->getTag('foo'), '->getTag() returns an empty array if the tag is not defined'); + $this->assertEquals([], $def->getTag('foo'), '->getTag() returns an empty array if the tag is not defined'); $this->assertFalse($def->hasTag('foo')); $this->assertSame($def, $def->addTag('foo'), '->addTag() implements a fluent interface'); $this->assertTrue($def->hasTag('foo')); - $this->assertEquals(array(array()), $def->getTag('foo'), '->getTag() returns attributes for a tag name'); - $def->addTag('foo', array('foo' => 'bar')); - $this->assertEquals(array(array(), array('foo' => 'bar')), $def->getTag('foo'), '->addTag() can adds the same tag several times'); - $def->addTag('bar', array('bar' => 'bar')); - $this->assertEquals($def->getTags(), array( - 'foo' => array(array(), array('foo' => 'bar')), - 'bar' => array(array('bar' => 'bar')), - ), '->getTags() returns all tags'); + $this->assertEquals([[]], $def->getTag('foo'), '->getTag() returns attributes for a tag name'); + $def->addTag('foo', ['foo' => 'bar']); + $this->assertEquals([[], ['foo' => 'bar']], $def->getTag('foo'), '->addTag() can adds the same tag several times'); + $def->addTag('bar', ['bar' => 'bar']); + $this->assertEquals($def->getTags(), [ + 'foo' => [[], ['foo' => 'bar']], + 'bar' => [['bar' => 'bar']], + ], '->getTags() returns all tags'); } public function testSetArgument() @@ -241,17 +241,17 @@ public function testSetArgument() $def = new Definition('stdClass'); $def->addArgument('foo'); - $this->assertSame(array('foo'), $def->getArguments()); + $this->assertSame(['foo'], $def->getArguments()); $this->assertSame($def, $def->replaceArgument(0, 'moo')); - $this->assertSame(array('moo'), $def->getArguments()); + $this->assertSame(['moo'], $def->getArguments()); $def->addArgument('moo'); $def ->replaceArgument(0, 'foo') ->replaceArgument(1, 'bar') ; - $this->assertSame(array('foo', 'bar'), $def->getArguments()); + $this->assertSame(['foo', 'bar'], $def->getArguments()); } /** @@ -291,18 +291,18 @@ public function testSetGetProperties() { $def = new Definition('stdClass'); - $this->assertEquals(array(), $def->getProperties()); - $this->assertSame($def, $def->setProperties(array('foo' => 'bar'))); - $this->assertEquals(array('foo' => 'bar'), $def->getProperties()); + $this->assertEquals([], $def->getProperties()); + $this->assertSame($def, $def->setProperties(['foo' => 'bar'])); + $this->assertEquals(['foo' => 'bar'], $def->getProperties()); } public function testSetProperty() { $def = new Definition('stdClass'); - $this->assertEquals(array(), $def->getProperties()); + $this->assertEquals([], $def->getProperties()); $this->assertSame($def, $def->setProperty('foo', 'bar')); - $this->assertEquals(array('foo' => 'bar'), $def->getProperties()); + $this->assertEquals(['foo' => 'bar'], $def->getProperties()); } public function testAutowired() @@ -321,12 +321,12 @@ public function testChangesNoChanges() { $def = new Definition(); - $this->assertSame(array(), $def->getChanges()); + $this->assertSame([], $def->getChanges()); } public function testGetChangesWithChanges() { - $def = new Definition('stdClass', array('fooarg')); + $def = new Definition('stdClass', ['fooarg']); $def->setAbstract(true); $def->setAutowired(true); @@ -340,13 +340,13 @@ public function testGetChangesWithChanges() $def->setShared(true); $def->setSynthetic(true); // changes aren't tracked for these, class or arguments - $def->setInstanceofConditionals(array()); + $def->setInstanceofConditionals([]); $def->addTag('foo_tag'); $def->addMethodCall('methodCall'); $def->setProperty('fooprop', true); $def->setAutoconfigured(true); - $this->assertSame(array( + $this->assertSame([ 'class' => true, 'autowired' => true, 'configurator' => true, @@ -358,10 +358,10 @@ public function testGetChangesWithChanges() 'public' => true, 'shared' => true, 'autoconfigured' => true, - ), $def->getChanges()); + ], $def->getChanges()); - $def->setChanges(array()); - $this->assertSame(array(), $def->getChanges()); + $def->setChanges([]); + $this->assertSame([], $def->getChanges()); } public function testShouldAutoconfigure() @@ -378,6 +378,6 @@ public function testAddError() $this->assertEmpty($def->getErrors()); $def->addError('First error'); $def->addError('Second error'); - $this->assertSame(array('First error', 'Second error'), $def->getErrors()); + $this->assertSame(['First error', 'Second error'], $def->getErrors()); } } diff --git a/Tests/Dumper/GraphvizDumperTest.php b/Tests/Dumper/GraphvizDumperTest.php index ffdd0730c..ea11c7c53 100644 --- a/Tests/Dumper/GraphvizDumperTest.php +++ b/Tests/Dumper/GraphvizDumperTest.php @@ -13,7 +13,9 @@ use PHPUnit\Framework\TestCase; use Symfony\Component\DependencyInjection\ContainerBuilder; +use Symfony\Component\DependencyInjection\Definition; use Symfony\Component\DependencyInjection\Dumper\GraphvizDumper; +use Symfony\Component\DependencyInjection\Reference; class GraphvizDumperTest extends TestCase { @@ -32,36 +34,36 @@ public function testDump() $container = include self::$fixturesPath.'/containers/container9.php'; $dumper = new GraphvizDumper($container); - $this->assertEquals(str_replace('%path%', __DIR__, file_get_contents(self::$fixturesPath.'/graphviz/services9.dot')), $dumper->dump(), '->dump() dumps services'); + $this->assertStringEqualsFile(self::$fixturesPath.'/graphviz/services9.dot', $dumper->dump(), '->dump() dumps services'); $container = include self::$fixturesPath.'/containers/container10.php'; $dumper = new GraphvizDumper($container); - $this->assertEquals(str_replace('%path%', __DIR__, file_get_contents(self::$fixturesPath.'/graphviz/services10.dot')), $dumper->dump(), '->dump() dumps services'); + $this->assertStringEqualsFile(self::$fixturesPath.'/graphviz/services10.dot', $dumper->dump(), '->dump() dumps services'); $container = include self::$fixturesPath.'/containers/container10.php'; $dumper = new GraphvizDumper($container); - $this->assertEquals($dumper->dump(array( - 'graph' => array('ratio' => 'normal'), - 'node' => array('fontsize' => 13, 'fontname' => 'Verdana', 'shape' => 'square'), - 'edge' => array('fontsize' => 12, 'fontname' => 'Verdana', 'color' => 'white', 'arrowhead' => 'closed', 'arrowsize' => 1), - 'node.instance' => array('fillcolor' => 'green', 'style' => 'empty'), - 'node.definition' => array('fillcolor' => 'grey'), - 'node.missing' => array('fillcolor' => 'red', 'style' => 'empty'), - )), str_replace('%path%', __DIR__, file_get_contents(self::$fixturesPath.'/graphviz/services10-1.dot')), '->dump() dumps services'); + $this->assertEquals($dumper->dump([ + 'graph' => ['ratio' => 'normal'], + 'node' => ['fontsize' => 13, 'fontname' => 'Verdana', 'shape' => 'square'], + 'edge' => ['fontsize' => 12, 'fontname' => 'Verdana', 'color' => 'white', 'arrowhead' => 'closed', 'arrowsize' => 1], + 'node.instance' => ['fillcolor' => 'green', 'style' => 'empty'], + 'node.definition' => ['fillcolor' => 'grey'], + 'node.missing' => ['fillcolor' => 'red', 'style' => 'empty'], + ]), file_get_contents(self::$fixturesPath.'/graphviz/services10-1.dot'), '->dump() dumps services'); } public function testDumpWithFrozenContainer() { $container = include self::$fixturesPath.'/containers/container13.php'; $dumper = new GraphvizDumper($container); - $this->assertEquals(str_replace('%path%', __DIR__, file_get_contents(self::$fixturesPath.'/graphviz/services13.dot')), $dumper->dump(), '->dump() dumps services'); + $this->assertStringEqualsFile(self::$fixturesPath.'/graphviz/services13.dot', $dumper->dump(), '->dump() dumps services'); } public function testDumpWithFrozenCustomClassContainer() { $container = include self::$fixturesPath.'/containers/container14.php'; $dumper = new GraphvizDumper($container); - $this->assertEquals(str_replace('%path%', __DIR__, file_get_contents(self::$fixturesPath.'/graphviz/services14.dot')), $dumper->dump(), '->dump() dumps services'); + $this->assertStringEqualsFile(self::$fixturesPath.'/graphviz/services14.dot', $dumper->dump(), '->dump() dumps services'); } public function testDumpWithUnresolvedParameter() @@ -69,6 +71,18 @@ public function testDumpWithUnresolvedParameter() $container = include self::$fixturesPath.'/containers/container17.php'; $dumper = new GraphvizDumper($container); - $this->assertEquals(str_replace('%path%', __DIR__, file_get_contents(self::$fixturesPath.'/graphviz/services17.dot')), $dumper->dump(), '->dump() dumps services'); + $this->assertStringEqualsFile(self::$fixturesPath.'/graphviz/services17.dot', $dumper->dump(), '->dump() dumps services'); + } + + public function testDumpWithInlineDefinition() + { + $container = new ContainerBuilder(); + $container->register('foo', 'stdClass')->addArgument( + (new Definition('stdClass'))->addArgument(new Reference('bar')) + ); + $container->register('bar', 'stdClass'); + $dumper = new GraphvizDumper($container); + + $this->assertStringEqualsFile(self::$fixturesPath.'/graphviz/services_inline.dot', $dumper->dump(), '->dump() dumps nested references'); } } diff --git a/Tests/Dumper/PhpDumperTest.php b/Tests/Dumper/PhpDumperTest.php index 52e7ff18f..cfc038c8e 100644 --- a/Tests/Dumper/PhpDumperTest.php +++ b/Tests/Dumper/PhpDumperTest.php @@ -19,18 +19,19 @@ use Symfony\Component\DependencyInjection\Argument\ServiceClosureArgument; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\ContainerInterface as SymfonyContainerInterface; +use Symfony\Component\DependencyInjection\Definition; use Symfony\Component\DependencyInjection\Dumper\PhpDumper; use Symfony\Component\DependencyInjection\EnvVarProcessorInterface; +use Symfony\Component\DependencyInjection\Exception\ServiceCircularReferenceException; +use Symfony\Component\DependencyInjection\Loader\YamlFileLoader; use Symfony\Component\DependencyInjection\Parameter; use Symfony\Component\DependencyInjection\ParameterBag\ParameterBag; use Symfony\Component\DependencyInjection\Reference; -use Symfony\Component\DependencyInjection\Tests\Fixtures\StubbedTranslator; -use Symfony\Component\DependencyInjection\TypedReference; -use Symfony\Component\DependencyInjection\Definition; -use Symfony\Component\DependencyInjection\Loader\YamlFileLoader; use Symfony\Component\DependencyInjection\ServiceLocator; use Symfony\Component\DependencyInjection\Tests\Fixtures\CustomDefinition; +use Symfony\Component\DependencyInjection\Tests\Fixtures\StubbedTranslator; use Symfony\Component\DependencyInjection\Tests\Fixtures\TestServiceSubscriber; +use Symfony\Component\DependencyInjection\TypedReference; use Symfony\Component\DependencyInjection\Variable; use Symfony\Component\ExpressionLanguage\Expression; @@ -52,14 +53,14 @@ public function testDump() $dumper = new PhpDumper($container); $this->assertStringEqualsFile(self::$fixturesPath.'/php/services1.php', $dumper->dump(), '->dump() dumps an empty container as an empty PHP class'); - $this->assertStringEqualsFile(self::$fixturesPath.'/php/services1-1.php', $dumper->dump(array('class' => 'Container', 'base_class' => 'AbstractContainer', 'namespace' => 'Symfony\Component\DependencyInjection\Dump')), '->dump() takes a class and a base_class options'); + $this->assertStringEqualsFile(self::$fixturesPath.'/php/services1-1.php', $dumper->dump(['class' => 'Container', 'base_class' => 'AbstractContainer', 'namespace' => 'Symfony\Component\DependencyInjection\Dump']), '->dump() takes a class and a base_class options'); } public function testDumpOptimizationString() { $definition = new Definition(); $definition->setClass('stdClass'); - $definition->addArgument(array( + $definition->addArgument([ 'only dot' => '.', 'concatenation as value' => '.\'\'.', 'concatenation from the start value' => '\'\'.', @@ -71,7 +72,7 @@ public function testDumpOptimizationString() 'optimize concatenation from the start' => '%empty_value%start', 'optimize concatenation at the end' => 'end%empty_value%', 'new line' => "string with \nnew line", - )); + ]); $definition->setPublic(true); $container = new ContainerBuilder(); @@ -90,19 +91,19 @@ public function testDumpRelativeDir() $definition = new Definition(); $definition->setClass('stdClass'); $definition->addArgument('%foo%'); - $definition->addArgument(array('%foo%' => '%buz%/')); + $definition->addArgument(['%foo%' => '%buz%/']); $definition->setPublic(true); $container = new ContainerBuilder(); $container->setDefinition('test', $definition); - $container->setParameter('foo', 'wiz'.dirname(__DIR__)); + $container->setParameter('foo', 'wiz'.\dirname(__DIR__)); $container->setParameter('bar', __DIR__); $container->setParameter('baz', '%bar%/PhpDumperTest.php'); - $container->setParameter('buz', dirname(dirname(__DIR__))); + $container->setParameter('buz', \dirname(\dirname(__DIR__))); $container->compile(); $dumper = new PhpDumper($container); - $this->assertStringEqualsFile(self::$fixturesPath.'/php/services12.php', $dumper->dump(array('file' => __FILE__)), '->dump() dumps __DIR__ relative strings'); + $this->assertStringEqualsFile(self::$fixturesPath.'/php/services12.php', $dumper->dump(['file' => __FILE__]), '->dump() dumps __DIR__ relative strings'); } public function testDumpCustomContainerClassWithoutConstructor() @@ -112,7 +113,7 @@ public function testDumpCustomContainerClassWithoutConstructor() $dumper = new PhpDumper($container); - $this->assertStringEqualsFile(self::$fixturesPath.'/php/custom_container_class_without_constructor.php', $dumper->dump(array('base_class' => 'NoConstructorContainer', 'namespace' => 'Symfony\Component\DependencyInjection\Tests\Fixtures\Container'))); + $this->assertStringEqualsFile(self::$fixturesPath.'/php/custom_container_class_without_constructor.php', $dumper->dump(['base_class' => 'NoConstructorContainer', 'namespace' => 'Symfony\Component\DependencyInjection\Tests\Fixtures\Container'])); } public function testDumpCustomContainerClassConstructorWithoutArguments() @@ -122,7 +123,7 @@ public function testDumpCustomContainerClassConstructorWithoutArguments() $dumper = new PhpDumper($container); - $this->assertStringEqualsFile(self::$fixturesPath.'/php/custom_container_class_constructor_without_arguments.php', $dumper->dump(array('base_class' => 'ConstructorWithoutArgumentsContainer', 'namespace' => 'Symfony\Component\DependencyInjection\Tests\Fixtures\Container'))); + $this->assertStringEqualsFile(self::$fixturesPath.'/php/custom_container_class_constructor_without_arguments.php', $dumper->dump(['base_class' => 'ConstructorWithoutArgumentsContainer', 'namespace' => 'Symfony\Component\DependencyInjection\Tests\Fixtures\Container'])); } public function testDumpCustomContainerClassWithOptionalArgumentLessConstructor() @@ -132,7 +133,7 @@ public function testDumpCustomContainerClassWithOptionalArgumentLessConstructor( $dumper = new PhpDumper($container); - $this->assertStringEqualsFile(self::$fixturesPath.'/php/custom_container_class_with_optional_constructor_arguments.php', $dumper->dump(array('base_class' => 'ConstructorWithOptionalArgumentsContainer', 'namespace' => 'Symfony\Component\DependencyInjection\Tests\Fixtures\Container'))); + $this->assertStringEqualsFile(self::$fixturesPath.'/php/custom_container_class_with_optional_constructor_arguments.php', $dumper->dump(['base_class' => 'ConstructorWithOptionalArgumentsContainer', 'namespace' => 'Symfony\Component\DependencyInjection\Tests\Fixtures\Container'])); } public function testDumpCustomContainerClassWithMandatoryArgumentLessConstructor() @@ -142,7 +143,7 @@ public function testDumpCustomContainerClassWithMandatoryArgumentLessConstructor $dumper = new PhpDumper($container); - $this->assertStringEqualsFile(self::$fixturesPath.'/php/custom_container_class_with_mandatory_constructor_arguments.php', $dumper->dump(array('base_class' => 'ConstructorWithMandatoryArgumentsContainer', 'namespace' => 'Symfony\Component\DependencyInjection\Tests\Fixtures\Container'))); + $this->assertStringEqualsFile(self::$fixturesPath.'/php/custom_container_class_with_mandatory_constructor_arguments.php', $dumper->dump(['base_class' => 'ConstructorWithMandatoryArgumentsContainer', 'namespace' => 'Symfony\Component\DependencyInjection\Tests\Fixtures\Container'])); } /** @@ -159,12 +160,12 @@ public function testExportParameters($parameters) public function provideInvalidParameters() { - return array( - array(array('foo' => new Definition('stdClass'))), - array(array('foo' => new Expression('service("foo").foo() ~ (container.hasParameter("foo") ? parameter("foo") : "default")'))), - array(array('foo' => new Reference('foo'))), - array(array('foo' => new Variable('foo'))), - ); + return [ + [['foo' => new Definition('stdClass')]], + [['foo' => new Expression('service("foo").foo() ~ (container.hasParameter("foo") ? parameter("foo") : "default")')]], + [['foo' => new Reference('foo')]], + [['foo' => new Variable('foo')]], + ]; } public function testAddParameters() @@ -190,7 +191,7 @@ public function testAddService() $container = include self::$fixturesPath.'/containers/container9.php'; $container->compile(); $dumper = new PhpDumper($container); - $this->assertStringEqualsFile(self::$fixturesPath.'/php/services9_compiled.php', str_replace(str_replace('\\', '\\\\', self::$fixturesPath.DIRECTORY_SEPARATOR.'includes'.DIRECTORY_SEPARATOR), '%path%', $dumper->dump()), '->dump() dumps services'); + $this->assertStringEqualsFile(self::$fixturesPath.'/php/services9_compiled.php', str_replace(str_replace('\\', '\\\\', self::$fixturesPath.\DIRECTORY_SEPARATOR.'includes'.\DIRECTORY_SEPARATOR), '%path%', $dumper->dump()), '->dump() dumps services'); $container = new ContainerBuilder(); $container->register('foo', 'FooClass')->addArgument(new \stdClass())->setPublic(true); @@ -215,8 +216,8 @@ public function testDumpAsFiles() ->setPublic(true); $container->compile(); $dumper = new PhpDumper($container); - $dump = print_r($dumper->dump(array('as_files' => true, 'file' => __DIR__, 'hot_path_tag' => 'hot')), true); - if ('\\' === DIRECTORY_SEPARATOR) { + $dump = print_r($dumper->dump(['as_files' => true, 'file' => __DIR__, 'hot_path_tag' => 'hot']), true); + if ('\\' === \DIRECTORY_SEPARATOR) { $dump = str_replace('\\\\Fixtures\\\\includes\\\\foo.php', '/Fixtures/includes/foo.php', $dump); } $this->assertStringMatchesFormatFile(self::$fixturesPath.'/php/services9_as_files.txt', $dump); @@ -235,12 +236,18 @@ public function testAddServiceIdWithUnsupportedCharacters() { $class = 'Symfony_DI_PhpDumper_Test_Unsupported_Characters'; $container = new ContainerBuilder(); + $container->setParameter("'", 'oh-no'); + $container->register("foo*/oh-no", 'FooClass')->setPublic(true); $container->register('bar$', 'FooClass')->setPublic(true); $container->register('bar$!', 'FooClass')->setPublic(true); $container->compile(); $dumper = new PhpDumper($container); - eval('?>'.$dumper->dump(array('class' => $class))); + $this->assertStringEqualsFile(self::$fixturesPath.'/php/services_unsupported_characters.php', $dumper->dump(['class' => $class])); + + require_once self::$fixturesPath.'/php/services_unsupported_characters.php'; + + $this->assertTrue(method_exists($class, 'getFooOhNoService')); $this->assertTrue(method_exists($class, 'getBarService')); $this->assertTrue(method_exists($class, 'getBar2Service')); } @@ -253,7 +260,7 @@ public function testConflictingServiceIds() $container->register('foobar', 'FooClass')->setPublic(true); $container->compile(); $dumper = new PhpDumper($container); - eval('?>'.$dumper->dump(array('class' => $class))); + eval('?>'.$dumper->dump(['class' => $class])); $this->assertTrue(method_exists($class, 'getFooBarService')); $this->assertTrue(method_exists($class, 'getFoobar2Service')); @@ -267,10 +274,10 @@ public function testConflictingMethodsWithParent() $container->register('foo_bar', 'FooClass')->setPublic(true); $container->compile(); $dumper = new PhpDumper($container); - eval('?>'.$dumper->dump(array( + eval('?>'.$dumper->dump([ 'class' => $class, 'base_class' => 'Symfony\Component\DependencyInjection\Tests\Fixtures\containers\CustomContainer', - ))); + ])); $this->assertTrue(method_exists($class, 'getBar2Service')); $this->assertTrue(method_exists($class, 'getFoobar2Service')); @@ -295,12 +302,12 @@ public function testInvalidFactories($factory) public function provideInvalidFactories() { - return array( - array(array('', 'method')), - array(array('class', '')), - array(array('...', 'method')), - array(array('class', '...')), - ); + return [ + [['', 'method']], + [['class', '']], + [['...', 'method']], + [['class', '...']], + ]; } public function testAliases() @@ -309,7 +316,7 @@ public function testAliases() $container->setParameter('foo_bar', 'foo_bar'); $container->compile(); $dumper = new PhpDumper($container); - eval('?>'.$dumper->dump(array('class' => 'Symfony_DI_PhpDumper_Test_Aliases'))); + eval('?>'.$dumper->dump(['class' => 'Symfony_DI_PhpDumper_Test_Aliases'])); $container = new \Symfony_DI_PhpDumper_Test_Aliases(); $foo = $container->get('foo'); @@ -323,7 +330,7 @@ public function testFrozenContainerWithoutAliases() $container->compile(); $dumper = new PhpDumper($container); - eval('?>'.$dumper->dump(array('class' => 'Symfony_DI_PhpDumper_Test_Frozen_No_Aliases'))); + eval('?>'.$dumper->dump(['class' => 'Symfony_DI_PhpDumper_Test_Frozen_No_Aliases'])); $container = new \Symfony_DI_PhpDumper_Test_Frozen_No_Aliases(); $this->assertFalse($container->has('foo')); @@ -373,12 +380,12 @@ public function testEnvParameter() $container->compile(); $dumper = new PhpDumper($container); - $this->assertStringEqualsFile(self::$fixturesPath.'/php/services26.php', $dumper->dump(array('class' => 'Symfony_DI_PhpDumper_Test_EnvParameters', 'file' => self::$fixturesPath.'/php/services26.php'))); + $this->assertStringEqualsFile(self::$fixturesPath.'/php/services26.php', $dumper->dump(['class' => 'Symfony_DI_PhpDumper_Test_EnvParameters', 'file' => self::$fixturesPath.'/php/services26.php'])); require self::$fixturesPath.'/php/services26.php'; $container = new \Symfony_DI_PhpDumper_Test_EnvParameters(); $this->assertSame($rand, $container->getParameter('baz')); - $this->assertSame(array(123, 'abc'), $container->getParameter('json')); + $this->assertSame([123, 'abc'], $container->getParameter('json')); $this->assertSame('sqlite:///foo/bar/var/data.db', $container->getParameter('db_dsn')); putenv('Baz'); } @@ -390,10 +397,10 @@ public function testResolvedBase64EnvParameters() $container->setParameter('hello', '%env(base64:foo)%'); $container->compile(true); - $expected = array( - 'env(foo)' => 'd29ybGQ=', - 'hello' => 'world', - ); + $expected = [ + 'env(foo)' => 'd29ybGQ=', + 'hello' => 'world', + ]; $this->assertSame($expected, $container->getParameterBag()->all()); } @@ -407,7 +414,7 @@ public function testDumpedBase64EnvParameters() $dumper = new PhpDumper($container); $dumper->dump(); - $this->assertStringEqualsFile(self::$fixturesPath.'/php/services_base64_env.php', $dumper->dump(array('class' => 'Symfony_DI_PhpDumper_Test_Base64Parameters'))); + $this->assertStringEqualsFile(self::$fixturesPath.'/php/services_base64_env.php', $dumper->dump(['class' => 'Symfony_DI_PhpDumper_Test_Base64Parameters'])); require self::$fixturesPath.'/php/services_base64_env.php'; $container = new \Symfony_DI_PhpDumper_Test_Base64Parameters(); @@ -424,11 +431,11 @@ public function testDumpedCsvEnvParameters() $dumper = new PhpDumper($container); $dumper->dump(); - $this->assertStringEqualsFile(self::$fixturesPath.'/php/services_csv_env.php', $dumper->dump(array('class' => 'Symfony_DI_PhpDumper_Test_CsvParameters'))); + $this->assertStringEqualsFile(self::$fixturesPath.'/php/services_csv_env.php', $dumper->dump(['class' => 'Symfony_DI_PhpDumper_Test_CsvParameters'])); require self::$fixturesPath.'/php/services_csv_env.php'; $container = new \Symfony_DI_PhpDumper_Test_CsvParameters(); - $this->assertSame(array('foo', 'bar'), $container->getParameter('hello')); + $this->assertSame(['foo', 'bar'], $container->getParameter('hello')); } public function testDumpedJsonEnvParameters() @@ -443,12 +450,12 @@ public function testDumpedJsonEnvParameters() $dumper = new PhpDumper($container); $dumper->dump(); - $this->assertStringEqualsFile(self::$fixturesPath.'/php/services_json_env.php', $dumper->dump(array('class' => 'Symfony_DI_PhpDumper_Test_JsonParameters'))); + $this->assertStringEqualsFile(self::$fixturesPath.'/php/services_json_env.php', $dumper->dump(['class' => 'Symfony_DI_PhpDumper_Test_JsonParameters'])); putenv('foobar="hello"'); require self::$fixturesPath.'/php/services_json_env.php'; $container = new \Symfony_DI_PhpDumper_Test_JsonParameters(); - $this->assertSame(array('foo', 'bar'), $container->getParameter('hello')); + $this->assertSame(['foo', 'bar'], $container->getParameter('hello')); $this->assertNull($container->getParameter('hello-bar')); } @@ -463,7 +470,7 @@ public function testCustomEnvParameters() $dumper = new PhpDumper($container); $dumper->dump(); - $this->assertStringEqualsFile(self::$fixturesPath.'/php/services_rot13_env.php', $dumper->dump(array('class' => 'Symfony_DI_PhpDumper_Test_Rot13Parameters'))); + $this->assertStringEqualsFile(self::$fixturesPath.'/php/services_rot13_env.php', $dumper->dump(['class' => 'Symfony_DI_PhpDumper_Test_Rot13Parameters'])); require self::$fixturesPath.'/php/services_rot13_env.php'; $container = new \Symfony_DI_PhpDumper_Test_Rot13Parameters(); @@ -505,7 +512,7 @@ public function testCircularDynamicEnv() $container->compile(); $dumper = new PhpDumper($container); - $dump = $dumper->dump(array('class' => $class = __FUNCTION__)); + $dump = $dumper->dump(['class' => $class = __FUNCTION__]); eval('?>'.$dump); $container = new $class(); @@ -521,7 +528,7 @@ public function testCircularDynamicEnv() public function testInlinedDefinitionReferencingServiceContainer() { $container = new ContainerBuilder(); - $container->register('foo', 'stdClass')->addMethodCall('add', array(new Reference('service_container')))->setPublic(false); + $container->register('foo', 'stdClass')->addMethodCall('add', [new Reference('service_container')])->setPublic(false); $container->register('bar', 'stdClass')->addArgument(new Reference('foo'))->setPublic(true); $container->compile(); @@ -556,7 +563,7 @@ public function testInitializePropertiesBeforeMethodCalls() $container->compile(); $dumper = new PhpDumper($container); - eval('?>'.$dumper->dump(array('class' => 'Symfony_DI_PhpDumper_Test_Properties_Before_Method_Calls'))); + eval('?>'.$dumper->dump(['class' => 'Symfony_DI_PhpDumper_Test_Properties_Before_Method_Calls'])); $container = new \Symfony_DI_PhpDumper_Test_Properties_Before_Method_Calls(); $this->assertTrue($container->get('bar')->callPassed(), '->dump() initializes properties before method calls'); @@ -570,50 +577,22 @@ public function testCircularReferenceAllowanceForLazyServices() $container->compile(); $dumper = new PhpDumper($container); + $dumper->setProxyDumper(new \DummyProxyDumper()); $dumper->dump(); $this->addToAssertionCount(1); - } - - public function testCircularReferenceAllowanceForInlinedDefinitionsForLazyServices() - { - /* - * test graph: - * [connection] -> [event_manager] --> [entity_manager](lazy) - * | - * --(call)- addEventListener ("@lazy_service") - * - * [lazy_service](lazy) -> [entity_manager](lazy) - * - */ - - $container = new ContainerBuilder(); - - $eventManagerDefinition = new Definition('stdClass'); - - $connectionDefinition = $container->register('connection', 'stdClass')->setPublic(true); - $connectionDefinition->addArgument($eventManagerDefinition); - - $container->register('entity_manager', 'stdClass') - ->setPublic(true) - ->setLazy(true) - ->addArgument(new Reference('connection')); - - $lazyServiceDefinition = $container->register('lazy_service', 'stdClass'); - $lazyServiceDefinition->setPublic(true); - $lazyServiceDefinition->setLazy(true); - $lazyServiceDefinition->addArgument(new Reference('entity_manager')); - - $eventManagerDefinition->addMethodCall('addEventListener', array(new Reference('lazy_service'))); - - $container->compile(); $dumper = new PhpDumper($container); - $dumper->setProxyDumper(new \DummyProxyDumper()); - $dumper->dump(); + $message = 'Circular reference detected for service "foo", path: "foo -> bar -> foo". Try running "composer require symfony/proxy-manager-bridge".'; + if (method_exists($this, 'expectException')) { + $this->expectException(ServiceCircularReferenceException::class); + $this->expectExceptionMessage($message); + } else { + $this->setExpectedException(ServiceCircularReferenceException::class, $message); + } - $this->addToAssertionCount(1); + $dumper->dump(); } public function testDedupLazyProxy() @@ -638,15 +617,15 @@ public function testLazyArgumentProvideGenerator() $container ->register('lazy_context', 'LazyContext') ->setPublic(true) - ->setArguments(array( - new IteratorArgument(array('k1' => new Reference('lazy_referenced'), 'k2' => new Reference('service_container'))), - new IteratorArgument(array()), - )) + ->setArguments([ + new IteratorArgument(['k1' => new Reference('lazy_referenced'), 'k2' => new Reference('service_container')]), + new IteratorArgument([]), + ]) ; $container->compile(); $dumper = new PhpDumper($container); - eval('?>'.$dumper->dump(array('class' => 'Symfony_DI_PhpDumper_Test_Lazy_Argument_Provide_Generator'))); + eval('?>'.$dumper->dump(['class' => 'Symfony_DI_PhpDumper_Test_Lazy_Argument_Provide_Generator'])); $container = new \Symfony_DI_PhpDumper_Test_Lazy_Argument_Provide_Generator(); $lazyContext = $container->get('lazy_context'); @@ -685,8 +664,8 @@ public function testNormalizedId() public function testDumpContainerBuilderWithFrozenConstructorIncludingPrivateServices() { $container = new ContainerBuilder(); - $container->register('foo_service', 'stdClass')->setArguments(array(new Reference('baz_service')))->setPublic(true); - $container->register('bar_service', 'stdClass')->setArguments(array(new Reference('baz_service')))->setPublic(true); + $container->register('foo_service', 'stdClass')->setArguments([new Reference('baz_service')])->setPublic(true); + $container->register('bar_service', 'stdClass')->setArguments([new Reference('baz_service')])->setPublic(true); $container->register('baz_service', 'stdClass')->setPublic(false); $container->compile(); @@ -700,20 +679,20 @@ public function testServiceLocator() $container = new ContainerBuilder(); $container->register('foo_service', ServiceLocator::class) ->setPublic(true) - ->addArgument(array( + ->addArgument([ 'bar' => new ServiceClosureArgument(new Reference('bar_service')), 'baz' => new ServiceClosureArgument(new TypedReference('baz_service', 'stdClass')), 'nil' => $nil = new ServiceClosureArgument(new Reference('nil')), - )) + ]) ; // no method calls $container->register('translator.loader_1', 'stdClass')->setPublic(true); $container->register('translator.loader_1_locator', ServiceLocator::class) ->setPublic(false) - ->addArgument(array( + ->addArgument([ 'translator.loader_1' => new ServiceClosureArgument(new Reference('translator.loader_1')), - )); + ]); $container->register('translator_1', StubbedTranslator::class) ->setPublic(true) ->addArgument(new Reference('translator.loader_1_locator')); @@ -722,29 +701,29 @@ public function testServiceLocator() $container->register('translator.loader_2', 'stdClass')->setPublic(true); $container->register('translator.loader_2_locator', ServiceLocator::class) ->setPublic(false) - ->addArgument(array( + ->addArgument([ 'translator.loader_2' => new ServiceClosureArgument(new Reference('translator.loader_2')), - )); + ]); $container->register('translator_2', StubbedTranslator::class) ->setPublic(true) ->addArgument(new Reference('translator.loader_2_locator')) - ->addMethodCall('addResource', array('db', new Reference('translator.loader_2'), 'nl')); + ->addMethodCall('addResource', ['db', new Reference('translator.loader_2'), 'nl']); // two method calls $container->register('translator.loader_3', 'stdClass')->setPublic(true); $container->register('translator.loader_3_locator', ServiceLocator::class) ->setPublic(false) - ->addArgument(array( + ->addArgument([ 'translator.loader_3' => new ServiceClosureArgument(new Reference('translator.loader_3')), - )); + ]); $container->register('translator_3', StubbedTranslator::class) ->setPublic(true) ->addArgument(new Reference('translator.loader_3_locator')) - ->addMethodCall('addResource', array('db', new Reference('translator.loader_3'), 'nl')) - ->addMethodCall('addResource', array('db', new Reference('translator.loader_3'), 'en')); + ->addMethodCall('addResource', ['db', new Reference('translator.loader_3'), 'nl']) + ->addMethodCall('addResource', ['db', new Reference('translator.loader_3'), 'en']); - $nil->setValues(array(null)); - $container->register('bar_service', 'stdClass')->setArguments(array(new Reference('baz_service')))->setPublic(true); + $nil->setValues([null]); + $container->register('bar_service', 'stdClass')->setArguments([new Reference('baz_service')])->setPublic(true); $container->register('baz_service', 'stdClass')->setPublic(false); $container->compile(); @@ -760,10 +739,10 @@ public function testServiceSubscriber() ->setPublic(true) ->setAutowired(true) ->addArgument(new Reference(ContainerInterface::class)) - ->addTag('container.service_subscriber', array( + ->addTag('container.service_subscriber', [ 'key' => 'bar', 'id' => TestServiceSubscriber::class, - )) + ]) ; $container->register(TestServiceSubscriber::class, TestServiceSubscriber::class)->setPublic(true); @@ -785,11 +764,11 @@ public function testPrivateWithIgnoreOnInvalidReference() ->setPublic(false); $container->register('bar', 'BarClass') ->setPublic(true) - ->addMethodCall('setBaz', array(new Reference('not_invalid', SymfonyContainerInterface::IGNORE_ON_INVALID_REFERENCE))); + ->addMethodCall('setBaz', [new Reference('not_invalid', SymfonyContainerInterface::IGNORE_ON_INVALID_REFERENCE)]); $container->compile(); $dumper = new PhpDumper($container); - eval('?>'.$dumper->dump(array('class' => 'Symfony_DI_PhpDumper_Test_Private_With_Ignore_On_Invalid_Reference'))); + eval('?>'.$dumper->dump(['class' => 'Symfony_DI_PhpDumper_Test_Private_With_Ignore_On_Invalid_Reference'])); $container = new \Symfony_DI_PhpDumper_Test_Private_With_Ignore_On_Invalid_Reference(); $this->assertInstanceOf('BazClass', $container->get('bar')->getBaz()); @@ -798,16 +777,16 @@ public function testPrivateWithIgnoreOnInvalidReference() public function testArrayParameters() { $container = new ContainerBuilder(); - $container->setParameter('array_1', array(123)); - $container->setParameter('array_2', array(__DIR__)); + $container->setParameter('array_1', [123]); + $container->setParameter('array_2', [__DIR__]); $container->register('bar', 'BarClass') ->setPublic(true) - ->addMethodCall('setBaz', array('%array_1%', '%array_2%', '%%array_1%%', array(123))); + ->addMethodCall('setBaz', ['%array_1%', '%array_2%', '%%array_1%%', [123]]); $container->compile(); $dumper = new PhpDumper($container); - $this->assertStringEqualsFile(self::$fixturesPath.'/php/services_array_params.php', str_replace('\\\\Dumper', '/Dumper', $dumper->dump(array('file' => self::$fixturesPath.'/php/services_array_params.php')))); + $this->assertStringEqualsFile(self::$fixturesPath.'/php/services_array_params.php', str_replace('\\\\Dumper', '/Dumper', $dumper->dump(['file' => self::$fixturesPath.'/php/services_array_params.php']))); } public function testExpressionReferencingPrivateService() @@ -819,7 +798,7 @@ public function testExpressionReferencingPrivateService() ->setPublic(false); $container->register('public_foo', 'stdClass') ->setPublic(true) - ->addArgument(new Expression('service("private_foo")')); + ->addArgument(new Expression('service("private_foo").bar')); $container->compile(); $dumper = new PhpDumper($container); @@ -833,7 +812,7 @@ public function testUninitializedReference() $container->compile(); $dumper = new PhpDumper($container); - $this->assertStringEqualsFile(self::$fixturesPath.'/php/services_uninitialized_ref.php', $dumper->dump(array('class' => 'Symfony_DI_PhpDumper_Test_Uninitialized_Reference'))); + $this->assertStringEqualsFile(self::$fixturesPath.'/php/services_uninitialized_ref.php', $dumper->dump(['class' => 'Symfony_DI_PhpDumper_Test_Uninitialized_Reference'])); require self::$fixturesPath.'/php/services_uninitialized_ref.php'; @@ -847,7 +826,7 @@ public function testUninitializedReference() $this->assertNull($bar->closures[0]()); $this->assertNull($bar->closures[1]()); $this->assertNull($bar->closures[2]()); - $this->assertSame(array(), iterator_to_array($bar->iter)); + $this->assertSame([], iterator_to_array($bar->iter)); $container = new \Symfony_DI_PhpDumper_Test_Uninitialized_Reference(); @@ -862,7 +841,7 @@ public function testUninitializedReference() $this->assertEquals(new \stdClass(), $bar->closures[0]()); $this->assertNull($bar->closures[1]()); $this->assertEquals(new \stdClass(), $bar->closures[2]()); - $this->assertEquals(array('foo1' => new \stdClass(), 'foo3' => new \stdClass()), iterator_to_array($bar->iter)); + $this->assertEquals(['foo1' => new \stdClass(), 'foo3' => new \stdClass()], iterator_to_array($bar->iter)); } /** @@ -875,7 +854,7 @@ public function testAlmostCircular($visibility) $dumper = new PhpDumper($container); $container = 'Symfony_DI_PhpDumper_Test_Almost_Circular_'.ucfirst($visibility); - $this->assertStringEqualsFile(self::$fixturesPath.'/php/services_almost_circular_'.$visibility.'.php', $dumper->dump(array('class' => $container))); + $this->assertStringEqualsFile(self::$fixturesPath.'/php/services_almost_circular_'.$visibility.'.php', $dumper->dump(['class' => $container])); require self::$fixturesPath.'/php/services_almost_circular_'.$visibility.'.php'; @@ -887,16 +866,71 @@ public function testAlmostCircular($visibility) $foo2 = $container->get('foo2'); $this->assertSame($foo2, $foo2->bar->foobar->foo); - $this->assertSame(array(), (array) $container->get('foobar4')); + $this->assertSame([], (array) $container->get('foobar4')); $foo5 = $container->get('foo5'); $this->assertSame($foo5, $foo5->bar->foo); + + $manager = $container->get('manager'); + $this->assertEquals(new \stdClass(), $manager); + + $manager = $container->get('manager2'); + $this->assertEquals(new \stdClass(), $manager); + + $foo6 = $container->get('foo6'); + $this->assertEquals((object) ['bar6' => (object) []], $foo6); + + $this->assertInstanceOf(\stdClass::class, $container->get('root')); } public function provideAlmostCircular() { - yield array('public'); - yield array('private'); + yield ['public']; + yield ['private']; + } + + public function testDeepServiceGraph() + { + $container = new ContainerBuilder(); + + $loader = new YamlFileLoader($container, new FileLocator(self::$fixturesPath.'/yaml')); + $loader->load('services_deep_graph.yml'); + + $container->compile(); + + $dumper = new PhpDumper($container); + $dumper->dump(); + + $this->assertStringEqualsFile(self::$fixturesPath.'/php/services_deep_graph.php', $dumper->dump(['class' => 'Symfony_DI_PhpDumper_Test_Deep_Graph'])); + + require self::$fixturesPath.'/php/services_deep_graph.php'; + + $container = new \Symfony_DI_PhpDumper_Test_Deep_Graph(); + + $this->assertInstanceOf(FooForDeepGraph::class, $container->get('foo')); + $this->assertEquals((object) ['p2' => (object) ['p3' => (object) []]], $container->get('foo')->bClone); + } + + public function testInlineSelfRef() + { + $container = new ContainerBuilder(); + + $bar = (new Definition('App\Bar')) + ->setProperty('foo', new Reference('App\Foo')); + + $baz = (new Definition('App\Baz')) + ->setProperty('bar', $bar) + ->addArgument($bar); + + $container->register('App\Foo') + ->setPublic(true) + ->addArgument($baz); + + $passConfig = $container->getCompiler()->getPassConfig(); + $container->compile(); + + $dumper = new PhpDumper($container); + $this->assertStringEqualsFile(self::$fixturesPath.'/php/services_inline_self_ref.php', $dumper->dump(['class' => 'Symfony_DI_PhpDumper_Test_Inline_Self_Ref'])); } public function testHotPathOptimizations() @@ -906,8 +940,8 @@ public function testHotPathOptimizations() $container->compile(); $dumper = new PhpDumper($container); - $dump = $dumper->dump(array('hot_path_tag' => 'container.hot_path', 'inline_class_loader_parameter' => 'inline_requires', 'file' => self::$fixturesPath.'/php/services_inline_requires.php')); - if ('\\' === DIRECTORY_SEPARATOR) { + $dump = $dumper->dump(['hot_path_tag' => 'container.hot_path', 'inline_class_loader_parameter' => 'inline_requires', 'file' => self::$fixturesPath.'/php/services_inline_requires.php']); + if ('\\' === \DIRECTORY_SEPARATOR) { $dump = str_replace("'\\\\includes\\\\HotPath\\\\", "'/includes/HotPath/", $dump); } @@ -921,7 +955,7 @@ public function testDumpHandlesLiteralClassWithRootNamespace() $container->compile(); $dumper = new PhpDumper($container); - eval('?>'.$dumper->dump(array('class' => 'Symfony_DI_PhpDumper_Test_Literal_Class_With_Root_Namespace'))); + eval('?>'.$dumper->dump(['class' => 'Symfony_DI_PhpDumper_Test_Literal_Class_With_Root_Namespace'])); $container = new \Symfony_DI_PhpDumper_Test_Literal_Class_With_Root_Namespace(); @@ -930,29 +964,64 @@ public function testDumpHandlesLiteralClassWithRootNamespace() public function testDumpHandlesObjectClassNames() { - $container = new ContainerBuilder(new ParameterBag(array( + $container = new ContainerBuilder(new ParameterBag([ 'class' => 'stdClass', - ))); + ])); $container->setDefinition('foo', new Definition(new Parameter('class'))); - $container->setDefinition('bar', new Definition('stdClass', array( + $container->setDefinition('bar', new Definition('stdClass', [ new Reference('foo'), - )))->setPublic(true); + ]))->setPublic(true); $container->setParameter('inline_requires', true); $container->compile(); $dumper = new PhpDumper($container); - eval('?>'.$dumper->dump(array( + eval('?>'.$dumper->dump([ 'class' => 'Symfony_DI_PhpDumper_Test_Object_Class_Name', 'inline_class_loader_parameter' => 'inline_requires', - ))); + ])); $container = new \Symfony_DI_PhpDumper_Test_Object_Class_Name(); $this->assertInstanceOf('stdClass', $container->get('bar')); } + public function testUninitializedSyntheticReference() + { + $container = new ContainerBuilder(); + $container->register('foo', 'stdClass')->setPublic(true)->setSynthetic(true); + $container->register('bar', 'stdClass')->setPublic(true)->setShared(false) + ->setProperty('foo', new Reference('foo', ContainerBuilder::IGNORE_ON_UNINITIALIZED_REFERENCE)); + + $container->compile(); + + $dumper = new PhpDumper($container); + eval('?>'.$dumper->dump([ + 'class' => 'Symfony_DI_PhpDumper_Test_UninitializedSyntheticReference', + 'inline_class_loader_parameter' => 'inline_requires', + ])); + + $container = new \Symfony_DI_PhpDumper_Test_UninitializedSyntheticReference(); + + $this->assertEquals((object) ['foo' => null], $container->get('bar')); + + $container->set('foo', (object) [123]); + $this->assertEquals((object) ['foo' => (object) [123]], $container->get('bar')); + } + + public function testAdawsonContainer() + { + $container = new ContainerBuilder(); + $loader = new YamlFileLoader($container, new FileLocator(self::$fixturesPath.'/yaml')); + $loader->load('services_adawson.yml'); + $container->compile(); + + $dumper = new PhpDumper($container); + $dump = $dumper->dump(); + $this->assertStringEqualsFile(self::$fixturesPath.'/php/services_adawson.php', $dumper->dump()); + } + /** * This test checks the trigger of a deprecation note and should not be removed in major releases. * @@ -972,7 +1041,7 @@ public function testPrivateServiceTriggersDeprecation() $container->compile(); $dumper = new PhpDumper($container); - eval('?>'.$dumper->dump(array('class' => 'Symfony_DI_PhpDumper_Test_Private_Service_Triggers_Deprecation'))); + eval('?>'.$dumper->dump(['class' => 'Symfony_DI_PhpDumper_Test_Private_Service_Triggers_Deprecation'])); $container = new \Symfony_DI_PhpDumper_Test_Private_Service_Triggers_Deprecation(); @@ -981,11 +1050,11 @@ public function testPrivateServiceTriggersDeprecation() public function testParameterWithMixedCase() { - $container = new ContainerBuilder(new ParameterBag(array('Foo' => 'bar', 'BAR' => 'foo'))); + $container = new ContainerBuilder(new ParameterBag(['Foo' => 'bar', 'BAR' => 'foo'])); $container->compile(); $dumper = new PhpDumper($container); - eval('?>'.$dumper->dump(array('class' => 'Symfony_DI_PhpDumper_Test_Parameter_With_Mixed_Case'))); + eval('?>'.$dumper->dump(['class' => 'Symfony_DI_PhpDumper_Test_Parameter_With_Mixed_Case'])); $container = new \Symfony_DI_PhpDumper_Test_Parameter_With_Mixed_Case(); @@ -1003,8 +1072,8 @@ public function testErroredDefinition() $container->setParameter('foo_bar', 'foo_bar'); $container->compile(); $dumper = new PhpDumper($container); - $dump = $dumper->dump(array('class' => 'Symfony_DI_PhpDumper_Errored_Definition')); - $this->assertStringEqualsFile(self::$fixturesPath.'/php/services_errored_definition.php', str_replace(str_replace('\\', '\\\\', self::$fixturesPath.DIRECTORY_SEPARATOR.'includes'.DIRECTORY_SEPARATOR), '%path%', $dump)); + $dump = $dumper->dump(['class' => 'Symfony_DI_PhpDumper_Errored_Definition']); + $this->assertStringEqualsFile(self::$fixturesPath.'/php/services_errored_definition.php', str_replace(str_replace('\\', '\\\\', self::$fixturesPath.\DIRECTORY_SEPARATOR.'includes'.\DIRECTORY_SEPARATOR), '%path%', $dump)); eval('?>'.$dump); $container = new \Symfony_DI_PhpDumper_Errored_Definition(); @@ -1021,6 +1090,17 @@ public function getEnv($prefix, $name, \Closure $getEnv) public static function getProvidedTypes() { - return array('rot13' => 'string'); + return ['rot13' => 'string']; + } +} + +class FooForDeepGraph +{ + public $bClone; + + public function __construct(\stdClass $a, \stdClass $b) + { + // clone to verify that $b has been fully initialized before + $this->bClone = clone $b; } } diff --git a/Tests/Dumper/XmlDumperTest.php b/Tests/Dumper/XmlDumperTest.php index 2e4ccf1fd..ac274c6f2 100644 --- a/Tests/Dumper/XmlDumperTest.php +++ b/Tests/Dumper/XmlDumperTest.php @@ -54,7 +54,7 @@ public function testAddService() $container = include self::$fixturesPath.'/containers/container9.php'; $dumper = new XmlDumper($container); - $this->assertEquals(str_replace('%path%', self::$fixturesPath.DIRECTORY_SEPARATOR.'includes'.DIRECTORY_SEPARATOR, file_get_contents(self::$fixturesPath.'/xml/services9.xml')), $dumper->dump(), '->dump() dumps services'); + $this->assertEquals(str_replace('%path%', self::$fixturesPath.\DIRECTORY_SEPARATOR.'includes'.\DIRECTORY_SEPARATOR, file_get_contents(self::$fixturesPath.'/xml/services9.xml')), $dumper->dump(), '->dump() dumps services'); $dumper = new XmlDumper($container = new ContainerBuilder()); $container->register('foo', 'FooClass')->addArgument(new \stdClass())->setPublic(true); @@ -123,8 +123,8 @@ public function provideDecoratedServicesData() { $fixturesPath = realpath(__DIR__.'/../Fixtures/'); - return array( - array(" + return [ + [" @@ -133,8 +133,8 @@ public function provideDecoratedServicesData() -", include $fixturesPath.'/containers/container15.php'), - array(" +", include $fixturesPath.'/containers/container15.php'], + [" @@ -143,8 +143,8 @@ public function provideDecoratedServicesData() -", include $fixturesPath.'/containers/container16.php'), - ); +", include $fixturesPath.'/containers/container16.php'], + ]; } /** @@ -163,13 +163,13 @@ public function testCompiledContainerCanBeDumped($containerFile) public function provideCompiledContainerData() { - return array( - array('container8'), - array('container9'), - array('container11'), - array('container12'), - array('container14'), - ); + return [ + ['container8'], + ['container9'], + ['container11'], + ['container12'], + ['container14'], + ]; } public function testDumpInlinedServices() @@ -194,7 +194,7 @@ public function testDumpLoad() $loader = new XmlFileLoader($container, new FileLocator(self::$fixturesPath.'/xml')); $loader->load('services_dump_load.xml'); - $this->assertEquals(array(new Reference('bar', ContainerInterface::IGNORE_ON_UNINITIALIZED_REFERENCE)), $container->getDefinition('foo')->getArguments()); + $this->assertEquals([new Reference('bar', ContainerInterface::IGNORE_ON_UNINITIALIZED_REFERENCE)], $container->getDefinition('foo')->getArguments()); $dumper = new XmlDumper($container); $this->assertStringEqualsFile(self::$fixturesPath.'/xml/services_dump_load.xml', $dumper->dump()); diff --git a/Tests/Dumper/YamlDumperTest.php b/Tests/Dumper/YamlDumperTest.php index 2a34692c5..49ee8e6f3 100644 --- a/Tests/Dumper/YamlDumperTest.php +++ b/Tests/Dumper/YamlDumperTest.php @@ -19,8 +19,8 @@ use Symfony\Component\DependencyInjection\Dumper\YamlDumper; use Symfony\Component\DependencyInjection\Loader\YamlFileLoader; use Symfony\Component\DependencyInjection\Reference; -use Symfony\Component\Yaml\Yaml; use Symfony\Component\Yaml\Parser; +use Symfony\Component\Yaml\Yaml; class YamlDumperTest extends TestCase { @@ -49,7 +49,7 @@ public function testAddService() { $container = include self::$fixturesPath.'/containers/container9.php'; $dumper = new YamlDumper($container); - $this->assertEqualYamlStructure(str_replace('%path%', self::$fixturesPath.DIRECTORY_SEPARATOR.'includes'.DIRECTORY_SEPARATOR, file_get_contents(self::$fixturesPath.'/yaml/services9.yml')), $dumper->dump(), '->dump() dumps services'); + $this->assertEqualYamlStructure(str_replace('%path%', self::$fixturesPath.\DIRECTORY_SEPARATOR.'includes'.\DIRECTORY_SEPARATOR, file_get_contents(self::$fixturesPath.'/yaml/services9.yml')), $dumper->dump(), '->dump() dumps services'); $dumper = new YamlDumper($container = new ContainerBuilder()); $container->register('foo', 'FooClass')->addArgument(new \stdClass())->setPublic(true); @@ -75,7 +75,7 @@ public function testDumpLoad() $loader = new YamlFileLoader($container, new FileLocator(self::$fixturesPath.'/yaml')); $loader->load('services_dump_load.yml'); - $this->assertEquals(array(new Reference('bar', ContainerInterface::IGNORE_ON_UNINITIALIZED_REFERENCE)), $container->getDefinition('foo')->getArguments()); + $this->assertEquals([new Reference('bar', ContainerInterface::IGNORE_ON_UNINITIALIZED_REFERENCE)], $container->getDefinition('foo')->getArguments()); $dumper = new YamlDumper($container); $this->assertStringEqualsFile(self::$fixturesPath.'/yaml/services_dump_load.yml', $dumper->dump()); diff --git a/Tests/EnvVarProcessorTest.php b/Tests/EnvVarProcessorTest.php index 79b3e47c7..b1b240316 100644 --- a/Tests/EnvVarProcessorTest.php +++ b/Tests/EnvVarProcessorTest.php @@ -31,16 +31,16 @@ public function testGetEnvString($value, $processed) public function validStrings() { - return array( - array('hello', 'hello'), - array('true', 'true'), - array('false', 'false'), - array('null', 'null'), - array('1', '1'), - array('0', '0'), - array('1.1', '1.1'), - array('1e1', '1e1'), - ); + return [ + ['hello', 'hello'], + ['true', 'true'], + ['false', 'false'], + ['null', 'null'], + ['1', '1'], + ['0', '0'], + ['1.1', '1.1'], + ['1e1', '1e1'], + ]; } /** @@ -61,15 +61,15 @@ public function testGetEnvBool($value, $processed) public function validBools() { - return array( - array('true', true), - array('false', false), - array('null', false), - array('1', true), - array('0', false), - array('1.1', true), - array('1e1', true), - ); + return [ + ['true', true], + ['false', false], + ['null', false], + ['1', true], + ['0', false], + ['1.1', true], + ['1e1', true], + ]; } /** @@ -90,11 +90,11 @@ public function testGetEnvInt($value, $processed) public function validInts() { - return array( - array('1', 1), - array('1.1', 1), - array('1e1', 10), - ); + return [ + ['1', 1], + ['1.1', 1], + ['1e1', 10], + ]; } /** @@ -115,11 +115,11 @@ public function testGetEnvIntInvalid($value) public function invalidInts() { - return array( - array('foo'), - array('true'), - array('null'), - ); + return [ + ['foo'], + ['true'], + ['null'], + ]; } /** @@ -140,11 +140,11 @@ public function testGetEnvFloat($value, $processed) public function validFloats() { - return array( - array('1', 1.0), - array('1.1', 1.1), - array('1e1', 10.0), - ); + return [ + ['1', 1.0], + ['1.1', 1.1], + ['1e1', 10.0], + ]; } /** @@ -165,11 +165,11 @@ public function testGetEnvFloatInvalid($value) public function invalidFloats() { - return array( - array('foo'), - array('true'), - array('null'), - ); + return [ + ['foo'], + ['true'], + ['null'], + ]; } /** @@ -190,10 +190,10 @@ public function testGetEnvConst($value, $processed) public function validConsts() { - return array( - array('Symfony\Component\DependencyInjection\Tests\EnvVarProcessorTest::TEST_CONST', self::TEST_CONST), - array('E_ERROR', E_ERROR), - ); + return [ + ['Symfony\Component\DependencyInjection\Tests\EnvVarProcessorTest::TEST_CONST', self::TEST_CONST], + ['E_ERROR', E_ERROR], + ]; } /** @@ -214,10 +214,10 @@ public function testGetEnvConstInvalid($value) public function invalidConsts() { - return array( - array('Symfony\Component\DependencyInjection\Tests\EnvVarProcessorTest::UNDEFINED_CONST'), - array('UNDEFINED_CONST'), - ); + return [ + ['Symfony\Component\DependencyInjection\Tests\EnvVarProcessorTest::UNDEFINED_CONST'], + ['UNDEFINED_CONST'], + ]; } public function testGetEnvBase64() @@ -251,11 +251,11 @@ public function testGetEnvJson($value, $processed) public function validJson() { - return array( - array('[1]', array(1)), - array('{"key": "value"}', array('key' => 'value')), - array(null, null), - ); + return [ + ['[1]', [1]], + ['{"key": "value"}', ['key' => 'value']], + [null, null], + ]; } /** @@ -291,13 +291,13 @@ public function testGetEnvJsonOther($value) public function otherJsonValues() { - return array( - array(1), - array(1.1), - array(true), - array(false), - array('foo'), - ); + return [ + [1], + [1.1], + [true], + [false], + ['foo'], + ]; } /** diff --git a/Tests/Extension/ExtensionTest.php b/Tests/Extension/ExtensionTest.php index 9f66bfd7c..3c912f2a1 100644 --- a/Tests/Extension/ExtensionTest.php +++ b/Tests/Extension/ExtensionTest.php @@ -23,15 +23,15 @@ class ExtensionTest extends TestCase public function testIsConfigEnabledReturnsTheResolvedValue($enabled) { $extension = new EnableableExtension(); - $this->assertSame($enabled, $extension->isConfigEnabled(new ContainerBuilder(), array('enabled' => $enabled))); + $this->assertSame($enabled, $extension->isConfigEnabled(new ContainerBuilder(), ['enabled' => $enabled])); } public function getResolvedEnabledFixtures() { - return array( - array(true), - array(false), - ); + return [ + [true], + [false], + ]; } /** @@ -42,7 +42,7 @@ public function testIsConfigEnabledOnNonEnableableConfig() { $extension = new EnableableExtension(); - $extension->isConfigEnabled(new ContainerBuilder(), array()); + $extension->isConfigEnabled(new ContainerBuilder(), []); } } diff --git a/Tests/Fixtures/Bar.php b/Tests/Fixtures/Bar.php index d243866d3..83f2da12a 100644 --- a/Tests/Fixtures/Bar.php +++ b/Tests/Fixtures/Bar.php @@ -13,7 +13,7 @@ class Bar implements BarInterface { - public function __construct($quz = null, \NonExistent $nonExistent = null, BarInterface $decorated = null, array $foo = array()) + public function __construct($quz = null, \NonExistent $nonExistent = null, BarInterface $decorated = null, array $foo = []) { } diff --git a/Tests/Fixtures/FactoryDummyWithoutReturnTypes.php b/Tests/Fixtures/FactoryDummyWithoutReturnTypes.php new file mode 100644 index 000000000..f480a668b --- /dev/null +++ b/Tests/Fixtures/FactoryDummyWithoutReturnTypes.php @@ -0,0 +1,19 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\DependencyInjection\Tests\Fixtures; + +class FactoryDummyWithoutReturnTypes +{ + public function createTestDefinition1() + { + } +} diff --git a/Tests/Fixtures/FooForCircularWithAddCalls.php b/Tests/Fixtures/FooForCircularWithAddCalls.php new file mode 100644 index 000000000..a8331dc3e --- /dev/null +++ b/Tests/Fixtures/FooForCircularWithAddCalls.php @@ -0,0 +1,19 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\DependencyInjection\Tests\Fixtures; + +class FooForCircularWithAddCalls +{ + public function call(\stdClass $argument) + { + } +} diff --git a/Tests/Fixtures/TestDefinition1.php b/Tests/Fixtures/TestDefinition1.php new file mode 100644 index 000000000..8ec76a9de --- /dev/null +++ b/Tests/Fixtures/TestDefinition1.php @@ -0,0 +1,18 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\DependencyInjection\Tests\Fixtures; + +use Symfony\Component\DependencyInjection\Definition; + +class TestDefinition1 extends Definition +{ +} diff --git a/Tests/Fixtures/TestServiceSubscriber.php b/Tests/Fixtures/TestServiceSubscriber.php index 875abe9e0..a3b042b8f 100644 --- a/Tests/Fixtures/TestServiceSubscriber.php +++ b/Tests/Fixtures/TestServiceSubscriber.php @@ -12,11 +12,11 @@ public function __construct($container) public static function getSubscribedServices() { - return array( + return [ __CLASS__, '?'.CustomDefinition::class, 'bar' => CustomDefinition::class, 'baz' => '?'.CustomDefinition::class, - ); + ]; } } diff --git a/Tests/Fixtures/config/anonymous.php b/Tests/Fixtures/config/anonymous.php index c8164d074..27fc96fc9 100644 --- a/Tests/Fixtures/config/anonymous.php +++ b/Tests/Fixtures/config/anonymous.php @@ -13,9 +13,9 @@ $s->set(null, StdClassDecorator::class) ->decorate('decorated', 'decorator42') - ->args(array(ref('decorator42'))); + ->args([ref('decorator42')]); - $s->set('listener_aggregator', FooClass::class)->public()->args(array(tagged('listener'))); + $s->set('listener_aggregator', FooClass::class)->public()->args([tagged('listener')]); $s->set(null, stdClass::class)->tag('listener'); }; diff --git a/Tests/Fixtures/config/basic.php b/Tests/Fixtures/config/basic.php index b98e894c3..a9e250b92 100644 --- a/Tests/Fixtures/config/basic.php +++ b/Tests/Fixtures/config/basic.php @@ -7,5 +7,5 @@ return function (ContainerConfigurator $c) { $s = $c->services(); $s->set(BarService::class) - ->args(array(inline('FooClass'))); + ->args([inline('FooClass')]); }; diff --git a/Tests/Fixtures/config/child.php b/Tests/Fixtures/config/child.php index 6fd84485e..8a5f2431d 100644 --- a/Tests/Fixtures/config/child.php +++ b/Tests/Fixtures/config/child.php @@ -13,7 +13,7 @@ ->set('foo') ->parent(BarService::class) ->decorate('bar', 'b', 1) - ->args(array(ref('b'))) + ->args([ref('b')]) ->class('Class2') ->file('file.php') ->parent('bar') diff --git a/Tests/Fixtures/config/defaults.php b/Tests/Fixtures/config/defaults.php index de3b99d74..2889d3fbb 100644 --- a/Tests/Fixtures/config/defaults.php +++ b/Tests/Fixtures/config/defaults.php @@ -12,10 +12,10 @@ ->private() ->autoconfigure() ->autowire() - ->tag('t', array('a' => 'b')) + ->tag('t', ['a' => 'b']) ->bind(Foo::class, ref('bar')) ->private(); - $s->set(Foo::class)->args(array(ref('bar')))->public(); + $s->set(Foo::class)->args([ref('bar')])->public(); $s->set('bar', Foo::class)->call('setFoo')->autoconfigure(false); }; diff --git a/Tests/Fixtures/config/instanceof.php b/Tests/Fixtures/config/instanceof.php index 062e8c00a..0d6aac7a0 100644 --- a/Tests/Fixtures/config/instanceof.php +++ b/Tests/Fixtures/config/instanceof.php @@ -9,8 +9,8 @@ $s = $c->services(); $s->instanceof(Prototype\Foo::class) ->property('p', 0) - ->call('setFoo', array(ref('foo'))) - ->tag('tag', array('k' => 'v')) + ->call('setFoo', [ref('foo')]) + ->tag('tag', ['k' => 'v']) ->share(false) ->lazy() ->configurator('c') diff --git a/Tests/Fixtures/config/object.php b/Tests/Fixtures/config/object.php index d8e3828e5..daf4682bf 100644 --- a/Tests/Fixtures/config/object.php +++ b/Tests/Fixtures/config/object.php @@ -9,6 +9,6 @@ public function __invoke(ContainerConfigurator $c) { $s = $c->services(); $s->set(BarService::class) - ->args(array(inline('FooClass'))); + ->args([inline('FooClass')]); } }; diff --git a/Tests/Fixtures/config/prototype.expected.yml b/Tests/Fixtures/config/prototype.expected.yml index 5394535ca..ebfe087d7 100644 --- a/Tests/Fixtures/config/prototype.expected.yml +++ b/Tests/Fixtures/config/prototype.expected.yml @@ -10,7 +10,7 @@ services: tags: - { name: foo } - { name: baz } - deprecated: %service_id% + deprecated: '%service_id%' arguments: [1] factory: f Symfony\Component\DependencyInjection\Tests\Fixtures\Prototype\Sub\Bar: @@ -19,7 +19,7 @@ services: tags: - { name: foo } - { name: baz } - deprecated: %service_id% + deprecated: '%service_id%' lazy: true arguments: [1] factory: f diff --git a/Tests/Fixtures/config/prototype.php b/Tests/Fixtures/config/prototype.php index 622c51af5..e2884aa20 100644 --- a/Tests/Fixtures/config/prototype.php +++ b/Tests/Fixtures/config/prototype.php @@ -12,8 +12,8 @@ ->exclude('../Prototype/{OtherDir,BadClasses}') ->factory('f') ->deprecate('%service_id%') - ->args(array(0)) - ->args(array(1)) + ->args([0]) + ->args([1]) ->autoconfigure(false) ->tag('foo') ->parent('foo'); diff --git a/Tests/Fixtures/config/services9.php b/Tests/Fixtures/config/services9.php index 8055f8ce7..4a7172b46 100644 --- a/Tests/Fixtures/config/services9.php +++ b/Tests/Fixtures/config/services9.php @@ -19,65 +19,65 @@ $s = $c->services()->defaults() ->public(); $s->set('foo') - ->args(array('foo', ref('foo.baz'), array('%foo%' => 'foo is %foo%', 'foobar' => '%foo%'), true, ref('service_container'))) + ->args(['foo', ref('foo.baz'), ['%foo%' => 'foo is %foo%', 'foobar' => '%foo%'], true, ref('service_container')]) ->class(FooClass::class) - ->tag('foo', array('foo' => 'foo')) - ->tag('foo', array('bar' => 'bar', 'baz' => 'baz')) - ->factory(array(FooClass::class, 'getInstance')) + ->tag('foo', ['foo' => 'foo']) + ->tag('foo', ['bar' => 'bar', 'baz' => 'baz']) + ->factory([FooClass::class, 'getInstance']) ->property('foo', 'bar') ->property('moo', ref('foo.baz')) - ->property('qux', array('%foo%' => 'foo is %foo%', 'foobar' => '%foo%')) - ->call('setBar', array(ref('bar'))) + ->property('qux', ['%foo%' => 'foo is %foo%', 'foobar' => '%foo%']) + ->call('setBar', [ref('bar')]) ->call('initialize') ->configurator('sc_configure'); $s->set('foo.baz', '%baz_class%') - ->factory(array('%baz_class%', 'getInstance')) - ->configurator(array('%baz_class%', 'configureStatic1')); + ->factory(['%baz_class%', 'getInstance']) + ->configurator(['%baz_class%', 'configureStatic1']); $s->set('bar', FooClass::class) - ->args(array('foo', ref('foo.baz'), new Parameter('foo_bar'))) - ->configurator(array(ref('foo.baz'), 'configure')); + ->args(['foo', ref('foo.baz'), new Parameter('foo_bar')]) + ->configurator([ref('foo.baz'), 'configure']); $s->set('foo_bar', '%foo_class%') - ->args(array(ref('deprecated_service'))) + ->args([ref('deprecated_service')]) ->share(false); $s->set('method_call1', 'Bar\FooClass') ->file(realpath(__DIR__.'/../includes/foo.php')) - ->call('setBar', array(ref('foo'))) - ->call('setBar', array(ref('foo2')->nullOnInvalid())) - ->call('setBar', array(ref('foo3')->ignoreOnInvalid())) - ->call('setBar', array(ref('foobaz')->ignoreOnInvalid())) - ->call('setBar', array(expr('service("foo").foo() ~ (container.hasParameter("foo") ? parameter("foo") : "default")'))); + ->call('setBar', [ref('foo')]) + ->call('setBar', [ref('foo2')->nullOnInvalid()]) + ->call('setBar', [ref('foo3')->ignoreOnInvalid()]) + ->call('setBar', [ref('foobaz')->ignoreOnInvalid()]) + ->call('setBar', [expr('service("foo").foo() ~ (container.hasParameter("foo") ? parameter("foo") : "default")')]); $s->set('foo_with_inline', 'Foo') - ->call('setBar', array(ref('inlined'))); + ->call('setBar', [ref('inlined')]); $s->set('inlined', 'Bar') ->property('pub', 'pub') - ->call('setBaz', array(ref('baz'))) + ->call('setBaz', [ref('baz')]) ->private(); $s->set('baz', 'Baz') - ->call('setFoo', array(ref('foo_with_inline'))); + ->call('setFoo', [ref('foo_with_inline')]); $s->set('request', 'Request') ->synthetic(); $s->set('configurator_service', 'ConfClass') ->private() - ->call('setFoo', array(ref('baz'))); + ->call('setFoo', [ref('baz')]); $s->set('configured_service', 'stdClass') - ->configurator(array(ref('configurator_service'), 'configureStdClass')); + ->configurator([ref('configurator_service'), 'configureStdClass']); $s->set('configurator_service_simple', 'ConfClass') - ->args(array('bar')) + ->args(['bar']) ->private(); $s->set('configured_service_simple', 'stdClass') - ->configurator(array(ref('configurator_service_simple'), 'configureStdClass')); + ->configurator([ref('configurator_service_simple'), 'configureStdClass']); $s->set('decorated', 'stdClass'); @@ -95,28 +95,28 @@ ->private(); $s->set('factory_service', 'Bar') - ->factory(array(ref('foo.baz'), 'getInstance')); + ->factory([ref('foo.baz'), 'getInstance']); $s->set('new_factory_service', 'FooBarBaz') ->property('foo', 'bar') - ->factory(array(ref('new_factory'), 'getInstance')); + ->factory([ref('new_factory'), 'getInstance']); $s->set('service_from_static_method', 'Bar\FooClass') - ->factory(array('Bar\FooClass', 'getInstance')); + ->factory(['Bar\FooClass', 'getInstance']); $s->set('factory_simple', 'SimpleFactoryClass') ->deprecate() - ->args(array('foo')) + ->args(['foo']) ->private(); $s->set('factory_service_simple', 'Bar') - ->factory(array(ref('factory_simple'), 'getInstance')); + ->factory([ref('factory_simple'), 'getInstance']); $s->set('lazy_context', 'LazyContext') - ->args(array(iterator(array('k1' => ref('foo.baz'), 'k2' => ref('service_container'))), iterator(array()))); + ->args([iterator(['k1' => ref('foo.baz'), 'k2' => ref('service_container')]), iterator([])]); $s->set('lazy_context_ignore_invalid_ref', 'LazyContext') - ->args(array(iterator(array(ref('foo.baz'), ref('invalid')->ignoreOnInvalid())), iterator(array()))); + ->args([iterator([ref('foo.baz'), ref('invalid')->ignoreOnInvalid()]), iterator([])]); $s->set('BAR', 'stdClass')->property('bar', ref('bar')); $s->set('bar2', 'stdClass'); @@ -128,10 +128,10 @@ $s->set('tagged_iterator', 'Bar') ->public() - ->args(array(tagged('foo'))); + ->args([tagged('foo')]); $s->set('runtime_error', 'stdClass') - ->args(array(new Reference('errored_definition', ContainerInterface::RUNTIME_EXCEPTION_ON_INVALID_REFERENCE))) + ->args([new Reference('errored_definition', ContainerInterface::RUNTIME_EXCEPTION_ON_INVALID_REFERENCE)]) ->public(); $s->set('errored_definition', 'stdClass')->private(); diff --git a/Tests/Fixtures/containers/container11.php b/Tests/Fixtures/containers/container11.php index 150cd7921..91e5c2633 100644 --- a/Tests/Fixtures/containers/container11.php +++ b/Tests/Fixtures/containers/container11.php @@ -6,7 +6,7 @@ $container = new ContainerBuilder(); $container-> register('foo', 'FooClass')-> - addArgument(new Definition('BarClass', array(new Definition('BazClass')))) + addArgument(new Definition('BarClass', [new Definition('BazClass')])) ->setPublic(true) ; diff --git a/Tests/Fixtures/containers/container12.php b/Tests/Fixtures/containers/container12.php index bc527eb79..ef0770302 100644 --- a/Tests/Fixtures/containers/container12.php +++ b/Tests/Fixtures/containers/container12.php @@ -6,7 +6,7 @@ $container-> register('foo', 'FooClass\\Foo')-> addArgument('foo<>&bar')-> - addTag('foo"bar\\bar', array('foo' => 'foo"barřž€')) + addTag('foo"bar\\bar', ['foo' => 'foo"barřž€']) ->setPublic(true) ; diff --git a/Tests/Fixtures/containers/container19.php b/Tests/Fixtures/containers/container19.php index 823a77f53..c3af5c960 100644 --- a/Tests/Fixtures/containers/container19.php +++ b/Tests/Fixtures/containers/container19.php @@ -7,9 +7,12 @@ $container = new ContainerBuilder(); +$container->setParameter('env(FOO)', 'Bar\FaooClass'); +$container->setParameter('foo', '%env(FOO)%'); + $container - ->register('service_from_anonymous_factory', 'Bar\FooClass') - ->setFactory(array(new Definition('Bar\FooClass'), 'getInstance')) + ->register('service_from_anonymous_factory', '%foo%') + ->setFactory([new Definition('%foo%'), 'getInstance']) ->setPublic(true) ; @@ -17,7 +20,7 @@ $anonymousServiceWithFactory->setFactory('Bar\FooClass::getInstance'); $container ->register('service_with_method_call_and_factory', 'Bar\FooClass') - ->addMethodCall('setBar', array($anonymousServiceWithFactory)) + ->addMethodCall('setBar', [$anonymousServiceWithFactory]) ->setPublic(true) ; diff --git a/Tests/Fixtures/containers/container21.php b/Tests/Fixtures/containers/container21.php index 298c9266a..d82cf3853 100644 --- a/Tests/Fixtures/containers/container21.php +++ b/Tests/Fixtures/containers/container21.php @@ -6,15 +6,15 @@ $container = new ContainerBuilder(); $bar = new Definition('Bar'); -$bar->setConfigurator(array(new Definition('Baz'), 'configureBar')); +$bar->setConfigurator([new Definition('Baz'), 'configureBar']); $fooFactory = new Definition('FooFactory'); -$fooFactory->setFactory(array(new Definition('Foobar'), 'createFooFactory')); +$fooFactory->setFactory([new Definition('Foobar'), 'createFooFactory']); $container ->register('foo', 'Foo') - ->setFactory(array($fooFactory, 'createFoo')) - ->setConfigurator(array($bar, 'configureFoo')) + ->setFactory([$fooFactory, 'createFoo']) + ->setConfigurator([$bar, 'configureFoo']) ->setPublic(true) ; diff --git a/Tests/Fixtures/containers/container8.php b/Tests/Fixtures/containers/container8.php index 31e6baab3..26d436b4d 100644 --- a/Tests/Fixtures/containers/container8.php +++ b/Tests/Fixtures/containers/container8.php @@ -3,14 +3,14 @@ use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\ParameterBag\ParameterBag; -$container = new ContainerBuilder(new ParameterBag(array( +$container = new ContainerBuilder(new ParameterBag([ 'foo' => '%baz%', 'baz' => 'bar', 'bar' => 'foo is %%foo bar', 'escape' => '@escapeme', - 'values' => array(true, false, null, 0, 1000.3, 'true', 'false', 'null'), + 'values' => [true, false, null, 0, 1000.3, 'true', 'false', 'null'], 'binary' => "\xf0\xf0\xf0\xf0", 'binary-control-char' => "This is a Bell char \x07", -))); +])); return $container; diff --git a/Tests/Fixtures/containers/container9.php b/Tests/Fixtures/containers/container9.php index c403a3af4..520f235b2 100644 --- a/Tests/Fixtures/containers/container9.php +++ b/Tests/Fixtures/containers/container9.php @@ -14,26 +14,26 @@ $container = new ContainerBuilder(); $container ->register('foo', '\Bar\FooClass') - ->addTag('foo', array('foo' => 'foo')) - ->addTag('foo', array('bar' => 'bar', 'baz' => 'baz')) - ->setFactory(array('Bar\\FooClass', 'getInstance')) - ->setArguments(array('foo', new Reference('foo.baz'), array('%foo%' => 'foo is %foo%', 'foobar' => '%foo%'), true, new Reference('service_container'))) - ->setProperties(array('foo' => 'bar', 'moo' => new Reference('foo.baz'), 'qux' => array('%foo%' => 'foo is %foo%', 'foobar' => '%foo%'))) - ->addMethodCall('setBar', array(new Reference('bar'))) + ->addTag('foo', ['foo' => 'foo']) + ->addTag('foo', ['bar' => 'bar', 'baz' => 'baz']) + ->setFactory(['Bar\\FooClass', 'getInstance']) + ->setArguments(['foo', new Reference('foo.baz'), ['%foo%' => 'foo is %foo%', 'foobar' => '%foo%'], true, new Reference('service_container')]) + ->setProperties(['foo' => 'bar', 'moo' => new Reference('foo.baz'), 'qux' => ['%foo%' => 'foo is %foo%', 'foobar' => '%foo%']]) + ->addMethodCall('setBar', [new Reference('bar')]) ->addMethodCall('initialize') ->setConfigurator('sc_configure') ->setPublic(true) ; $container ->register('foo.baz', '%baz_class%') - ->setFactory(array('%baz_class%', 'getInstance')) - ->setConfigurator(array('%baz_class%', 'configureStatic1')) + ->setFactory(['%baz_class%', 'getInstance']) + ->setConfigurator(['%baz_class%', 'configureStatic1']) ->setPublic(true) ; $container ->register('bar', 'Bar\FooClass') - ->setArguments(array('foo', new Reference('foo.baz'), new Parameter('foo_bar'))) - ->setConfigurator(array(new Reference('foo.baz'), 'configure')) + ->setArguments(['foo', new Reference('foo.baz'), new Parameter('foo_bar')]) + ->setConfigurator([new Reference('foo.baz'), 'configure']) ->setPublic(true) ; $container @@ -43,35 +43,35 @@ ->setPublic(true) ; $container->getParameterBag()->clear(); -$container->getParameterBag()->add(array( +$container->getParameterBag()->add([ 'baz_class' => 'BazClass', 'foo_class' => 'Bar\FooClass', 'foo' => 'bar', -)); +]); $container ->register('method_call1', 'Bar\FooClass') ->setFile(realpath(__DIR__.'/../includes/foo.php')) - ->addMethodCall('setBar', array(new Reference('foo'))) - ->addMethodCall('setBar', array(new Reference('foo2', ContainerInterface::NULL_ON_INVALID_REFERENCE))) - ->addMethodCall('setBar', array(new Reference('foo3', ContainerInterface::IGNORE_ON_INVALID_REFERENCE))) - ->addMethodCall('setBar', array(new Reference('foobaz', ContainerInterface::IGNORE_ON_INVALID_REFERENCE))) - ->addMethodCall('setBar', array(new Expression('service("foo").foo() ~ (container.hasParameter("foo") ? parameter("foo") : "default")'))) + ->addMethodCall('setBar', [new Reference('foo')]) + ->addMethodCall('setBar', [new Reference('foo2', ContainerInterface::NULL_ON_INVALID_REFERENCE)]) + ->addMethodCall('setBar', [new Reference('foo3', ContainerInterface::IGNORE_ON_INVALID_REFERENCE)]) + ->addMethodCall('setBar', [new Reference('foobaz', ContainerInterface::IGNORE_ON_INVALID_REFERENCE)]) + ->addMethodCall('setBar', [new Expression('service("foo").foo() ~ (container.hasParameter("foo") ? parameter("foo") : "default")')]) ->setPublic(true) ; $container ->register('foo_with_inline', 'Foo') - ->addMethodCall('setBar', array(new Reference('inlined'))) + ->addMethodCall('setBar', [new Reference('inlined')]) ->setPublic(true) ; $container ->register('inlined', 'Bar') ->setProperty('pub', 'pub') - ->addMethodCall('setBaz', array(new Reference('baz'))) + ->addMethodCall('setBaz', [new Reference('baz')]) ->setPublic(false) ; $container ->register('baz', 'Baz') - ->addMethodCall('setFoo', array(new Reference('foo_with_inline'))) + ->addMethodCall('setFoo', [new Reference('foo_with_inline')]) ->setPublic(true) ; $container @@ -82,11 +82,11 @@ $container ->register('configurator_service', 'ConfClass') ->setPublic(false) - ->addMethodCall('setFoo', array(new Reference('baz'))) + ->addMethodCall('setFoo', [new Reference('baz')]) ; $container ->register('configured_service', 'stdClass') - ->setConfigurator(array(new Reference('configurator_service'), 'configureStdClass')) + ->setConfigurator([new Reference('configurator_service'), 'configureStdClass']) ->setPublic(true) ; $container @@ -96,7 +96,7 @@ ; $container ->register('configured_service_simple', 'stdClass') - ->setConfigurator(array(new Reference('configurator_service_simple'), 'configureStdClass')) + ->setConfigurator([new Reference('configurator_service_simple'), 'configureStdClass']) ->setPublic(true) ; $container @@ -125,18 +125,18 @@ ; $container ->register('factory_service', 'Bar') - ->setFactory(array(new Reference('foo.baz'), 'getInstance')) + ->setFactory([new Reference('foo.baz'), 'getInstance']) ->setPublic(true) ; $container ->register('new_factory_service', 'FooBarBaz') ->setProperty('foo', 'bar') - ->setFactory(array(new Reference('new_factory'), 'getInstance')) + ->setFactory([new Reference('new_factory'), 'getInstance']) ->setPublic(true) ; $container ->register('service_from_static_method', 'Bar\FooClass') - ->setFactory(array('Bar\FooClass', 'getInstance')) + ->setFactory(['Bar\FooClass', 'getInstance']) ->setPublic(true) ; $container @@ -147,17 +147,17 @@ ; $container ->register('factory_service_simple', 'Bar') - ->setFactory(array(new Reference('factory_simple'), 'getInstance')) + ->setFactory([new Reference('factory_simple'), 'getInstance']) ->setPublic(true) ; $container ->register('lazy_context', 'LazyContext') - ->setArguments(array(new IteratorArgument(array('k1' => new Reference('foo.baz'), 'k2' => new Reference('service_container'))), new IteratorArgument(array()))) + ->setArguments([new IteratorArgument(['k1' => new Reference('foo.baz'), 'k2' => new Reference('service_container')]), new IteratorArgument([])]) ->setPublic(true) ; $container ->register('lazy_context_ignore_invalid_ref', 'LazyContext') - ->setArguments(array(new IteratorArgument(array(new Reference('foo.baz'), new Reference('invalid', ContainerInterface::IGNORE_ON_INVALID_REFERENCE))), new IteratorArgument(array()))) + ->setArguments([new IteratorArgument([new Reference('foo.baz'), new Reference('invalid', ContainerInterface::IGNORE_ON_INVALID_REFERENCE)]), new IteratorArgument([])]) ->setPublic(true) ; $container diff --git a/Tests/Fixtures/containers/container_almost_circular.php b/Tests/Fixtures/containers/container_almost_circular.php index dff937ccd..df136cfa5 100644 --- a/Tests/Fixtures/containers/container_almost_circular.php +++ b/Tests/Fixtures/containers/container_almost_circular.php @@ -4,6 +4,7 @@ use Symfony\Component\DependencyInjection\Definition; use Symfony\Component\DependencyInjection\Dumper\PhpDumper; use Symfony\Component\DependencyInjection\Reference; +use Symfony\Component\DependencyInjection\Tests\Fixtures\FooForCircularWithAddCalls; $public = 'public' === $visibility; $container = new ContainerBuilder(); @@ -14,7 +15,7 @@ ->addArgument(new Reference('bar')); $container->register('bar', BarCircular::class)->setPublic($public) - ->addMethodCall('addFoobar', array(new Reference('foobar'))); + ->addMethodCall('addFoobar', [new Reference('foobar')]); $container->register('foobar', FoobarCircular::class)->setPublic($public) ->addArgument(new Reference('foo')); @@ -25,7 +26,7 @@ ->addArgument(new Reference('bar2')); $container->register('bar2', BarCircular::class)->setPublic(!$public) - ->addMethodCall('addFoobar', array(new Reference('foobar2'))); + ->addMethodCall('addFoobar', [new Reference('foobar2')]); $container->register('foobar2', FoobarCircular::class)->setPublic($public) ->addArgument(new Reference('foo2')); @@ -33,7 +34,7 @@ // simple inline setter with internal reference $container->register('bar3', BarCircular::class)->setPublic(true) - ->addMethodCall('addFoobar', array(new Reference('foobar3'), new Reference('foobar3'))); + ->addMethodCall('addFoobar', [new Reference('foobar3'), new Reference('foobar3')]); $container->register('foobar3', FoobarCircular::class)->setPublic($public); @@ -55,4 +56,93 @@ ->addArgument(new Reference('foo5')) ->setProperty('foo', new Reference('foo5')); +// doctrine-like event system + some extra + +$container->register('manager', 'stdClass')->setPublic(true) + ->addArgument(new Reference('connection')); + +$container->register('logger', 'stdClass')->setPublic(true) + ->addArgument(new Reference('connection')) + ->setProperty('handler', (new Definition('stdClass'))->addArgument(new Reference('manager'))) +; +$container->register('connection', 'stdClass')->setPublic(true) + ->addArgument(new Reference('dispatcher')) + ->addArgument(new Reference('config')); + +$container->register('config', 'stdClass')->setPublic(false) + ->setProperty('logger', new Reference('logger')); + +$container->register('dispatcher', 'stdClass')->setPublic($public) + ->setLazy($public) + ->setProperty('subscriber', new Reference('subscriber')); + +$container->register('subscriber', 'stdClass')->setPublic(true) + ->addArgument(new Reference('manager')); + +// doctrine-like event system + some extra (bis) + +$container->register('manager2', 'stdClass')->setPublic(true) + ->addArgument(new Reference('connection2')); + +$container->register('logger2', 'stdClass')->setPublic(false) + ->addArgument(new Reference('connection2')) + ->setProperty('handler2', (new Definition('stdClass'))->addArgument(new Reference('manager2'))) +; +$container->register('connection2', 'stdClass')->setPublic(true) + ->addArgument(new Reference('dispatcher2')) + ->addArgument(new Reference('config2')); + +$container->register('config2', 'stdClass')->setPublic(false) + ->setProperty('logger2', new Reference('logger2')); + +$container->register('dispatcher2', 'stdClass')->setPublic($public) + ->setLazy($public) + ->setProperty('subscriber2', new Reference('subscriber2')); + +$container->register('subscriber2', 'stdClass')->setPublic(false) + ->addArgument(new Reference('manager2')); + +// private service involved in a loop + +$container->register('foo6', 'stdClass') + ->setPublic(true) + ->setProperty('bar6', new Reference('bar6')); + +$container->register('bar6', 'stdClass') + ->setPublic(false) + ->addArgument(new Reference('foo6')); + +$container->register('baz6', 'stdClass') + ->setPublic(true) + ->setProperty('bar6', new Reference('bar6')); + +// provided by Christian Schiffler + +$container + ->register('root', 'stdClass') + ->setArguments([new Reference('level2'), new Reference('multiuse1')]) + ->setPublic(true); + +$container + ->register('level2', FooForCircularWithAddCalls::class) + ->addMethodCall('call', [new Reference('level3')]); + +$container->register('multiuse1', 'stdClass'); + +$container + ->register('level3', 'stdClass') + ->addArgument(new Reference('level4')); + +$container + ->register('level4', 'stdClass') + ->setArguments([new Reference('multiuse1'), new Reference('level5')]); + +$container + ->register('level5', 'stdClass') + ->addArgument(new Reference('level6')); + +$container + ->register('level6', FooForCircularWithAddCalls::class) + ->addMethodCall('call', [new Reference('level5')]); + return $container; diff --git a/Tests/Fixtures/containers/container_env_in_id.php b/Tests/Fixtures/containers/container_env_in_id.php index 4699f4101..1e851cf01 100644 --- a/Tests/Fixtures/containers/container_env_in_id.php +++ b/Tests/Fixtures/containers/container_env_in_id.php @@ -11,7 +11,7 @@ $container->register('foo', 'stdClass')->setPublic(true) ->addArgument(new Reference('bar_%env(BAR)%')) - ->addArgument(array('baz_%env(BAR)%' => new Reference('baz_%env(BAR)%'))); + ->addArgument(['baz_%env(BAR)%' => new Reference('baz_%env(BAR)%')]); $container->register('bar', 'stdClass')->setPublic(true) ->addArgument(new Reference('bar_%env(BAR)%')); diff --git a/Tests/Fixtures/containers/container_uninitialized_ref.php b/Tests/Fixtures/containers/container_uninitialized_ref.php index 7aeefb4d5..36c05c3fa 100644 --- a/Tests/Fixtures/containers/container_uninitialized_ref.php +++ b/Tests/Fixtures/containers/container_uninitialized_ref.php @@ -33,16 +33,16 @@ ->setProperty('foo1', new Reference('foo1', $container::IGNORE_ON_UNINITIALIZED_REFERENCE)) ->setProperty('foo2', new Reference('foo2', $container::IGNORE_ON_UNINITIALIZED_REFERENCE)) ->setProperty('foo3', new Reference('foo3', $container::IGNORE_ON_UNINITIALIZED_REFERENCE)) - ->setProperty('closures', array( + ->setProperty('closures', [ new ServiceClosureArgument(new Reference('foo1', $container::IGNORE_ON_UNINITIALIZED_REFERENCE)), new ServiceClosureArgument(new Reference('foo2', $container::IGNORE_ON_UNINITIALIZED_REFERENCE)), new ServiceClosureArgument(new Reference('foo3', $container::IGNORE_ON_UNINITIALIZED_REFERENCE)), - )) - ->setProperty('iter', new IteratorArgument(array( + ]) + ->setProperty('iter', new IteratorArgument([ 'foo1' => new Reference('foo1', $container::IGNORE_ON_UNINITIALIZED_REFERENCE), 'foo2' => new Reference('foo2', $container::IGNORE_ON_UNINITIALIZED_REFERENCE), 'foo3' => new Reference('foo3', $container::IGNORE_ON_UNINITIALIZED_REFERENCE), - ))) + ])) ->setPublic(true) ; diff --git a/Tests/Fixtures/graphviz/services_inline.dot b/Tests/Fixtures/graphviz/services_inline.dot new file mode 100644 index 000000000..b430b186d --- /dev/null +++ b/Tests/Fixtures/graphviz/services_inline.dot @@ -0,0 +1,10 @@ +digraph sc { + ratio="compress" + node [fontsize="11" fontname="Arial" shape="record"]; + edge [fontsize="9" fontname="Arial" color="grey" arrowhead="open" arrowsize="0.5"]; + + node_service_container [label="service_container (Psr\Container\ContainerInterface, Symfony\Component\DependencyInjection\ContainerInterface)\nSymfony\\Component\\DependencyInjection\\ContainerInterface\n", shape=record, fillcolor="#eeeeee", style="filled"]; + node_foo [label="foo\nstdClass\n", shape=record, fillcolor="#eeeeee", style="filled"]; + node_bar [label="bar\nstdClass\n", shape=record, fillcolor="#eeeeee", style="filled"]; + node_foo -> node_bar [label="" style="filled"]; +} diff --git a/Tests/Fixtures/includes/ProjectExtension.php b/Tests/Fixtures/includes/ProjectExtension.php index e01c21326..81ea2b18b 100644 --- a/Tests/Fixtures/includes/ProjectExtension.php +++ b/Tests/Fixtures/includes/ProjectExtension.php @@ -13,7 +13,7 @@ public function load(array $configs, ContainerBuilder $configuration) if ($configs) { $config = array_merge(...$configs); } else { - $config = array(); + $config = []; } $configuration->register('project.service.bar', 'FooClass')->setPublic(true); diff --git a/Tests/Fixtures/includes/autowiring_classes.php b/Tests/Fixtures/includes/autowiring_classes.php index d806f294d..a2f872168 100644 --- a/Tests/Fixtures/includes/autowiring_classes.php +++ b/Tests/Fixtures/includes/autowiring_classes.php @@ -361,7 +361,7 @@ interface DecoratorInterface class Decorated implements DecoratorInterface { - public function __construct($quz = null, \NonExistent $nonExistent = null, DecoratorInterface $decorated = null, array $foo = array()) + public function __construct($quz = null, \NonExistent $nonExistent = null, DecoratorInterface $decorated = null, array $foo = []) { } } @@ -373,6 +373,13 @@ public function __construct(LoggerInterface $logger, DecoratorInterface $decorat } } +class DecoratedDecorator implements DecoratorInterface +{ + public function __construct(DecoratorInterface $decorator) + { + } +} + class NonAutowirableDecorator implements DecoratorInterface { public function __construct(LoggerInterface $logger, DecoratorInterface $decorated1, DecoratorInterface $decorated2) diff --git a/Tests/Fixtures/includes/foo.php b/Tests/Fixtures/includes/foo.php index bcb4e20a9..20bc928b9 100644 --- a/Tests/Fixtures/includes/foo.php +++ b/Tests/Fixtures/includes/foo.php @@ -11,14 +11,14 @@ class FooClass public $initialized = false; public $configured = false; public $called = false; - public $arguments = array(); + public $arguments = []; - public function __construct($arguments = array()) + public function __construct($arguments = []) { $this->arguments = $arguments; } - public static function getInstance($arguments = array()) + public static function getInstance($arguments = []) { $obj = new self($arguments); $obj->called = true; diff --git a/Tests/Fixtures/ini/types.ini b/Tests/Fixtures/ini/types.ini index 19cc5b3b3..75840907d 100644 --- a/Tests/Fixtures/ini/types.ini +++ b/Tests/Fixtures/ini/types.ini @@ -11,9 +11,10 @@ constant = PHP_VERSION 12 = 12 12_string = '12' + 12_quoted_number = "12" 12_comment = 12 ; comment 12_string_comment = '12' ; comment - 12_string_comment_again = "12" ; comment + 12_quoted_number_comment = "12" ; comment -12 = -12 0 = 0 1 = 1 diff --git a/Tests/Fixtures/php/custom_container_class_constructor_without_arguments.php b/Tests/Fixtures/php/custom_container_class_constructor_without_arguments.php index a6b9962b3..d56f6fdf5 100644 --- a/Tests/Fixtures/php/custom_container_class_constructor_without_arguments.php +++ b/Tests/Fixtures/php/custom_container_class_constructor_without_arguments.php @@ -19,26 +19,26 @@ class ProjectServiceContainer extends \Symfony\Component\DependencyInjection\Tests\Fixtures\Container\ConstructorWithoutArgumentsContainer { private $parameters; - private $targetDirs = array(); + private $targetDirs = []; /** * @internal but protected for BC on cache:clear */ - protected $privates = array(); + protected $privates = []; public function __construct() { parent::__construct(); $this->parameterBag = null; - $this->services = $this->privates = array(); + $this->services = $this->privates = []; - $this->aliases = array(); + $this->aliases = []; } public function reset() { - $this->privates = array(); + $this->privates = []; parent::reset(); } @@ -54,9 +54,9 @@ public function isCompiled() public function getRemovedIds() { - return array( + return [ 'Psr\\Container\\ContainerInterface' => true, 'Symfony\\Component\\DependencyInjection\\ContainerInterface' => true, - ); + ]; } } diff --git a/Tests/Fixtures/php/custom_container_class_with_mandatory_constructor_arguments.php b/Tests/Fixtures/php/custom_container_class_with_mandatory_constructor_arguments.php index e513fd721..daa7102ff 100644 --- a/Tests/Fixtures/php/custom_container_class_with_mandatory_constructor_arguments.php +++ b/Tests/Fixtures/php/custom_container_class_with_mandatory_constructor_arguments.php @@ -19,23 +19,23 @@ class ProjectServiceContainer extends \Symfony\Component\DependencyInjection\Tests\Fixtures\Container\ConstructorWithMandatoryArgumentsContainer { private $parameters; - private $targetDirs = array(); + private $targetDirs = []; /** * @internal but protected for BC on cache:clear */ - protected $privates = array(); + protected $privates = []; public function __construct() { - $this->services = $this->privates = array(); + $this->services = $this->privates = []; - $this->aliases = array(); + $this->aliases = []; } public function reset() { - $this->privates = array(); + $this->privates = []; parent::reset(); } @@ -51,9 +51,9 @@ public function isCompiled() public function getRemovedIds() { - return array( + return [ 'Psr\\Container\\ContainerInterface' => true, 'Symfony\\Component\\DependencyInjection\\ContainerInterface' => true, - ); + ]; } } diff --git a/Tests/Fixtures/php/custom_container_class_with_optional_constructor_arguments.php b/Tests/Fixtures/php/custom_container_class_with_optional_constructor_arguments.php index 84986f163..45aab35eb 100644 --- a/Tests/Fixtures/php/custom_container_class_with_optional_constructor_arguments.php +++ b/Tests/Fixtures/php/custom_container_class_with_optional_constructor_arguments.php @@ -19,26 +19,26 @@ class ProjectServiceContainer extends \Symfony\Component\DependencyInjection\Tests\Fixtures\Container\ConstructorWithOptionalArgumentsContainer { private $parameters; - private $targetDirs = array(); + private $targetDirs = []; /** * @internal but protected for BC on cache:clear */ - protected $privates = array(); + protected $privates = []; public function __construct() { parent::__construct(); $this->parameterBag = null; - $this->services = $this->privates = array(); + $this->services = $this->privates = []; - $this->aliases = array(); + $this->aliases = []; } public function reset() { - $this->privates = array(); + $this->privates = []; parent::reset(); } @@ -54,9 +54,9 @@ public function isCompiled() public function getRemovedIds() { - return array( + return [ 'Psr\\Container\\ContainerInterface' => true, 'Symfony\\Component\\DependencyInjection\\ContainerInterface' => true, - ); + ]; } } diff --git a/Tests/Fixtures/php/custom_container_class_without_constructor.php b/Tests/Fixtures/php/custom_container_class_without_constructor.php index 0a4975b7d..ab8c816e6 100644 --- a/Tests/Fixtures/php/custom_container_class_without_constructor.php +++ b/Tests/Fixtures/php/custom_container_class_without_constructor.php @@ -19,23 +19,23 @@ class ProjectServiceContainer extends \Symfony\Component\DependencyInjection\Tests\Fixtures\Container\NoConstructorContainer { private $parameters; - private $targetDirs = array(); + private $targetDirs = []; /** * @internal but protected for BC on cache:clear */ - protected $privates = array(); + protected $privates = []; public function __construct() { - $this->services = $this->privates = array(); + $this->services = $this->privates = []; - $this->aliases = array(); + $this->aliases = []; } public function reset() { - $this->privates = array(); + $this->privates = []; parent::reset(); } @@ -51,9 +51,9 @@ public function isCompiled() public function getRemovedIds() { - return array( + return [ 'Psr\\Container\\ContainerInterface' => true, 'Symfony\\Component\\DependencyInjection\\ContainerInterface' => true, - ); + ]; } } diff --git a/Tests/Fixtures/php/services1-1.php b/Tests/Fixtures/php/services1-1.php index a04d80aff..ed34a0af5 100644 --- a/Tests/Fixtures/php/services1-1.php +++ b/Tests/Fixtures/php/services1-1.php @@ -19,23 +19,23 @@ class Container extends \Symfony\Component\DependencyInjection\Dump\AbstractContainer { private $parameters; - private $targetDirs = array(); + private $targetDirs = []; /** * @internal but protected for BC on cache:clear */ - protected $privates = array(); + protected $privates = []; public function __construct() { - $this->services = $this->privates = array(); + $this->services = $this->privates = []; - $this->aliases = array(); + $this->aliases = []; } public function reset() { - $this->privates = array(); + $this->privates = []; parent::reset(); } @@ -51,9 +51,9 @@ public function isCompiled() public function getRemovedIds() { - return array( + return [ 'Psr\\Container\\ContainerInterface' => true, 'Symfony\\Component\\DependencyInjection\\ContainerInterface' => true, - ); + ]; } } diff --git a/Tests/Fixtures/php/services1.php b/Tests/Fixtures/php/services1.php index f25c59b81..4c15bfa7e 100644 --- a/Tests/Fixtures/php/services1.php +++ b/Tests/Fixtures/php/services1.php @@ -17,23 +17,23 @@ class ProjectServiceContainer extends Container { private $parameters; - private $targetDirs = array(); + private $targetDirs = []; /** * @internal but protected for BC on cache:clear */ - protected $privates = array(); + protected $privates = []; public function __construct() { - $this->services = $this->privates = array(); + $this->services = $this->privates = []; - $this->aliases = array(); + $this->aliases = []; } public function reset() { - $this->privates = array(); + $this->privates = []; parent::reset(); } @@ -49,9 +49,9 @@ public function isCompiled() public function getRemovedIds() { - return array( + return [ 'Psr\\Container\\ContainerInterface' => true, 'Symfony\\Component\\DependencyInjection\\ContainerInterface' => true, - ); + ]; } } diff --git a/Tests/Fixtures/php/services10.php b/Tests/Fixtures/php/services10.php index 31c4475ec..094f8d9d0 100644 --- a/Tests/Fixtures/php/services10.php +++ b/Tests/Fixtures/php/services10.php @@ -17,28 +17,28 @@ class ProjectServiceContainer extends Container { private $parameters; - private $targetDirs = array(); + private $targetDirs = []; /** * @internal but protected for BC on cache:clear */ - protected $privates = array(); + protected $privates = []; public function __construct() { $this->parameters = $this->getDefaultParameters(); - $this->services = $this->privates = array(); - $this->methodMap = array( + $this->services = $this->privates = []; + $this->methodMap = [ 'test' => 'getTestService', - ); + ]; - $this->aliases = array(); + $this->aliases = []; } public function reset() { - $this->privates = array(); + $this->privates = []; parent::reset(); } @@ -54,10 +54,10 @@ public function isCompiled() public function getRemovedIds() { - return array( + return [ 'Psr\\Container\\ContainerInterface' => true, 'Symfony\\Component\\DependencyInjection\\ContainerInterface' => true, - ); + ]; } /** @@ -67,7 +67,7 @@ public function getRemovedIds() */ protected function getTestService() { - return $this->services['test'] = new \stdClass(array('only dot' => '.', 'concatenation as value' => '.\'\'.', 'concatenation from the start value' => '\'\'.', '.' => 'dot as a key', '.\'\'.' => 'concatenation as a key', '\'\'.' => 'concatenation from the start key', 'optimize concatenation' => 'string1-string2', 'optimize concatenation with empty string' => 'string1string2', 'optimize concatenation from the start' => 'start', 'optimize concatenation at the end' => 'end', 'new line' => 'string with '."\n".'new line')); + return $this->services['test'] = new \stdClass(['only dot' => '.', 'concatenation as value' => '.\'\'.', 'concatenation from the start value' => '\'\'.', '.' => 'dot as a key', '.\'\'.' => 'concatenation as a key', '\'\'.' => 'concatenation from the start key', 'optimize concatenation' => 'string1-string2', 'optimize concatenation with empty string' => 'string1string2', 'optimize concatenation from the start' => 'start', 'optimize concatenation at the end' => 'end', 'new line' => 'string with '."\n".'new line']); } public function getParameter($name) @@ -109,13 +109,13 @@ public function getParameterBag() return $this->parameterBag; } - private $loadedDynamicParameters = array(); - private $dynamicParameters = array(); + private $loadedDynamicParameters = []; + private $dynamicParameters = []; /** * Computes a dynamic parameter. * - * @param string The name of the dynamic parameter to load + * @param string $name The name of the dynamic parameter to load * * @return mixed The value of the dynamic parameter * @@ -133,9 +133,9 @@ private function getDynamicParameter($name) */ protected function getDefaultParameters() { - return array( + return [ 'empty_value' => '', 'some_string' => '-', - ); + ]; } } diff --git a/Tests/Fixtures/php/services12.php b/Tests/Fixtures/php/services12.php index d4f872f94..887e5d28f 100644 --- a/Tests/Fixtures/php/services12.php +++ b/Tests/Fixtures/php/services12.php @@ -17,12 +17,12 @@ class ProjectServiceContainer extends Container { private $parameters; - private $targetDirs = array(); + private $targetDirs = []; /** * @internal but protected for BC on cache:clear */ - protected $privates = array(); + protected $privates = []; public function __construct() { @@ -32,17 +32,17 @@ public function __construct() } $this->parameters = $this->getDefaultParameters(); - $this->services = $this->privates = array(); - $this->methodMap = array( + $this->services = $this->privates = []; + $this->methodMap = [ 'test' => 'getTestService', - ); + ]; - $this->aliases = array(); + $this->aliases = []; } public function reset() { - $this->privates = array(); + $this->privates = []; parent::reset(); } @@ -58,10 +58,10 @@ public function isCompiled() public function getRemovedIds() { - return array( + return [ 'Psr\\Container\\ContainerInterface' => true, 'Symfony\\Component\\DependencyInjection\\ContainerInterface' => true, - ); + ]; } /** @@ -71,7 +71,7 @@ public function getRemovedIds() */ protected function getTestService() { - return $this->services['test'] = new \stdClass(('wiz'.$this->targetDirs[1]), array(('wiz'.$this->targetDirs[1]) => ($this->targetDirs[2].'/'))); + return $this->services['test'] = new \stdClass(('wiz'.$this->targetDirs[1]), [('wiz'.$this->targetDirs[1]) => ($this->targetDirs[2].'/')]); } public function getParameter($name) @@ -113,16 +113,16 @@ public function getParameterBag() return $this->parameterBag; } - private $loadedDynamicParameters = array( + private $loadedDynamicParameters = [ 'foo' => false, 'buz' => false, - ); - private $dynamicParameters = array(); + ]; + private $dynamicParameters = []; /** * Computes a dynamic parameter. * - * @param string The name of the dynamic parameter to load + * @param string $name The name of the dynamic parameter to load * * @return mixed The value of the dynamic parameter * @@ -147,9 +147,9 @@ private function getDynamicParameter($name) */ protected function getDefaultParameters() { - return array( + return [ 'bar' => __DIR__, 'baz' => (__DIR__.'/PhpDumperTest.php'), - ); + ]; } } diff --git a/Tests/Fixtures/php/services13.php b/Tests/Fixtures/php/services13.php index 8c90280d2..d40f55716 100644 --- a/Tests/Fixtures/php/services13.php +++ b/Tests/Fixtures/php/services13.php @@ -17,26 +17,26 @@ class ProjectServiceContainer extends Container { private $parameters; - private $targetDirs = array(); + private $targetDirs = []; /** * @internal but protected for BC on cache:clear */ - protected $privates = array(); + protected $privates = []; public function __construct() { - $this->services = $this->privates = array(); - $this->methodMap = array( + $this->services = $this->privates = []; + $this->methodMap = [ 'bar' => 'getBarService', - ); + ]; - $this->aliases = array(); + $this->aliases = []; } public function reset() { - $this->privates = array(); + $this->privates = []; parent::reset(); } @@ -52,11 +52,11 @@ public function isCompiled() public function getRemovedIds() { - return array( + return [ 'Psr\\Container\\ContainerInterface' => true, 'Symfony\\Component\\DependencyInjection\\ContainerInterface' => true, 'foo' => true, - ); + ]; } /** diff --git a/Tests/Fixtures/php/services19.php b/Tests/Fixtures/php/services19.php index 673c9d54b..3937bd0e8 100644 --- a/Tests/Fixtures/php/services19.php +++ b/Tests/Fixtures/php/services19.php @@ -17,27 +17,29 @@ class ProjectServiceContainer extends Container { private $parameters; - private $targetDirs = array(); + private $targetDirs = []; /** * @internal but protected for BC on cache:clear */ - protected $privates = array(); + protected $privates = []; public function __construct() { - $this->services = $this->privates = array(); - $this->methodMap = array( + $this->parameters = $this->getDefaultParameters(); + + $this->services = $this->privates = []; + $this->methodMap = [ 'service_from_anonymous_factory' => 'getServiceFromAnonymousFactoryService', 'service_with_method_call_and_factory' => 'getServiceWithMethodCallAndFactoryService', - ); + ]; - $this->aliases = array(); + $this->aliases = []; } public function reset() { - $this->privates = array(); + $this->privates = []; parent::reset(); } @@ -53,20 +55,20 @@ public function isCompiled() public function getRemovedIds() { - return array( + return [ 'Psr\\Container\\ContainerInterface' => true, 'Symfony\\Component\\DependencyInjection\\ContainerInterface' => true, - ); + ]; } /** * Gets the public 'service_from_anonymous_factory' shared service. * - * @return \Bar\FooClass + * @return object A %env(FOO)% instance */ protected function getServiceFromAnonymousFactoryService() { - return $this->services['service_from_anonymous_factory'] = (new \Bar\FooClass())->getInstance(); + return $this->services['service_from_anonymous_factory'] = (new ${($_ = $this->getEnv('FOO')) && false ?: "_"}())->getInstance(); } /** @@ -82,4 +84,80 @@ protected function getServiceWithMethodCallAndFactoryService() return $instance; } + + public function getParameter($name) + { + $name = (string) $name; + + if (!(isset($this->parameters[$name]) || isset($this->loadedDynamicParameters[$name]) || array_key_exists($name, $this->parameters))) { + throw new InvalidArgumentException(sprintf('The parameter "%s" must be defined.', $name)); + } + if (isset($this->loadedDynamicParameters[$name])) { + return $this->loadedDynamicParameters[$name] ? $this->dynamicParameters[$name] : $this->getDynamicParameter($name); + } + + return $this->parameters[$name]; + } + + public function hasParameter($name) + { + $name = (string) $name; + + return isset($this->parameters[$name]) || isset($this->loadedDynamicParameters[$name]) || array_key_exists($name, $this->parameters); + } + + public function setParameter($name, $value) + { + throw new LogicException('Impossible to call set() on a frozen ParameterBag.'); + } + + public function getParameterBag() + { + if (null === $this->parameterBag) { + $parameters = $this->parameters; + foreach ($this->loadedDynamicParameters as $name => $loaded) { + $parameters[$name] = $loaded ? $this->dynamicParameters[$name] : $this->getDynamicParameter($name); + } + $this->parameterBag = new FrozenParameterBag($parameters); + } + + return $this->parameterBag; + } + + private $loadedDynamicParameters = [ + 'foo' => false, + ]; + private $dynamicParameters = []; + + /** + * Computes a dynamic parameter. + * + * @param string $name The name of the dynamic parameter to load + * + * @return mixed The value of the dynamic parameter + * + * @throws InvalidArgumentException When the dynamic parameter does not exist + */ + private function getDynamicParameter($name) + { + switch ($name) { + case 'foo': $value = $this->getEnv('FOO'); break; + default: throw new InvalidArgumentException(sprintf('The dynamic parameter "%s" must be defined.', $name)); + } + $this->loadedDynamicParameters[$name] = true; + + return $this->dynamicParameters[$name] = $value; + } + + /** + * Gets the default parameters. + * + * @return array An array of the default parameters + */ + protected function getDefaultParameters() + { + return [ + 'env(FOO)' => 'Bar\\FaooClass', + ]; + } } diff --git a/Tests/Fixtures/php/services24.php b/Tests/Fixtures/php/services24.php index 090a77dd3..f210d94a2 100644 --- a/Tests/Fixtures/php/services24.php +++ b/Tests/Fixtures/php/services24.php @@ -17,26 +17,26 @@ class ProjectServiceContainer extends Container { private $parameters; - private $targetDirs = array(); + private $targetDirs = []; /** * @internal but protected for BC on cache:clear */ - protected $privates = array(); + protected $privates = []; public function __construct() { - $this->services = $this->privates = array(); - $this->methodMap = array( + $this->services = $this->privates = []; + $this->methodMap = [ 'foo' => 'getFooService', - ); + ]; - $this->aliases = array(); + $this->aliases = []; } public function reset() { - $this->privates = array(); + $this->privates = []; parent::reset(); } @@ -52,10 +52,10 @@ public function isCompiled() public function getRemovedIds() { - return array( + return [ 'Psr\\Container\\ContainerInterface' => true, 'Symfony\\Component\\DependencyInjection\\ContainerInterface' => true, - ); + ]; } /** diff --git a/Tests/Fixtures/php/services26.php b/Tests/Fixtures/php/services26.php index 942eb0eb7..dced22e52 100644 --- a/Tests/Fixtures/php/services26.php +++ b/Tests/Fixtures/php/services26.php @@ -17,12 +17,12 @@ class Symfony_DI_PhpDumper_Test_EnvParameters extends Container { private $parameters; - private $targetDirs = array(); + private $targetDirs = []; /** * @internal but protected for BC on cache:clear */ - protected $privates = array(); + protected $privates = []; public function __construct() { @@ -32,18 +32,18 @@ public function __construct() } $this->parameters = $this->getDefaultParameters(); - $this->services = $this->privates = array(); - $this->methodMap = array( + $this->services = $this->privates = []; + $this->methodMap = [ 'bar' => 'getBarService', 'test' => 'getTestService', - ); + ]; - $this->aliases = array(); + $this->aliases = []; } public function reset() { - $this->privates = array(); + $this->privates = []; parent::reset(); } @@ -59,10 +59,10 @@ public function isCompiled() public function getRemovedIds() { - return array( + return [ 'Psr\\Container\\ContainerInterface' => true, 'Symfony\\Component\\DependencyInjection\\ContainerInterface' => true, - ); + ]; } /** @@ -126,19 +126,19 @@ public function getParameterBag() return $this->parameterBag; } - private $loadedDynamicParameters = array( + private $loadedDynamicParameters = [ 'bar' => false, 'baz' => false, 'json' => false, 'db_dsn' => false, 'env(json_file)' => false, - ); - private $dynamicParameters = array(); + ]; + private $dynamicParameters = []; /** * Computes a dynamic parameter. * - * @param string The name of the dynamic parameter to load + * @param string $name The name of the dynamic parameter to load * * @return mixed The value of the dynamic parameter * @@ -166,10 +166,10 @@ private function getDynamicParameter($name) */ protected function getDefaultParameters() { - return array( + return [ 'project_dir' => '/foo/bar', 'env(FOO)' => 'foo', 'env(DB)' => 'sqlite://%project_dir%/var/data.db', - ); + ]; } } diff --git a/Tests/Fixtures/php/services33.php b/Tests/Fixtures/php/services33.php index 1c70b0ee8..ff8f80e9f 100644 --- a/Tests/Fixtures/php/services33.php +++ b/Tests/Fixtures/php/services33.php @@ -17,27 +17,27 @@ class ProjectServiceContainer extends Container { private $parameters; - private $targetDirs = array(); + private $targetDirs = []; /** * @internal but protected for BC on cache:clear */ - protected $privates = array(); + protected $privates = []; public function __construct() { - $this->services = $this->privates = array(); - $this->methodMap = array( + $this->services = $this->privates = []; + $this->methodMap = [ 'Bar\\Foo' => 'getFooService', 'Foo\\Foo' => 'getFoo2Service', - ); + ]; - $this->aliases = array(); + $this->aliases = []; } public function reset() { - $this->privates = array(); + $this->privates = []; parent::reset(); } @@ -53,10 +53,10 @@ public function isCompiled() public function getRemovedIds() { - return array( + return [ 'Psr\\Container\\ContainerInterface' => true, 'Symfony\\Component\\DependencyInjection\\ContainerInterface' => true, - ); + ]; } /** @@ -66,7 +66,7 @@ public function getRemovedIds() */ protected function getFooService() { - return $this->services['Bar\Foo'] = new \Bar\Foo(); + return $this->services['Bar\\Foo'] = new \Bar\Foo(); } /** @@ -76,6 +76,6 @@ protected function getFooService() */ protected function getFoo2Service() { - return $this->services['Foo\Foo'] = new \Foo\Foo(); + return $this->services['Foo\\Foo'] = new \Foo\Foo(); } } diff --git a/Tests/Fixtures/php/services8.php b/Tests/Fixtures/php/services8.php index eeeb37a07..7e05e0f03 100644 --- a/Tests/Fixtures/php/services8.php +++ b/Tests/Fixtures/php/services8.php @@ -17,25 +17,25 @@ class ProjectServiceContainer extends Container { private $parameters; - private $targetDirs = array(); + private $targetDirs = []; /** * @internal but protected for BC on cache:clear */ - protected $privates = array(); + protected $privates = []; public function __construct() { $this->parameters = $this->getDefaultParameters(); - $this->services = $this->privates = array(); + $this->services = $this->privates = []; - $this->aliases = array(); + $this->aliases = []; } public function reset() { - $this->privates = array(); + $this->privates = []; parent::reset(); } @@ -51,10 +51,10 @@ public function isCompiled() public function getRemovedIds() { - return array( + return [ 'Psr\\Container\\ContainerInterface' => true, 'Symfony\\Component\\DependencyInjection\\ContainerInterface' => true, - ); + ]; } public function getParameter($name) @@ -96,13 +96,13 @@ public function getParameterBag() return $this->parameterBag; } - private $loadedDynamicParameters = array(); - private $dynamicParameters = array(); + private $loadedDynamicParameters = []; + private $dynamicParameters = []; /** * Computes a dynamic parameter. * - * @param string The name of the dynamic parameter to load + * @param string $name The name of the dynamic parameter to load * * @return mixed The value of the dynamic parameter * @@ -120,12 +120,12 @@ private function getDynamicParameter($name) */ protected function getDefaultParameters() { - return array( + return [ 'foo' => 'bar', 'baz' => 'bar', 'bar' => 'foo is %foo bar', 'escape' => '@escapeme', - 'values' => array( + 'values' => [ 0 => true, 1 => false, 2 => NULL, @@ -134,9 +134,9 @@ protected function getDefaultParameters() 5 => 'true', 6 => 'false', 7 => 'null', - ), + ], 'binary' => 'ðððð', 'binary-control-char' => 'This is a Bell char ', - ); + ]; } } diff --git a/Tests/Fixtures/php/services9_as_files.txt b/Tests/Fixtures/php/services9_as_files.txt index 2b92c5838..15fdb07f6 100644 --- a/Tests/Fixtures/php/services9_as_files.txt +++ b/Tests/Fixtures/php/services9_as_files.txt @@ -2,7 +2,7 @@ Array ( [Container%s/removed-ids.php] => true, 'Symfony\\Component\\DependencyInjection\\ContainerInterface' => true, 'configurator_service' => true, @@ -14,7 +14,7 @@ return array( 'inlined' => true, 'new_factory' => true, 'tagged_iterator_foo' => true, -); +]; [Container%s/getBAR2Service.php] => services['foo.baz'] ?? $this->load('getFoo_BazService.php')); -$this->services['foo'] = $instance = \Bar\FooClass::getInstance('foo', $a, array('bar' => 'foo is bar', 'foobar' => 'bar'), true, $this); +$this->services['foo'] = $instance = \Bar\FooClass::getInstance('foo', $a, ['bar' => 'foo is bar', 'foobar' => 'bar'], true, $this); $instance->foo = 'bar'; $instance->moo = $a; -$instance->qux = array('bar' => 'foo is bar', 'foobar' => 'bar'); +$instance->qux = ['bar' => 'foo is bar', 'foobar' => 'bar']; $instance->setBar(($this->services['bar'] ?? $this->getBarService())); $instance->initialize(); sc_configure($instance); @@ -230,7 +230,6 @@ use Symfony\Component\DependencyInjection\Exception\RuntimeException; $this->services['foo_with_inline'] = $instance = new \Foo(); $a = new \Bar(); - $a->pub = 'pub'; $a->setBaz(($this->services['baz'] ?? $this->load('getBazService.php'))); @@ -348,7 +347,7 @@ use Symfony\Component\DependencyInjection\Exception\RuntimeException; return $this->services['tagged_iterator'] = new \Bar(new RewindableGenerator(function () { yield 0 => ($this->services['foo'] ?? $this->load('getFooService.php')); - yield 1 => ($this->privates['tagged_iterator_foo'] ?? $this->privates['tagged_iterator_foo'] = new \Bar()); + yield 1 => ($this->privates['tagged_iterator_foo'] ?? ($this->privates['tagged_iterator_foo'] = new \Bar())); }, 2)); [Container%s/getTaggedIteratorFooService.php] => targetDirs[0] = \dirname($containerDir); for ($i = 1; $i <= 5; ++$i) { @@ -401,14 +400,14 @@ class ProjectServiceContainer extends Container $this->containerDir = $containerDir; $this->parameters = $this->getDefaultParameters(); - $this->services = $this->privates = array(); - $this->syntheticIds = array( + $this->services = $this->privates = []; + $this->syntheticIds = [ 'request' => true, - ); - $this->methodMap = array( + ]; + $this->methodMap = [ 'bar' => 'getBarService', - ); - $this->fileMap = array( + ]; + $this->fileMap = [ 'BAR' => 'getBAR2Service.php', 'BAR2' => 'getBAR22Service.php', 'bar2' => 'getBar23Service.php', @@ -432,17 +431,17 @@ class ProjectServiceContainer extends Container 'runtime_error' => 'getRuntimeErrorService.php', 'service_from_static_method' => 'getServiceFromStaticMethodService.php', 'tagged_iterator' => 'getTaggedIteratorService.php', - ); - $this->aliases = array( + ]; + $this->aliases = [ 'alias_for_alias' => 'foo', 'alias_for_foo' => 'foo', 'decorated' => 'decorator_service_with_name', - ); + ]; } public function reset() { - $this->privates = array(); + $this->privates = []; parent::reset(); } @@ -530,13 +529,13 @@ class ProjectServiceContainer extends Container return $this->parameterBag; } - private $loadedDynamicParameters = array(); - private $dynamicParameters = array(); + private $loadedDynamicParameters = []; + private $dynamicParameters = []; /** * Computes a dynamic parameter. * - * @param string The name of the dynamic parameter to load + * @param string $name The name of the dynamic parameter to load * * @return mixed The value of the dynamic parameter * @@ -554,11 +553,11 @@ class ProjectServiceContainer extends Container */ protected function getDefaultParameters() { - return array( + return [ 'baz_class' => 'BazClass', 'foo_class' => 'Bar\\FooClass', 'foo' => 'bar', - ); + ]; } } @@ -578,10 +577,10 @@ if (!\class_exists(ProjectServiceContainer::class, false)) { \class_alias(\Container%s\ProjectServiceContainer::class, ProjectServiceContainer::class, false); } -return new \Container%s\ProjectServiceContainer(array( +return new \Container%s\ProjectServiceContainer([ 'container.build_hash' => '%s', 'container.build_id' => '%s', 'container.build_time' => %d, -), __DIR__.\DIRECTORY_SEPARATOR.'Container%s'); +], __DIR__.\DIRECTORY_SEPARATOR.'Container%s'); ) diff --git a/Tests/Fixtures/php/services9_compiled.php b/Tests/Fixtures/php/services9_compiled.php index 6231dab53..4a0b82f96 100644 --- a/Tests/Fixtures/php/services9_compiled.php +++ b/Tests/Fixtures/php/services9_compiled.php @@ -17,22 +17,22 @@ class ProjectServiceContainer extends Container { private $parameters; - private $targetDirs = array(); + private $targetDirs = []; /** * @internal but protected for BC on cache:clear */ - protected $privates = array(); + protected $privates = []; public function __construct() { $this->parameters = $this->getDefaultParameters(); - $this->services = $this->privates = array(); - $this->syntheticIds = array( + $this->services = $this->privates = []; + $this->syntheticIds = [ 'request' => true, - ); - $this->methodMap = array( + ]; + $this->methodMap = [ 'BAR' => 'getBARService', 'BAR2' => 'getBAR2Service', 'bar' => 'getBar3Service', @@ -56,17 +56,17 @@ public function __construct() 'runtime_error' => 'getRuntimeErrorService', 'service_from_static_method' => 'getServiceFromStaticMethodService', 'tagged_iterator' => 'getTaggedIteratorService', - ); - $this->aliases = array( + ]; + $this->aliases = [ 'alias_for_alias' => 'foo', 'alias_for_foo' => 'foo', 'decorated' => 'decorator_service_with_name', - ); + ]; } public function reset() { - $this->privates = array(); + $this->privates = []; parent::reset(); } @@ -82,7 +82,7 @@ public function isCompiled() public function getRemovedIds() { - return array( + return [ 'Psr\\Container\\ContainerInterface' => true, 'Symfony\\Component\\DependencyInjection\\ContainerInterface' => true, 'configurator_service' => true, @@ -94,7 +94,7 @@ public function getRemovedIds() 'inlined' => true, 'new_factory' => true, 'tagged_iterator_foo' => true, - ); + ]; } /** @@ -255,11 +255,11 @@ protected function getFooService() { $a = ($this->services['foo.baz'] ?? $this->getFoo_BazService()); - $this->services['foo'] = $instance = \Bar\FooClass::getInstance('foo', $a, array('bar' => 'foo is bar', 'foobar' => 'bar'), true, $this); + $this->services['foo'] = $instance = \Bar\FooClass::getInstance('foo', $a, ['bar' => 'foo is bar', 'foobar' => 'bar'], true, $this); $instance->foo = 'bar'; $instance->moo = $a; - $instance->qux = array('bar' => 'foo is bar', 'foobar' => 'bar'); + $instance->qux = ['bar' => 'foo is bar', 'foobar' => 'bar']; $instance->setBar(($this->services['bar'] ?? $this->getBar3Service())); $instance->initialize(); sc_configure($instance); @@ -301,7 +301,6 @@ protected function getFooWithInlineService() $this->services['foo_with_inline'] = $instance = new \Foo(); $a = new \Bar(); - $a->pub = 'pub'; $a->setBaz(($this->services['baz'] ?? $this->getBazService())); @@ -403,7 +402,7 @@ protected function getTaggedIteratorService() { return $this->services['tagged_iterator'] = new \Bar(new RewindableGenerator(function () { yield 0 => ($this->services['foo'] ?? $this->getFooService()); - yield 1 => ($this->privates['tagged_iterator_foo'] ?? $this->privates['tagged_iterator_foo'] = new \Bar()); + yield 1 => ($this->privates['tagged_iterator_foo'] ?? ($this->privates['tagged_iterator_foo'] = new \Bar())); }, 2)); } @@ -470,13 +469,13 @@ public function getParameterBag() return $this->parameterBag; } - private $loadedDynamicParameters = array(); - private $dynamicParameters = array(); + private $loadedDynamicParameters = []; + private $dynamicParameters = []; /** * Computes a dynamic parameter. * - * @param string The name of the dynamic parameter to load + * @param string $name The name of the dynamic parameter to load * * @return mixed The value of the dynamic parameter * @@ -494,10 +493,10 @@ private function getDynamicParameter($name) */ protected function getDefaultParameters() { - return array( + return [ 'baz_class' => 'BazClass', 'foo_class' => 'Bar\\FooClass', 'foo' => 'bar', - ); + ]; } } diff --git a/Tests/Fixtures/php/services_adawson.php b/Tests/Fixtures/php/services_adawson.php new file mode 100644 index 000000000..7c27f7fcc --- /dev/null +++ b/Tests/Fixtures/php/services_adawson.php @@ -0,0 +1,119 @@ +services = $this->privates = []; + $this->methodMap = [ + 'App\\Bus' => 'getBusService', + 'App\\Db' => 'getDbService', + ]; + + $this->aliases = []; + } + + public function reset() + { + $this->privates = []; + parent::reset(); + } + + public function compile() + { + throw new LogicException('You cannot compile a dumped container that was already compiled.'); + } + + public function isCompiled() + { + return true; + } + + public function getRemovedIds() + { + return [ + 'App\\Handler1' => true, + 'App\\Handler2' => true, + 'App\\Processor' => true, + 'App\\Registry' => true, + 'App\\Schema' => true, + 'Psr\\Container\\ContainerInterface' => true, + 'Symfony\\Component\\DependencyInjection\\ContainerInterface' => true, + ]; + } + + /** + * Gets the public 'App\Bus' shared service. + * + * @return \App\Bus + */ + protected function getBusService() + { + $a = ($this->services['App\\Db'] ?? $this->getDbService()); + + $this->services['App\\Bus'] = $instance = new \App\Bus($a); + + $b = ($this->privates['App\\Schema'] ?? $this->getSchemaService()); + $c = new \App\Registry(); + $c->processor = [0 => $a, 1 => $instance]; + + $d = new \App\Processor($c, $a); + + $instance->handler1 = new \App\Handler1($a, $b, $d); + $instance->handler2 = new \App\Handler2($a, $b, $d); + + return $instance; + } + + /** + * Gets the public 'App\Db' shared service. + * + * @return \App\Db + */ + protected function getDbService() + { + $this->services['App\\Db'] = $instance = new \App\Db(); + + $instance->schema = ($this->privates['App\\Schema'] ?? $this->getSchemaService()); + + return $instance; + } + + /** + * Gets the private 'App\Schema' shared service. + * + * @return \App\Schema + */ + protected function getSchemaService() + { + $a = ($this->services['App\\Db'] ?? $this->getDbService()); + + if (isset($this->privates['App\\Schema'])) { + return $this->privates['App\\Schema']; + } + + return $this->privates['App\\Schema'] = new \App\Schema($a); + } +} diff --git a/Tests/Fixtures/php/services_almost_circular_private.php b/Tests/Fixtures/php/services_almost_circular_private.php index 4de6bfc23..84b917f5e 100644 --- a/Tests/Fixtures/php/services_almost_circular_private.php +++ b/Tests/Fixtures/php/services_almost_circular_private.php @@ -17,31 +17,40 @@ class Symfony_DI_PhpDumper_Test_Almost_Circular_Private extends Container { private $parameters; - private $targetDirs = array(); + private $targetDirs = []; /** * @internal but protected for BC on cache:clear */ - protected $privates = array(); + protected $privates = []; public function __construct() { - $this->services = $this->privates = array(); - $this->methodMap = array( + $this->services = $this->privates = []; + $this->methodMap = [ 'bar2' => 'getBar2Service', 'bar3' => 'getBar3Service', + 'baz6' => 'getBaz6Service', + 'connection' => 'getConnectionService', + 'connection2' => 'getConnection2Service', 'foo' => 'getFooService', 'foo2' => 'getFoo2Service', 'foo5' => 'getFoo5Service', + 'foo6' => 'getFoo6Service', 'foobar4' => 'getFoobar4Service', - ); - - $this->aliases = array(); + 'logger' => 'getLoggerService', + 'manager' => 'getManagerService', + 'manager2' => 'getManager2Service', + 'root' => 'getRootService', + 'subscriber' => 'getSubscriberService', + ]; + + $this->aliases = []; } public function reset() { - $this->privates = array(); + $this->privates = []; parent::reset(); } @@ -57,16 +66,29 @@ public function isCompiled() public function getRemovedIds() { - return array( + return [ 'Psr\\Container\\ContainerInterface' => true, 'Symfony\\Component\\DependencyInjection\\ContainerInterface' => true, 'bar' => true, 'bar5' => true, + 'bar6' => true, + 'config' => true, + 'config2' => true, + 'dispatcher' => true, + 'dispatcher2' => true, 'foo4' => true, 'foobar' => true, 'foobar2' => true, 'foobar3' => true, - ); + 'level2' => true, + 'level3' => true, + 'level4' => true, + 'level5' => true, + 'level6' => true, + 'logger2' => true, + 'multiuse1' => true, + 'subscriber2' => true, + ]; } /** @@ -99,6 +121,66 @@ protected function getBar3Service() return $instance; } + /** + * Gets the public 'baz6' shared service. + * + * @return \stdClass + */ + protected function getBaz6Service() + { + $this->services['baz6'] = $instance = new \stdClass(); + + $instance->bar6 = ($this->privates['bar6'] ?? $this->getBar6Service()); + + return $instance; + } + + /** + * Gets the public 'connection' shared service. + * + * @return \stdClass + */ + protected function getConnectionService() + { + $a = new \stdClass(); + + $b = new \stdClass(); + + $this->services['connection'] = $instance = new \stdClass($a, $b); + + $b->logger = ($this->services['logger'] ?? $this->getLoggerService()); + + $a->subscriber = ($this->services['subscriber'] ?? $this->getSubscriberService()); + + return $instance; + } + + /** + * Gets the public 'connection2' shared service. + * + * @return \stdClass + */ + protected function getConnection2Service() + { + $a = new \stdClass(); + + $b = new \stdClass(); + + $this->services['connection2'] = $instance = new \stdClass($a, $b); + + $c = new \stdClass($instance); + + $d = ($this->services['manager2'] ?? $this->getManager2Service()); + + $c->handler2 = new \stdClass($d); + + $b->logger2 = $c; + + $a->subscriber2 = new \stdClass($d); + + return $instance; + } + /** * Gets the public 'foo' shared service. * @@ -140,8 +222,7 @@ protected function getFoo5Service() { $this->services['foo5'] = $instance = new \stdClass(); - $a = new \stdClass(($this->services['foo5'] ?? $this->getFoo5Service())); - + $a = new \stdClass($instance); $a->foo = $instance; $instance->bar = $a; @@ -149,6 +230,20 @@ protected function getFoo5Service() return $instance; } + /** + * Gets the public 'foo6' shared service. + * + * @return \stdClass + */ + protected function getFoo6Service() + { + $this->services['foo6'] = $instance = new \stdClass(); + + $instance->bar6 = ($this->privates['bar6'] ?? $this->getBar6Service()); + + return $instance; + } + /** * Gets the public 'foobar4' shared service. * @@ -164,4 +259,120 @@ protected function getFoobar4Service() return $instance; } + + /** + * Gets the public 'logger' shared service. + * + * @return \stdClass + */ + protected function getLoggerService() + { + $a = ($this->services['connection'] ?? $this->getConnectionService()); + + if (isset($this->services['logger'])) { + return $this->services['logger']; + } + + $this->services['logger'] = $instance = new \stdClass($a); + + $instance->handler = new \stdClass(($this->services['manager'] ?? $this->getManagerService())); + + return $instance; + } + + /** + * Gets the public 'manager' shared service. + * + * @return \stdClass + */ + protected function getManagerService() + { + $a = ($this->services['connection'] ?? $this->getConnectionService()); + + if (isset($this->services['manager'])) { + return $this->services['manager']; + } + + return $this->services['manager'] = new \stdClass($a); + } + + /** + * Gets the public 'manager2' shared service. + * + * @return \stdClass + */ + protected function getManager2Service() + { + $a = ($this->services['connection2'] ?? $this->getConnection2Service()); + + if (isset($this->services['manager2'])) { + return $this->services['manager2']; + } + + return $this->services['manager2'] = new \stdClass($a); + } + + /** + * Gets the public 'root' shared service. + * + * @return \stdClass + */ + protected function getRootService() + { + $a = new \Symfony\Component\DependencyInjection\Tests\Fixtures\FooForCircularWithAddCalls(); + + $b = new \stdClass(); + + $a->call(new \stdClass(new \stdClass($b, ($this->privates['level5'] ?? $this->getLevel5Service())))); + + return $this->services['root'] = new \stdClass($a, $b); + } + + /** + * Gets the public 'subscriber' shared service. + * + * @return \stdClass + */ + protected function getSubscriberService() + { + $a = ($this->services['manager'] ?? $this->getManagerService()); + + if (isset($this->services['subscriber'])) { + return $this->services['subscriber']; + } + + return $this->services['subscriber'] = new \stdClass($a); + } + + /** + * Gets the private 'bar6' shared service. + * + * @return \stdClass + */ + protected function getBar6Service() + { + $a = ($this->services['foo6'] ?? $this->getFoo6Service()); + + if (isset($this->privates['bar6'])) { + return $this->privates['bar6']; + } + + return $this->privates['bar6'] = new \stdClass($a); + } + + /** + * Gets the private 'level5' shared service. + * + * @return \stdClass + */ + protected function getLevel5Service() + { + $a = new \Symfony\Component\DependencyInjection\Tests\Fixtures\FooForCircularWithAddCalls(); + + $this->privates['level5'] = $instance = new \stdClass($a); + + $a->call($instance); + + return $instance; + } } diff --git a/Tests/Fixtures/php/services_almost_circular_public.php b/Tests/Fixtures/php/services_almost_circular_public.php index 79a0c11cc..7f4daec86 100644 --- a/Tests/Fixtures/php/services_almost_circular_public.php +++ b/Tests/Fixtures/php/services_almost_circular_public.php @@ -17,36 +17,47 @@ class Symfony_DI_PhpDumper_Test_Almost_Circular_Public extends Container { private $parameters; - private $targetDirs = array(); + private $targetDirs = []; /** * @internal but protected for BC on cache:clear */ - protected $privates = array(); + protected $privates = []; public function __construct() { - $this->services = $this->privates = array(); - $this->methodMap = array( + $this->services = $this->privates = []; + $this->methodMap = [ 'bar' => 'getBarService', 'bar3' => 'getBar3Service', 'bar5' => 'getBar5Service', + 'baz6' => 'getBaz6Service', + 'connection' => 'getConnectionService', + 'connection2' => 'getConnection2Service', + 'dispatcher' => 'getDispatcherService', + 'dispatcher2' => 'getDispatcher2Service', 'foo' => 'getFooService', 'foo2' => 'getFoo2Service', 'foo4' => 'getFoo4Service', 'foo5' => 'getFoo5Service', + 'foo6' => 'getFoo6Service', 'foobar' => 'getFoobarService', 'foobar2' => 'getFoobar2Service', 'foobar3' => 'getFoobar3Service', 'foobar4' => 'getFoobar4Service', - ); - - $this->aliases = array(); + 'logger' => 'getLoggerService', + 'manager' => 'getManagerService', + 'manager2' => 'getManager2Service', + 'root' => 'getRootService', + 'subscriber' => 'getSubscriberService', + ]; + + $this->aliases = []; } public function reset() { - $this->privates = array(); + $this->privates = []; parent::reset(); } @@ -62,11 +73,22 @@ public function isCompiled() public function getRemovedIds() { - return array( + return [ 'Psr\\Container\\ContainerInterface' => true, 'Symfony\\Component\\DependencyInjection\\ContainerInterface' => true, 'bar2' => true, - ); + 'bar6' => true, + 'config' => true, + 'config2' => true, + 'level2' => true, + 'level3' => true, + 'level4' => true, + 'level5' => true, + 'level6' => true, + 'logger2' => true, + 'multiuse1' => true, + 'subscriber2' => true, + ]; } /** @@ -92,7 +114,7 @@ protected function getBar3Service() { $this->services['bar3'] = $instance = new \BarCircular(); - $a = ($this->services['foobar3'] ?? $this->services['foobar3'] = new \FoobarCircular()); + $a = ($this->services['foobar3'] ?? ($this->services['foobar3'] = new \FoobarCircular())); $instance->addFoobar($a, $a); @@ -119,6 +141,93 @@ protected function getBar5Service() return $instance; } + /** + * Gets the public 'baz6' shared service. + * + * @return \stdClass + */ + protected function getBaz6Service() + { + $this->services['baz6'] = $instance = new \stdClass(); + + $instance->bar6 = ($this->privates['bar6'] ?? $this->getBar6Service()); + + return $instance; + } + + /** + * Gets the public 'connection' shared service. + * + * @return \stdClass + */ + protected function getConnectionService() + { + $a = ($this->services['dispatcher'] ?? $this->getDispatcherService()); + + if (isset($this->services['connection'])) { + return $this->services['connection']; + } + $b = new \stdClass(); + + $this->services['connection'] = $instance = new \stdClass($a, $b); + + $b->logger = ($this->services['logger'] ?? $this->getLoggerService()); + + return $instance; + } + + /** + * Gets the public 'connection2' shared service. + * + * @return \stdClass + */ + protected function getConnection2Service() + { + $a = ($this->services['dispatcher2'] ?? $this->getDispatcher2Service()); + + if (isset($this->services['connection2'])) { + return $this->services['connection2']; + } + $b = new \stdClass(); + + $this->services['connection2'] = $instance = new \stdClass($a, $b); + + $c = new \stdClass($instance); + $c->handler2 = new \stdClass(($this->services['manager2'] ?? $this->getManager2Service())); + + $b->logger2 = $c; + + return $instance; + } + + /** + * Gets the public 'dispatcher' shared service. + * + * @return \stdClass + */ + protected function getDispatcherService($lazyLoad = true) + { + $this->services['dispatcher'] = $instance = new \stdClass(); + + $instance->subscriber = ($this->services['subscriber'] ?? $this->getSubscriberService()); + + return $instance; + } + + /** + * Gets the public 'dispatcher2' shared service. + * + * @return \stdClass + */ + protected function getDispatcher2Service($lazyLoad = true) + { + $this->services['dispatcher2'] = $instance = new \stdClass(); + + $instance->subscriber2 = new \stdClass(($this->services['manager2'] ?? $this->getManager2Service())); + + return $instance; + } + /** * Gets the public 'foo' shared service. * @@ -179,6 +288,20 @@ protected function getFoo5Service() return $instance; } + /** + * Gets the public 'foo6' shared service. + * + * @return \stdClass + */ + protected function getFoo6Service() + { + $this->services['foo6'] = $instance = new \stdClass(); + + $instance->bar6 = ($this->privates['bar6'] ?? $this->getBar6Service()); + + return $instance; + } + /** * Gets the public 'foobar' shared service. * @@ -236,4 +359,120 @@ protected function getFoobar4Service() return $instance; } + + /** + * Gets the public 'logger' shared service. + * + * @return \stdClass + */ + protected function getLoggerService() + { + $a = ($this->services['connection'] ?? $this->getConnectionService()); + + if (isset($this->services['logger'])) { + return $this->services['logger']; + } + + $this->services['logger'] = $instance = new \stdClass($a); + + $instance->handler = new \stdClass(($this->services['manager'] ?? $this->getManagerService())); + + return $instance; + } + + /** + * Gets the public 'manager' shared service. + * + * @return \stdClass + */ + protected function getManagerService() + { + $a = ($this->services['connection'] ?? $this->getConnectionService()); + + if (isset($this->services['manager'])) { + return $this->services['manager']; + } + + return $this->services['manager'] = new \stdClass($a); + } + + /** + * Gets the public 'manager2' shared service. + * + * @return \stdClass + */ + protected function getManager2Service() + { + $a = ($this->services['connection2'] ?? $this->getConnection2Service()); + + if (isset($this->services['manager2'])) { + return $this->services['manager2']; + } + + return $this->services['manager2'] = new \stdClass($a); + } + + /** + * Gets the public 'root' shared service. + * + * @return \stdClass + */ + protected function getRootService() + { + $a = new \Symfony\Component\DependencyInjection\Tests\Fixtures\FooForCircularWithAddCalls(); + + $b = new \stdClass(); + + $a->call(new \stdClass(new \stdClass($b, ($this->privates['level5'] ?? $this->getLevel5Service())))); + + return $this->services['root'] = new \stdClass($a, $b); + } + + /** + * Gets the public 'subscriber' shared service. + * + * @return \stdClass + */ + protected function getSubscriberService() + { + $a = ($this->services['manager'] ?? $this->getManagerService()); + + if (isset($this->services['subscriber'])) { + return $this->services['subscriber']; + } + + return $this->services['subscriber'] = new \stdClass($a); + } + + /** + * Gets the private 'bar6' shared service. + * + * @return \stdClass + */ + protected function getBar6Service() + { + $a = ($this->services['foo6'] ?? $this->getFoo6Service()); + + if (isset($this->privates['bar6'])) { + return $this->privates['bar6']; + } + + return $this->privates['bar6'] = new \stdClass($a); + } + + /** + * Gets the private 'level5' shared service. + * + * @return \stdClass + */ + protected function getLevel5Service() + { + $a = new \Symfony\Component\DependencyInjection\Tests\Fixtures\FooForCircularWithAddCalls(); + + $this->privates['level5'] = $instance = new \stdClass($a); + + $a->call($instance); + + return $instance; + } } diff --git a/Tests/Fixtures/php/services_array_params.php b/Tests/Fixtures/php/services_array_params.php index d72e6fd00..4b4f00ae1 100644 --- a/Tests/Fixtures/php/services_array_params.php +++ b/Tests/Fixtures/php/services_array_params.php @@ -17,12 +17,12 @@ class ProjectServiceContainer extends Container { private $parameters; - private $targetDirs = array(); + private $targetDirs = []; /** * @internal but protected for BC on cache:clear */ - protected $privates = array(); + protected $privates = []; public function __construct() { @@ -32,17 +32,17 @@ public function __construct() } $this->parameters = $this->getDefaultParameters(); - $this->services = $this->privates = array(); - $this->methodMap = array( + $this->services = $this->privates = []; + $this->methodMap = [ 'bar' => 'getBarService', - ); + ]; - $this->aliases = array(); + $this->aliases = []; } public function reset() { - $this->privates = array(); + $this->privates = []; parent::reset(); } @@ -58,10 +58,10 @@ public function isCompiled() public function getRemovedIds() { - return array( + return [ 'Psr\\Container\\ContainerInterface' => true, 'Symfony\\Component\\DependencyInjection\\ContainerInterface' => true, - ); + ]; } /** @@ -117,15 +117,15 @@ public function getParameterBag() return $this->parameterBag; } - private $loadedDynamicParameters = array( + private $loadedDynamicParameters = [ 'array_2' => false, - ); - private $dynamicParameters = array(); + ]; + private $dynamicParameters = []; /** * Computes a dynamic parameter. * - * @param string The name of the dynamic parameter to load + * @param string $name The name of the dynamic parameter to load * * @return mixed The value of the dynamic parameter * @@ -134,9 +134,9 @@ public function getParameterBag() private function getDynamicParameter($name) { switch ($name) { - case 'array_2': $value = array( + case 'array_2': $value = [ 0 => ($this->targetDirs[2].'/Dumper'), - ); break; + ]; break; default: throw new InvalidArgumentException(sprintf('The dynamic parameter "%s" must be defined.', $name)); } $this->loadedDynamicParameters[$name] = true; @@ -151,10 +151,10 @@ private function getDynamicParameter($name) */ protected function getDefaultParameters() { - return array( - 'array_1' => array( + return [ + 'array_1' => [ 0 => 123, - ), - ); + ], + ]; } } diff --git a/Tests/Fixtures/php/services_base64_env.php b/Tests/Fixtures/php/services_base64_env.php index 8af802f70..c109c1a36 100644 --- a/Tests/Fixtures/php/services_base64_env.php +++ b/Tests/Fixtures/php/services_base64_env.php @@ -17,25 +17,25 @@ class Symfony_DI_PhpDumper_Test_Base64Parameters extends Container { private $parameters; - private $targetDirs = array(); + private $targetDirs = []; /** * @internal but protected for BC on cache:clear */ - protected $privates = array(); + protected $privates = []; public function __construct() { $this->parameters = $this->getDefaultParameters(); - $this->services = $this->privates = array(); + $this->services = $this->privates = []; - $this->aliases = array(); + $this->aliases = []; } public function reset() { - $this->privates = array(); + $this->privates = []; parent::reset(); } @@ -51,10 +51,10 @@ public function isCompiled() public function getRemovedIds() { - return array( + return [ 'Psr\\Container\\ContainerInterface' => true, 'Symfony\\Component\\DependencyInjection\\ContainerInterface' => true, - ); + ]; } public function getParameter($name) @@ -96,15 +96,15 @@ public function getParameterBag() return $this->parameterBag; } - private $loadedDynamicParameters = array( + private $loadedDynamicParameters = [ 'hello' => false, - ); - private $dynamicParameters = array(); + ]; + private $dynamicParameters = []; /** * Computes a dynamic parameter. * - * @param string The name of the dynamic parameter to load + * @param string $name The name of the dynamic parameter to load * * @return mixed The value of the dynamic parameter * @@ -128,8 +128,8 @@ private function getDynamicParameter($name) */ protected function getDefaultParameters() { - return array( + return [ 'env(foo)' => 'd29ybGQ=', - ); + ]; } } diff --git a/Tests/Fixtures/php/services_csv_env.php b/Tests/Fixtures/php/services_csv_env.php index 99215f5fd..9a4c8a1d6 100644 --- a/Tests/Fixtures/php/services_csv_env.php +++ b/Tests/Fixtures/php/services_csv_env.php @@ -17,25 +17,25 @@ class Symfony_DI_PhpDumper_Test_CsvParameters extends Container { private $parameters; - private $targetDirs = array(); + private $targetDirs = []; /** * @internal but protected for BC on cache:clear */ - protected $privates = array(); + protected $privates = []; public function __construct() { $this->parameters = $this->getDefaultParameters(); - $this->services = $this->privates = array(); + $this->services = $this->privates = []; - $this->aliases = array(); + $this->aliases = []; } public function reset() { - $this->privates = array(); + $this->privates = []; parent::reset(); } @@ -51,10 +51,10 @@ public function isCompiled() public function getRemovedIds() { - return array( + return [ 'Psr\\Container\\ContainerInterface' => true, 'Symfony\\Component\\DependencyInjection\\ContainerInterface' => true, - ); + ]; } public function getParameter($name) @@ -96,15 +96,15 @@ public function getParameterBag() return $this->parameterBag; } - private $loadedDynamicParameters = array( + private $loadedDynamicParameters = [ 'hello' => false, - ); - private $dynamicParameters = array(); + ]; + private $dynamicParameters = []; /** * Computes a dynamic parameter. * - * @param string The name of the dynamic parameter to load + * @param string $name The name of the dynamic parameter to load * * @return mixed The value of the dynamic parameter * @@ -128,8 +128,8 @@ private function getDynamicParameter($name) */ protected function getDefaultParameters() { - return array( + return [ 'env(foo)' => 'foo,bar', - ); + ]; } } diff --git a/Tests/Fixtures/php/services_dedup_lazy_proxy.php b/Tests/Fixtures/php/services_dedup_lazy_proxy.php index 1653e6ef7..a1101950c 100644 --- a/Tests/Fixtures/php/services_dedup_lazy_proxy.php +++ b/Tests/Fixtures/php/services_dedup_lazy_proxy.php @@ -17,27 +17,27 @@ class ProjectServiceContainer extends Container { private $parameters; - private $targetDirs = array(); + private $targetDirs = []; /** * @internal but protected for BC on cache:clear */ - protected $privates = array(); + protected $privates = []; public function __construct() { - $this->services = $this->privates = array(); - $this->methodMap = array( + $this->services = $this->privates = []; + $this->methodMap = [ 'bar' => 'getBarService', 'foo' => 'getFooService', - ); + ]; - $this->aliases = array(); + $this->aliases = []; } public function reset() { - $this->privates = array(); + $this->privates = []; parent::reset(); } @@ -53,10 +53,10 @@ public function isCompiled() public function getRemovedIds() { - return array( + return [ 'Psr\\Container\\ContainerInterface' => true, 'Symfony\\Component\\DependencyInjection\\ContainerInterface' => true, - ); + ]; } protected function createProxy($class, \Closure $factory) diff --git a/Tests/Fixtures/php/services_deep_graph.php b/Tests/Fixtures/php/services_deep_graph.php new file mode 100644 index 000000000..e47d9ffe2 --- /dev/null +++ b/Tests/Fixtures/php/services_deep_graph.php @@ -0,0 +1,97 @@ +services = $this->privates = []; + $this->methodMap = [ + 'bar' => 'getBarService', + 'foo' => 'getFooService', + ]; + + $this->aliases = []; + } + + public function reset() + { + $this->privates = []; + parent::reset(); + } + + public function compile() + { + throw new LogicException('You cannot compile a dumped container that was already compiled.'); + } + + public function isCompiled() + { + return true; + } + + public function getRemovedIds() + { + return [ + 'Psr\\Container\\ContainerInterface' => true, + 'Symfony\\Component\\DependencyInjection\\ContainerInterface' => true, + ]; + } + + /** + * Gets the public 'bar' shared service. + * + * @return \stdClass + */ + protected function getBarService() + { + $this->services['bar'] = $instance = new \stdClass(); + + $instance->p5 = new \stdClass(($this->services['foo'] ?? $this->getFooService())); + + return $instance; + } + + /** + * Gets the public 'foo' shared service. + * + * @return \Symfony\Component\DependencyInjection\Tests\Dumper\FooForDeepGraph + */ + protected function getFooService() + { + $a = ($this->services['bar'] ?? $this->getBarService()); + + if (isset($this->services['foo'])) { + return $this->services['foo']; + } + $b = new \stdClass(); + + $c = new \stdClass(); + $c->p3 = new \stdClass(); + + $b->p2 = $c; + + return $this->services['foo'] = new \Symfony\Component\DependencyInjection\Tests\Dumper\FooForDeepGraph($a, $b); + } +} diff --git a/Tests/Fixtures/php/services_env_in_id.php b/Tests/Fixtures/php/services_env_in_id.php index 4100dcdd2..93670a662 100644 --- a/Tests/Fixtures/php/services_env_in_id.php +++ b/Tests/Fixtures/php/services_env_in_id.php @@ -17,29 +17,29 @@ class ProjectServiceContainer extends Container { private $parameters; - private $targetDirs = array(); + private $targetDirs = []; /** * @internal but protected for BC on cache:clear */ - protected $privates = array(); + protected $privates = []; public function __construct() { $this->parameters = $this->getDefaultParameters(); - $this->services = $this->privates = array(); - $this->methodMap = array( + $this->services = $this->privates = []; + $this->methodMap = [ 'bar' => 'getBarService', 'foo' => 'getFooService', - ); + ]; - $this->aliases = array(); + $this->aliases = []; } public function reset() { - $this->privates = array(); + $this->privates = []; parent::reset(); } @@ -55,12 +55,12 @@ public function isCompiled() public function getRemovedIds() { - return array( + return [ 'Psr\\Container\\ContainerInterface' => true, 'Symfony\\Component\\DependencyInjection\\ContainerInterface' => true, 'bar_%env(BAR)%' => true, 'baz_%env(BAR)%' => true, - ); + ]; } /** @@ -70,7 +70,7 @@ public function getRemovedIds() */ protected function getBarService() { - return $this->services['bar'] = new \stdClass(($this->privates['bar_%env(BAR)%'] ?? $this->privates['bar_%env(BAR)%'] = new \stdClass())); + return $this->services['bar'] = new \stdClass(($this->privates['bar_%env(BAR)%'] ?? ($this->privates['bar_%env(BAR)%'] = new \stdClass()))); } /** @@ -80,7 +80,7 @@ protected function getBarService() */ protected function getFooService() { - return $this->services['foo'] = new \stdClass(($this->privates['bar_%env(BAR)%'] ?? $this->privates['bar_%env(BAR)%'] = new \stdClass()), array('baz_'.$this->getEnv('string:BAR') => new \stdClass())); + return $this->services['foo'] = new \stdClass(($this->privates['bar_%env(BAR)%'] ?? ($this->privates['bar_%env(BAR)%'] = new \stdClass())), ['baz_'.$this->getEnv('string:BAR') => new \stdClass()]); } public function getParameter($name) @@ -122,13 +122,13 @@ public function getParameterBag() return $this->parameterBag; } - private $loadedDynamicParameters = array(); - private $dynamicParameters = array(); + private $loadedDynamicParameters = []; + private $dynamicParameters = []; /** * Computes a dynamic parameter. * - * @param string The name of the dynamic parameter to load + * @param string $name The name of the dynamic parameter to load * * @return mixed The value of the dynamic parameter * @@ -146,8 +146,8 @@ private function getDynamicParameter($name) */ protected function getDefaultParameters() { - return array( + return [ 'env(BAR)' => 'bar', - ); + ]; } } diff --git a/Tests/Fixtures/php/services_errored_definition.php b/Tests/Fixtures/php/services_errored_definition.php index 34a38dfc4..7fdcdc903 100644 --- a/Tests/Fixtures/php/services_errored_definition.php +++ b/Tests/Fixtures/php/services_errored_definition.php @@ -17,22 +17,22 @@ class Symfony_DI_PhpDumper_Errored_Definition extends Container { private $parameters; - private $targetDirs = array(); + private $targetDirs = []; /** * @internal but protected for BC on cache:clear */ - protected $privates = array(); + protected $privates = []; public function __construct() { $this->parameters = $this->getDefaultParameters(); - $this->services = $this->privates = array(); - $this->syntheticIds = array( + $this->services = $this->privates = []; + $this->syntheticIds = [ 'request' => true, - ); - $this->methodMap = array( + ]; + $this->methodMap = [ 'BAR' => 'getBARService', 'BAR2' => 'getBAR2Service', 'bar' => 'getBar3Service', @@ -56,17 +56,17 @@ public function __construct() 'runtime_error' => 'getRuntimeErrorService', 'service_from_static_method' => 'getServiceFromStaticMethodService', 'tagged_iterator' => 'getTaggedIteratorService', - ); - $this->aliases = array( + ]; + $this->aliases = [ 'alias_for_alias' => 'foo', 'alias_for_foo' => 'foo', 'decorated' => 'decorator_service_with_name', - ); + ]; } public function reset() { - $this->privates = array(); + $this->privates = []; parent::reset(); } @@ -82,7 +82,7 @@ public function isCompiled() public function getRemovedIds() { - return array( + return [ 'Psr\\Container\\ContainerInterface' => true, 'Symfony\\Component\\DependencyInjection\\ContainerInterface' => true, 'configurator_service' => true, @@ -94,7 +94,7 @@ public function getRemovedIds() 'inlined' => true, 'new_factory' => true, 'tagged_iterator_foo' => true, - ); + ]; } /** @@ -255,11 +255,11 @@ protected function getFooService() { $a = ($this->services['foo.baz'] ?? $this->getFoo_BazService()); - $this->services['foo'] = $instance = \Bar\FooClass::getInstance('foo', $a, array('bar' => 'foo is bar', 'foobar' => 'bar'), true, $this); + $this->services['foo'] = $instance = \Bar\FooClass::getInstance('foo', $a, ['bar' => 'foo is bar', 'foobar' => 'bar'], true, $this); $instance->foo = 'bar'; $instance->moo = $a; - $instance->qux = array('bar' => 'foo is bar', 'foobar' => 'bar'); + $instance->qux = ['bar' => 'foo is bar', 'foobar' => 'bar']; $instance->setBar(($this->services['bar'] ?? $this->getBar3Service())); $instance->initialize(); sc_configure($instance); @@ -301,7 +301,6 @@ protected function getFooWithInlineService() $this->services['foo_with_inline'] = $instance = new \Foo(); $a = new \Bar(); - $a->pub = 'pub'; $a->setBaz(($this->services['baz'] ?? $this->getBazService())); @@ -403,7 +402,7 @@ protected function getTaggedIteratorService() { return $this->services['tagged_iterator'] = new \Bar(new RewindableGenerator(function () { yield 0 => ($this->services['foo'] ?? $this->getFooService()); - yield 1 => ($this->privates['tagged_iterator_foo'] ?? $this->privates['tagged_iterator_foo'] = new \Bar()); + yield 1 => ($this->privates['tagged_iterator_foo'] ?? ($this->privates['tagged_iterator_foo'] = new \Bar())); }, 2)); } @@ -470,13 +469,13 @@ public function getParameterBag() return $this->parameterBag; } - private $loadedDynamicParameters = array(); - private $dynamicParameters = array(); + private $loadedDynamicParameters = []; + private $dynamicParameters = []; /** * Computes a dynamic parameter. * - * @param string The name of the dynamic parameter to load + * @param string $name The name of the dynamic parameter to load * * @return mixed The value of the dynamic parameter * @@ -494,11 +493,11 @@ private function getDynamicParameter($name) */ protected function getDefaultParameters() { - return array( + return [ 'baz_class' => 'BazClass', 'foo_class' => 'Bar\\FooClass', 'foo' => 'bar', 'foo_bar' => 'foo_bar', - ); + ]; } } diff --git a/Tests/Fixtures/php/services_inline_requires.php b/Tests/Fixtures/php/services_inline_requires.php index 7a882f446..f0138f7ae 100644 --- a/Tests/Fixtures/php/services_inline_requires.php +++ b/Tests/Fixtures/php/services_inline_requires.php @@ -17,12 +17,12 @@ class ProjectServiceContainer extends Container { private $parameters; - private $targetDirs = array(); + private $targetDirs = []; /** * @internal but protected for BC on cache:clear */ - protected $privates = array(); + protected $privates = []; public function __construct() { @@ -32,14 +32,14 @@ public function __construct() } $this->parameters = $this->getDefaultParameters(); - $this->services = $this->privates = array(); - $this->methodMap = array( + $this->services = $this->privates = []; + $this->methodMap = [ 'Symfony\\Component\\DependencyInjection\\Tests\\Fixtures\\ParentNotExists' => 'getParentNotExistsService', 'Symfony\\Component\\DependencyInjection\\Tests\\Fixtures\\includes\\HotPath\\C1' => 'getC1Service', 'Symfony\\Component\\DependencyInjection\\Tests\\Fixtures\\includes\\HotPath\\C2' => 'getC2Service', - ); + ]; - $this->aliases = array(); + $this->aliases = []; $this->privates['service_container'] = function () { include_once $this->targetDirs[1].'/includes/HotPath/I1.php'; @@ -51,7 +51,7 @@ public function __construct() public function reset() { - $this->privates = array(); + $this->privates = []; parent::reset(); } @@ -67,11 +67,11 @@ public function isCompiled() public function getRemovedIds() { - return array( + return [ 'Psr\\Container\\ContainerInterface' => true, 'Symfony\\Component\\DependencyInjection\\ContainerInterface' => true, 'Symfony\\Component\\DependencyInjection\\Tests\\Fixtures\\includes\\HotPath\\C3' => true, - ); + ]; } /** @@ -81,7 +81,7 @@ public function getRemovedIds() */ protected function getParentNotExistsService() { - return $this->services['Symfony\Component\DependencyInjection\Tests\Fixtures\ParentNotExists'] = new \Symfony\Component\DependencyInjection\Tests\Fixtures\ParentNotExists(); + return $this->services['Symfony\\Component\\DependencyInjection\\Tests\\Fixtures\\ParentNotExists'] = new \Symfony\Component\DependencyInjection\Tests\Fixtures\ParentNotExists(); } /** @@ -91,7 +91,7 @@ protected function getParentNotExistsService() */ protected function getC1Service() { - return $this->services['Symfony\Component\DependencyInjection\Tests\Fixtures\includes\HotPath\C1'] = new \Symfony\Component\DependencyInjection\Tests\Fixtures\includes\HotPath\C1(); + return $this->services['Symfony\\Component\\DependencyInjection\\Tests\\Fixtures\\includes\\HotPath\\C1'] = new \Symfony\Component\DependencyInjection\Tests\Fixtures\includes\HotPath\C1(); } /** @@ -101,10 +101,10 @@ protected function getC1Service() */ protected function getC2Service() { - include_once $this->targetDirs[1].'/includes/HotPath/C3.php'; include_once $this->targetDirs[1].'/includes/HotPath/C2.php'; + include_once $this->targetDirs[1].'/includes/HotPath/C3.php'; - return $this->services['Symfony\Component\DependencyInjection\Tests\Fixtures\includes\HotPath\C2'] = new \Symfony\Component\DependencyInjection\Tests\Fixtures\includes\HotPath\C2(new \Symfony\Component\DependencyInjection\Tests\Fixtures\includes\HotPath\C3()); + return $this->services['Symfony\\Component\\DependencyInjection\\Tests\\Fixtures\\includes\\HotPath\\C2'] = new \Symfony\Component\DependencyInjection\Tests\Fixtures\includes\HotPath\C2(new \Symfony\Component\DependencyInjection\Tests\Fixtures\includes\HotPath\C3()); } public function getParameter($name) @@ -146,13 +146,13 @@ public function getParameterBag() return $this->parameterBag; } - private $loadedDynamicParameters = array(); - private $dynamicParameters = array(); + private $loadedDynamicParameters = []; + private $dynamicParameters = []; /** * Computes a dynamic parameter. * - * @param string The name of the dynamic parameter to load + * @param string $name The name of the dynamic parameter to load * * @return mixed The value of the dynamic parameter * @@ -170,8 +170,8 @@ private function getDynamicParameter($name) */ protected function getDefaultParameters() { - return array( + return [ 'inline_requires' => true, - ); + ]; } } diff --git a/Tests/Fixtures/php/services_inline_self_ref.php b/Tests/Fixtures/php/services_inline_self_ref.php new file mode 100644 index 000000000..c7e9e62a7 --- /dev/null +++ b/Tests/Fixtures/php/services_inline_self_ref.php @@ -0,0 +1,79 @@ +services = $this->privates = []; + $this->methodMap = [ + 'App\\Foo' => 'getFooService', + ]; + + $this->aliases = []; + } + + public function reset() + { + $this->privates = []; + parent::reset(); + } + + public function compile() + { + throw new LogicException('You cannot compile a dumped container that was already compiled.'); + } + + public function isCompiled() + { + return true; + } + + public function getRemovedIds() + { + return [ + 'Psr\\Container\\ContainerInterface' => true, + 'Symfony\\Component\\DependencyInjection\\ContainerInterface' => true, + ]; + } + + /** + * Gets the public 'App\Foo' shared service. + * + * @return \App\Foo + */ + protected function getFooService() + { + $a = new \App\Bar(); + + $b = new \App\Baz($a); + $b->bar = $a; + + $this->services['App\\Foo'] = $instance = new \App\Foo($b); + + $a->foo = $instance; + + return $instance; + } +} diff --git a/Tests/Fixtures/php/services_json_env.php b/Tests/Fixtures/php/services_json_env.php index dd2930a42..cd170b780 100644 --- a/Tests/Fixtures/php/services_json_env.php +++ b/Tests/Fixtures/php/services_json_env.php @@ -17,25 +17,25 @@ class Symfony_DI_PhpDumper_Test_JsonParameters extends Container { private $parameters; - private $targetDirs = array(); + private $targetDirs = []; /** * @internal but protected for BC on cache:clear */ - protected $privates = array(); + protected $privates = []; public function __construct() { $this->parameters = $this->getDefaultParameters(); - $this->services = $this->privates = array(); + $this->services = $this->privates = []; - $this->aliases = array(); + $this->aliases = []; } public function reset() { - $this->privates = array(); + $this->privates = []; parent::reset(); } @@ -51,10 +51,10 @@ public function isCompiled() public function getRemovedIds() { - return array( + return [ 'Psr\\Container\\ContainerInterface' => true, 'Symfony\\Component\\DependencyInjection\\ContainerInterface' => true, - ); + ]; } public function getParameter($name) @@ -96,16 +96,16 @@ public function getParameterBag() return $this->parameterBag; } - private $loadedDynamicParameters = array( + private $loadedDynamicParameters = [ 'hello' => false, 'hello-bar' => false, - ); - private $dynamicParameters = array(); + ]; + private $dynamicParameters = []; /** * Computes a dynamic parameter. * - * @param string The name of the dynamic parameter to load + * @param string $name The name of the dynamic parameter to load * * @return mixed The value of the dynamic parameter * @@ -130,9 +130,9 @@ private function getDynamicParameter($name) */ protected function getDefaultParameters() { - return array( + return [ 'env(foo)' => '["foo","bar"]', 'env(bar)' => 'null', - ); + ]; } } diff --git a/Tests/Fixtures/php/services_locator.php b/Tests/Fixtures/php/services_locator.php index 59bbce3a9..10f16c9cf 100644 --- a/Tests/Fixtures/php/services_locator.php +++ b/Tests/Fixtures/php/services_locator.php @@ -17,17 +17,17 @@ class ProjectServiceContainer extends Container { private $parameters; - private $targetDirs = array(); + private $targetDirs = []; /** * @internal but protected for BC on cache:clear */ - protected $privates = array(); + protected $privates = []; public function __construct() { - $this->services = $this->privates = array(); - $this->methodMap = array( + $this->services = $this->privates = []; + $this->methodMap = [ 'bar_service' => 'getBarServiceService', 'foo_service' => 'getFooServiceService', 'translator.loader_1' => 'getTranslator_Loader1Service', @@ -36,14 +36,14 @@ public function __construct() 'translator_1' => 'getTranslator1Service', 'translator_2' => 'getTranslator2Service', 'translator_3' => 'getTranslator3Service', - ); + ]; - $this->aliases = array(); + $this->aliases = []; } public function reset() { - $this->privates = array(); + $this->privates = []; parent::reset(); } @@ -59,14 +59,14 @@ public function isCompiled() public function getRemovedIds() { - return array( + return [ 'Psr\\Container\\ContainerInterface' => true, 'Symfony\\Component\\DependencyInjection\\ContainerInterface' => true, 'baz_service' => true, 'translator.loader_1_locator' => true, 'translator.loader_2_locator' => true, 'translator.loader_3_locator' => true, - ); + ]; } /** @@ -76,7 +76,7 @@ public function getRemovedIds() */ protected function getBarServiceService() { - return $this->services['bar_service'] = new \stdClass(($this->privates['baz_service'] ?? $this->privates['baz_service'] = new \stdClass())); + return $this->services['bar_service'] = new \stdClass(($this->privates['baz_service'] ?? ($this->privates['baz_service'] = new \stdClass()))); } /** @@ -86,13 +86,13 @@ protected function getBarServiceService() */ protected function getFooServiceService() { - return $this->services['foo_service'] = new \Symfony\Component\DependencyInjection\ServiceLocator(array('bar' => function () { + return $this->services['foo_service'] = new \Symfony\Component\DependencyInjection\ServiceLocator(['bar' => function () { return ($this->services['bar_service'] ?? $this->getBarServiceService()); }, 'baz' => function (): \stdClass { - return ($this->privates['baz_service'] ?? $this->privates['baz_service'] = new \stdClass()); + return ($this->privates['baz_service'] ?? ($this->privates['baz_service'] = new \stdClass())); }, 'nil' => function () { return NULL; - })); + }]); } /** @@ -132,9 +132,9 @@ protected function getTranslator_Loader3Service() */ protected function getTranslator1Service() { - return $this->services['translator_1'] = new \Symfony\Component\DependencyInjection\Tests\Fixtures\StubbedTranslator(new \Symfony\Component\DependencyInjection\ServiceLocator(array('translator.loader_1' => function () { - return ($this->services['translator.loader_1'] ?? $this->services['translator.loader_1'] = new \stdClass()); - }))); + return $this->services['translator_1'] = new \Symfony\Component\DependencyInjection\Tests\Fixtures\StubbedTranslator(new \Symfony\Component\DependencyInjection\ServiceLocator(['translator.loader_1' => function () { + return ($this->services['translator.loader_1'] ?? ($this->services['translator.loader_1'] = new \stdClass())); + }])); } /** @@ -144,11 +144,11 @@ protected function getTranslator1Service() */ protected function getTranslator2Service() { - $this->services['translator_2'] = $instance = new \Symfony\Component\DependencyInjection\Tests\Fixtures\StubbedTranslator(new \Symfony\Component\DependencyInjection\ServiceLocator(array('translator.loader_2' => function () { - return ($this->services['translator.loader_2'] ?? $this->services['translator.loader_2'] = new \stdClass()); - }))); + $this->services['translator_2'] = $instance = new \Symfony\Component\DependencyInjection\Tests\Fixtures\StubbedTranslator(new \Symfony\Component\DependencyInjection\ServiceLocator(['translator.loader_2' => function () { + return ($this->services['translator.loader_2'] ?? ($this->services['translator.loader_2'] = new \stdClass())); + }])); - $instance->addResource('db', ($this->services['translator.loader_2'] ?? $this->services['translator.loader_2'] = new \stdClass()), 'nl'); + $instance->addResource('db', ($this->services['translator.loader_2'] ?? ($this->services['translator.loader_2'] = new \stdClass())), 'nl'); return $instance; } @@ -160,11 +160,11 @@ protected function getTranslator2Service() */ protected function getTranslator3Service() { - $this->services['translator_3'] = $instance = new \Symfony\Component\DependencyInjection\Tests\Fixtures\StubbedTranslator(new \Symfony\Component\DependencyInjection\ServiceLocator(array('translator.loader_3' => function () { - return ($this->services['translator.loader_3'] ?? $this->services['translator.loader_3'] = new \stdClass()); - }))); + $this->services['translator_3'] = $instance = new \Symfony\Component\DependencyInjection\Tests\Fixtures\StubbedTranslator(new \Symfony\Component\DependencyInjection\ServiceLocator(['translator.loader_3' => function () { + return ($this->services['translator.loader_3'] ?? ($this->services['translator.loader_3'] = new \stdClass())); + }])); - $a = ($this->services['translator.loader_3'] ?? $this->services['translator.loader_3'] = new \stdClass()); + $a = ($this->services['translator.loader_3'] ?? ($this->services['translator.loader_3'] = new \stdClass())); $instance->addResource('db', $a, 'nl'); $instance->addResource('db', $a, 'en'); diff --git a/Tests/Fixtures/php/services_non_shared_lazy.php b/Tests/Fixtures/php/services_non_shared_lazy.php index cd5707ef2..8f8989af4 100644 --- a/Tests/Fixtures/php/services_non_shared_lazy.php +++ b/Tests/Fixtures/php/services_non_shared_lazy.php @@ -17,26 +17,26 @@ class ProjectServiceContainer extends Container { private $parameters; - private $targetDirs = array(); + private $targetDirs = []; /** * @internal but protected for BC on cache:clear */ - protected $privates = array(); + protected $privates = []; public function __construct() { - $this->services = $this->privates = array(); - $this->methodMap = array( + $this->services = $this->privates = []; + $this->methodMap = [ 'bar' => 'getBarService', - ); + ]; - $this->aliases = array(); + $this->aliases = []; } public function reset() { - $this->privates = array(); + $this->privates = []; parent::reset(); } @@ -52,11 +52,11 @@ public function isCompiled() public function getRemovedIds() { - return array( + return [ 'Psr\\Container\\ContainerInterface' => true, 'Symfony\\Component\\DependencyInjection\\ContainerInterface' => true, 'foo' => true, - ); + ]; } protected function createProxy($class, \Closure $factory) diff --git a/Tests/Fixtures/php/services_private_frozen.php b/Tests/Fixtures/php/services_private_frozen.php index 86315e2eb..b4ffa69ed 100644 --- a/Tests/Fixtures/php/services_private_frozen.php +++ b/Tests/Fixtures/php/services_private_frozen.php @@ -17,27 +17,27 @@ class ProjectServiceContainer extends Container { private $parameters; - private $targetDirs = array(); + private $targetDirs = []; /** * @internal but protected for BC on cache:clear */ - protected $privates = array(); + protected $privates = []; public function __construct() { - $this->services = $this->privates = array(); - $this->methodMap = array( + $this->services = $this->privates = []; + $this->methodMap = [ 'bar_service' => 'getBarServiceService', 'foo_service' => 'getFooServiceService', - ); + ]; - $this->aliases = array(); + $this->aliases = []; } public function reset() { - $this->privates = array(); + $this->privates = []; parent::reset(); } @@ -53,11 +53,11 @@ public function isCompiled() public function getRemovedIds() { - return array( + return [ 'Psr\\Container\\ContainerInterface' => true, 'Symfony\\Component\\DependencyInjection\\ContainerInterface' => true, 'baz_service' => true, - ); + ]; } /** @@ -67,7 +67,7 @@ public function getRemovedIds() */ protected function getBarServiceService() { - return $this->services['bar_service'] = new \stdClass(($this->privates['baz_service'] ?? $this->privates['baz_service'] = new \stdClass())); + return $this->services['bar_service'] = new \stdClass(($this->privates['baz_service'] ?? ($this->privates['baz_service'] = new \stdClass()))); } /** @@ -77,6 +77,6 @@ protected function getBarServiceService() */ protected function getFooServiceService() { - return $this->services['foo_service'] = new \stdClass(($this->privates['baz_service'] ?? $this->privates['baz_service'] = new \stdClass())); + return $this->services['foo_service'] = new \stdClass(($this->privates['baz_service'] ?? ($this->privates['baz_service'] = new \stdClass()))); } } diff --git a/Tests/Fixtures/php/services_private_in_expression.php b/Tests/Fixtures/php/services_private_in_expression.php index 5caf9104d..a98d6b133 100644 --- a/Tests/Fixtures/php/services_private_in_expression.php +++ b/Tests/Fixtures/php/services_private_in_expression.php @@ -17,26 +17,26 @@ class ProjectServiceContainer extends Container { private $parameters; - private $targetDirs = array(); + private $targetDirs = []; /** * @internal but protected for BC on cache:clear */ - protected $privates = array(); + protected $privates = []; public function __construct() { - $this->services = $this->privates = array(); - $this->methodMap = array( + $this->services = $this->privates = []; + $this->methodMap = [ 'public_foo' => 'getPublicFooService', - ); + ]; - $this->aliases = array(); + $this->aliases = []; } public function reset() { - $this->privates = array(); + $this->privates = []; parent::reset(); } @@ -52,12 +52,12 @@ public function isCompiled() public function getRemovedIds() { - return array( + return [ 'Psr\\Container\\ContainerInterface' => true, 'Symfony\\Component\\DependencyInjection\\ContainerInterface' => true, 'private_bar' => true, 'private_foo' => true, - ); + ]; } /** @@ -67,6 +67,6 @@ public function getRemovedIds() */ protected function getPublicFooService() { - return $this->services['public_foo'] = new \stdClass(($this->privates['private_foo'] ?? $this->privates['private_foo'] = new \stdClass())); + return $this->services['public_foo'] = new \stdClass(($this->privates['private_foo'] ?? ($this->privates['private_foo'] = new \stdClass()))->bar); } } diff --git a/Tests/Fixtures/php/services_rot13_env.php b/Tests/Fixtures/php/services_rot13_env.php index 012a36023..0b4c83e56 100644 --- a/Tests/Fixtures/php/services_rot13_env.php +++ b/Tests/Fixtures/php/services_rot13_env.php @@ -17,29 +17,29 @@ class Symfony_DI_PhpDumper_Test_Rot13Parameters extends Container { private $parameters; - private $targetDirs = array(); + private $targetDirs = []; /** * @internal but protected for BC on cache:clear */ - protected $privates = array(); + protected $privates = []; public function __construct() { $this->parameters = $this->getDefaultParameters(); - $this->services = $this->privates = array(); - $this->methodMap = array( + $this->services = $this->privates = []; + $this->methodMap = [ 'Symfony\\Component\\DependencyInjection\\Tests\\Dumper\\Rot13EnvVarProcessor' => 'getRot13EnvVarProcessorService', 'container.env_var_processors_locator' => 'getContainer_EnvVarProcessorsLocatorService', - ); + ]; - $this->aliases = array(); + $this->aliases = []; } public function reset() { - $this->privates = array(); + $this->privates = []; parent::reset(); } @@ -55,10 +55,10 @@ public function isCompiled() public function getRemovedIds() { - return array( + return [ 'Psr\\Container\\ContainerInterface' => true, 'Symfony\\Component\\DependencyInjection\\ContainerInterface' => true, - ); + ]; } /** @@ -68,7 +68,7 @@ public function getRemovedIds() */ protected function getRot13EnvVarProcessorService() { - return $this->services['Symfony\Component\DependencyInjection\Tests\Dumper\Rot13EnvVarProcessor'] = new \Symfony\Component\DependencyInjection\Tests\Dumper\Rot13EnvVarProcessor(); + return $this->services['Symfony\\Component\\DependencyInjection\\Tests\\Dumper\\Rot13EnvVarProcessor'] = new \Symfony\Component\DependencyInjection\Tests\Dumper\Rot13EnvVarProcessor(); } /** @@ -78,9 +78,9 @@ protected function getRot13EnvVarProcessorService() */ protected function getContainer_EnvVarProcessorsLocatorService() { - return $this->services['container.env_var_processors_locator'] = new \Symfony\Component\DependencyInjection\ServiceLocator(array('rot13' => function () { - return ($this->services['Symfony\Component\DependencyInjection\Tests\Dumper\Rot13EnvVarProcessor'] ?? $this->services['Symfony\Component\DependencyInjection\Tests\Dumper\Rot13EnvVarProcessor'] = new \Symfony\Component\DependencyInjection\Tests\Dumper\Rot13EnvVarProcessor()); - })); + return $this->services['container.env_var_processors_locator'] = new \Symfony\Component\DependencyInjection\ServiceLocator(['rot13' => function () { + return ($this->services['Symfony\\Component\\DependencyInjection\\Tests\\Dumper\\Rot13EnvVarProcessor'] ?? ($this->services['Symfony\\Component\\DependencyInjection\\Tests\\Dumper\\Rot13EnvVarProcessor'] = new \Symfony\Component\DependencyInjection\Tests\Dumper\Rot13EnvVarProcessor())); + }]); } public function getParameter($name) @@ -122,15 +122,15 @@ public function getParameterBag() return $this->parameterBag; } - private $loadedDynamicParameters = array( + private $loadedDynamicParameters = [ 'hello' => false, - ); - private $dynamicParameters = array(); + ]; + private $dynamicParameters = []; /** * Computes a dynamic parameter. * - * @param string The name of the dynamic parameter to load + * @param string $name The name of the dynamic parameter to load * * @return mixed The value of the dynamic parameter * @@ -154,8 +154,8 @@ private function getDynamicParameter($name) */ protected function getDefaultParameters() { - return array( + return [ 'env(foo)' => 'jbeyq', - ); + ]; } } diff --git a/Tests/Fixtures/php/services_subscriber.php b/Tests/Fixtures/php/services_subscriber.php index 2c887e0e2..76dff3880 100644 --- a/Tests/Fixtures/php/services_subscriber.php +++ b/Tests/Fixtures/php/services_subscriber.php @@ -17,27 +17,27 @@ class ProjectServiceContainer extends Container { private $parameters; - private $targetDirs = array(); + private $targetDirs = []; /** * @internal but protected for BC on cache:clear */ - protected $privates = array(); + protected $privates = []; public function __construct() { - $this->services = $this->privates = array(); - $this->methodMap = array( + $this->services = $this->privates = []; + $this->methodMap = [ 'Symfony\\Component\\DependencyInjection\\Tests\\Fixtures\\TestServiceSubscriber' => 'getTestServiceSubscriberService', 'foo_service' => 'getFooServiceService', - ); + ]; - $this->aliases = array(); + $this->aliases = []; } public function reset() { - $this->privates = array(); + $this->privates = []; parent::reset(); } @@ -53,13 +53,13 @@ public function isCompiled() public function getRemovedIds() { - return array( + return [ '.service_locator.ljJrY4L' => true, '.service_locator.ljJrY4L.foo_service' => true, 'Psr\\Container\\ContainerInterface' => true, 'Symfony\\Component\\DependencyInjection\\ContainerInterface' => true, 'Symfony\\Component\\DependencyInjection\\Tests\\Fixtures\\CustomDefinition' => true, - ); + ]; } /** @@ -69,7 +69,7 @@ public function getRemovedIds() */ protected function getTestServiceSubscriberService() { - return $this->services['Symfony\Component\DependencyInjection\Tests\Fixtures\TestServiceSubscriber'] = new \Symfony\Component\DependencyInjection\Tests\Fixtures\TestServiceSubscriber(); + return $this->services['Symfony\\Component\\DependencyInjection\\Tests\\Fixtures\\TestServiceSubscriber'] = new \Symfony\Component\DependencyInjection\Tests\Fixtures\TestServiceSubscriber(); } /** @@ -79,14 +79,14 @@ protected function getTestServiceSubscriberService() */ protected function getFooServiceService() { - return $this->services['foo_service'] = new \Symfony\Component\DependencyInjection\Tests\Fixtures\TestServiceSubscriber((new \Symfony\Component\DependencyInjection\ServiceLocator(array('Symfony\\Component\\DependencyInjection\\Tests\\Fixtures\\CustomDefinition' => function (): ?\Symfony\Component\DependencyInjection\Tests\Fixtures\CustomDefinition { - return ($this->privates['Symfony\Component\DependencyInjection\Tests\Fixtures\CustomDefinition'] ?? $this->privates['Symfony\Component\DependencyInjection\Tests\Fixtures\CustomDefinition'] = new \Symfony\Component\DependencyInjection\Tests\Fixtures\CustomDefinition()); + return $this->services['foo_service'] = new \Symfony\Component\DependencyInjection\Tests\Fixtures\TestServiceSubscriber((new \Symfony\Component\DependencyInjection\ServiceLocator(['Symfony\\Component\\DependencyInjection\\Tests\\Fixtures\\CustomDefinition' => function (): ?\Symfony\Component\DependencyInjection\Tests\Fixtures\CustomDefinition { + return ($this->privates['Symfony\\Component\\DependencyInjection\\Tests\\Fixtures\\CustomDefinition'] ?? ($this->privates['Symfony\\Component\\DependencyInjection\\Tests\\Fixtures\\CustomDefinition'] = new \Symfony\Component\DependencyInjection\Tests\Fixtures\CustomDefinition())); }, 'Symfony\\Component\\DependencyInjection\\Tests\\Fixtures\\TestServiceSubscriber' => function (): \Symfony\Component\DependencyInjection\Tests\Fixtures\TestServiceSubscriber { - return ($this->services['Symfony\Component\DependencyInjection\Tests\Fixtures\TestServiceSubscriber'] ?? $this->services['Symfony\Component\DependencyInjection\Tests\Fixtures\TestServiceSubscriber'] = new \Symfony\Component\DependencyInjection\Tests\Fixtures\TestServiceSubscriber()); + return ($this->services['Symfony\\Component\\DependencyInjection\\Tests\\Fixtures\\TestServiceSubscriber'] ?? ($this->services['Symfony\\Component\\DependencyInjection\\Tests\\Fixtures\\TestServiceSubscriber'] = new \Symfony\Component\DependencyInjection\Tests\Fixtures\TestServiceSubscriber())); }, 'bar' => function (): \Symfony\Component\DependencyInjection\Tests\Fixtures\CustomDefinition { - return ($this->services['Symfony\Component\DependencyInjection\Tests\Fixtures\TestServiceSubscriber'] ?? $this->services['Symfony\Component\DependencyInjection\Tests\Fixtures\TestServiceSubscriber'] = new \Symfony\Component\DependencyInjection\Tests\Fixtures\TestServiceSubscriber()); + return ($this->services['Symfony\\Component\\DependencyInjection\\Tests\\Fixtures\\TestServiceSubscriber'] ?? ($this->services['Symfony\\Component\\DependencyInjection\\Tests\\Fixtures\\TestServiceSubscriber'] = new \Symfony\Component\DependencyInjection\Tests\Fixtures\TestServiceSubscriber())); }, 'baz' => function (): ?\Symfony\Component\DependencyInjection\Tests\Fixtures\CustomDefinition { - return ($this->privates['Symfony\Component\DependencyInjection\Tests\Fixtures\CustomDefinition'] ?? $this->privates['Symfony\Component\DependencyInjection\Tests\Fixtures\CustomDefinition'] = new \Symfony\Component\DependencyInjection\Tests\Fixtures\CustomDefinition()); - })))->withContext('foo_service', $this)); + return ($this->privates['Symfony\\Component\\DependencyInjection\\Tests\\Fixtures\\CustomDefinition'] ?? ($this->privates['Symfony\\Component\\DependencyInjection\\Tests\\Fixtures\\CustomDefinition'] = new \Symfony\Component\DependencyInjection\Tests\Fixtures\CustomDefinition())); + }]))->withContext('foo_service', $this)); } } diff --git a/Tests/Fixtures/php/services_tsantos.php b/Tests/Fixtures/php/services_tsantos.php new file mode 100644 index 000000000..8f624cf75 --- /dev/null +++ b/Tests/Fixtures/php/services_tsantos.php @@ -0,0 +1,88 @@ +services = $this->privates = []; + $this->methodMap = [ + 'tsantos_serializer' => 'getTsantosSerializerService', + ]; + $this->aliases = [ + 'TSantos\\Serializer\\SerializerInterface' => 'tsantos_serializer', + ]; + } + + public function reset() + { + $this->privates = []; + parent::reset(); + } + + public function compile() + { + throw new LogicException('You cannot compile a dumped container that was already compiled.'); + } + + public function isCompiled() + { + return true; + } + + public function getRemovedIds() + { + return [ + 'Psr\\Container\\ContainerInterface' => true, + 'Symfony\\Component\\DependencyInjection\\ContainerInterface' => true, + ]; + } + + /** + * Gets the public 'tsantos_serializer' shared service. + * + * @return \TSantos\Serializer\EventEmitterSerializer + */ + protected function getTsantosSerializerService() + { + $a = new \TSantos\Serializer\NormalizerRegistry(); + + $b = new \TSantos\Serializer\Normalizer\CollectionNormalizer(); + + $c = new \TSantos\Serializer\EventDispatcher\EventDispatcher(); + $c->addSubscriber(new \TSantos\SerializerBundle\EventListener\StopwatchListener(new \Symfony\Component\Stopwatch\Stopwatch(true))); + + $this->services['tsantos_serializer'] = $instance = new \TSantos\Serializer\EventEmitterSerializer(new \TSantos\Serializer\Encoder\JsonEncoder(), $a, $c); + + $b->setSerializer($instance); + $d = new \TSantos\Serializer\Normalizer\JsonNormalizer(); + $d->setSerializer($instance); + + $a->add(new \TSantos\Serializer\Normalizer\ObjectNormalizer(new \TSantos\SerializerBundle\Serializer\CircularReferenceHandler())); + $a->add($b); + $a->add($d); + + return $instance; + } +} diff --git a/Tests/Fixtures/php/services_uninitialized_ref.php b/Tests/Fixtures/php/services_uninitialized_ref.php index 0f5090c80..831442df8 100644 --- a/Tests/Fixtures/php/services_uninitialized_ref.php +++ b/Tests/Fixtures/php/services_uninitialized_ref.php @@ -17,28 +17,28 @@ class Symfony_DI_PhpDumper_Test_Uninitialized_Reference extends Container { private $parameters; - private $targetDirs = array(); + private $targetDirs = []; /** * @internal but protected for BC on cache:clear */ - protected $privates = array(); + protected $privates = []; public function __construct() { - $this->services = $this->privates = array(); - $this->methodMap = array( + $this->services = $this->privates = []; + $this->methodMap = [ 'bar' => 'getBarService', 'baz' => 'getBazService', 'foo1' => 'getFoo1Service', - ); + ]; - $this->aliases = array(); + $this->aliases = []; } public function reset() { - $this->privates = array(); + $this->privates = []; parent::reset(); } @@ -54,12 +54,12 @@ public function isCompiled() public function getRemovedIds() { - return array( + return [ 'Psr\\Container\\ContainerInterface' => true, 'Symfony\\Component\\DependencyInjection\\ContainerInterface' => true, 'foo2' => true, 'foo3' => true, - ); + ]; } /** @@ -74,13 +74,13 @@ protected function getBarService() $instance->foo1 = ($this->services['foo1'] ?? null); $instance->foo2 = null; $instance->foo3 = ($this->privates['foo3'] ?? null); - $instance->closures = array(0 => function () { + $instance->closures = [0 => function () { return ($this->services['foo1'] ?? null); }, 1 => function () { return null; }, 2 => function () { return ($this->privates['foo3'] ?? null); - }); + }]; $instance->iter = new RewindableGenerator(function () { if (isset($this->services['foo1'])) { yield 'foo1' => ($this->services['foo1'] ?? null); @@ -107,7 +107,7 @@ protected function getBazService() { $this->services['baz'] = $instance = new \stdClass(); - $instance->foo3 = ($this->privates['foo3'] ?? $this->privates['foo3'] = new \stdClass()); + $instance->foo3 = ($this->privates['foo3'] ?? ($this->privates['foo3'] = new \stdClass())); return $instance; } diff --git a/Tests/Fixtures/php/services_unsupported_characters.php b/Tests/Fixtures/php/services_unsupported_characters.php new file mode 100644 index 000000000..5793b4b51 --- /dev/null +++ b/Tests/Fixtures/php/services_unsupported_characters.php @@ -0,0 +1,162 @@ +parameters = $this->getDefaultParameters(); + + $this->services = $this->privates = []; + $this->methodMap = [ + 'bar$' => 'getBarService', + 'bar$!' => 'getBar2Service', + 'foo*/oh-no' => 'getFooohnoService', + ]; + + $this->aliases = []; + } + + public function reset() + { + $this->privates = []; + parent::reset(); + } + + public function compile() + { + throw new LogicException('You cannot compile a dumped container that was already compiled.'); + } + + public function isCompiled() + { + return true; + } + + public function getRemovedIds() + { + return [ + 'Psr\\Container\\ContainerInterface' => true, + 'Symfony\\Component\\DependencyInjection\\ContainerInterface' => true, + ]; + } + + /** + * Gets the public 'bar$' shared service. + * + * @return \FooClass + */ + protected function getBarService() + { + return $this->services['bar$'] = new \FooClass(); + } + + /** + * Gets the public 'bar$!' shared service. + * + * @return \FooClass + */ + protected function getBar2Service() + { + return $this->services['bar$!'] = new \FooClass(); + } + + /** + * Gets the public 'foo oh-no' shared service. + * + * @return \FooClass + */ + protected function getFooohnoService() + { + return $this->services['foo*/oh-no'] = new \FooClass(); + } + + public function getParameter($name) + { + $name = (string) $name; + + if (!(isset($this->parameters[$name]) || isset($this->loadedDynamicParameters[$name]) || array_key_exists($name, $this->parameters))) { + throw new InvalidArgumentException(sprintf('The parameter "%s" must be defined.', $name)); + } + if (isset($this->loadedDynamicParameters[$name])) { + return $this->loadedDynamicParameters[$name] ? $this->dynamicParameters[$name] : $this->getDynamicParameter($name); + } + + return $this->parameters[$name]; + } + + public function hasParameter($name) + { + $name = (string) $name; + + return isset($this->parameters[$name]) || isset($this->loadedDynamicParameters[$name]) || array_key_exists($name, $this->parameters); + } + + public function setParameter($name, $value) + { + throw new LogicException('Impossible to call set() on a frozen ParameterBag.'); + } + + public function getParameterBag() + { + if (null === $this->parameterBag) { + $parameters = $this->parameters; + foreach ($this->loadedDynamicParameters as $name => $loaded) { + $parameters[$name] = $loaded ? $this->dynamicParameters[$name] : $this->getDynamicParameter($name); + } + $this->parameterBag = new FrozenParameterBag($parameters); + } + + return $this->parameterBag; + } + + private $loadedDynamicParameters = []; + private $dynamicParameters = []; + + /** + * Computes a dynamic parameter. + * + * @param string $name The name of the dynamic parameter to load + * + * @return mixed The value of the dynamic parameter + * + * @throws InvalidArgumentException When the dynamic parameter does not exist + */ + private function getDynamicParameter($name) + { + throw new InvalidArgumentException(sprintf('The dynamic parameter "%s" must be defined.', $name)); + } + + /** + * Gets the default parameters. + * + * @return array An array of the default parameters + */ + protected function getDefaultParameters() + { + return [ + '\'' => 'oh-no', + ]; + } +} diff --git a/Tests/Fixtures/xml/services6.xml b/Tests/Fixtures/xml/services6.xml index cffd5df60..c85b7a7c0 100644 --- a/Tests/Fixtures/xml/services6.xml +++ b/Tests/Fixtures/xml/services6.xml @@ -61,5 +61,9 @@ + + + + diff --git a/Tests/Fixtures/xml/services_tsantos.xml b/Tests/Fixtures/xml/services_tsantos.xml new file mode 100644 index 000000000..bb310b279 --- /dev/null +++ b/Tests/Fixtures/xml/services_tsantos.xml @@ -0,0 +1,65 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + true + + + + + + + + + + + diff --git a/Tests/Fixtures/yaml/services_adawson.yml b/Tests/Fixtures/yaml/services_adawson.yml new file mode 100644 index 000000000..2a26f38a8 --- /dev/null +++ b/Tests/Fixtures/yaml/services_adawson.yml @@ -0,0 +1,28 @@ +services: + App\Db: + public: true + properties: + schema: '@App\Schema' + + App\Bus: + public: true + arguments: ['@App\Db'] + properties: + handler1: '@App\Handler1' + handler2: '@App\Handler2' + + App\Handler1: + ['@App\Db', '@App\Schema', '@App\Processor'] + + App\Handler2: + ['@App\Db', '@App\Schema', '@App\Processor'] + + App\Processor: + ['@App\Registry', '@App\Db'] + + App\Registry: + properties: + processor: ['@App\Db', '@App\Bus'] + + App\Schema: + arguments: ['@App\Db'] diff --git a/Tests/Fixtures/yaml/services_deep_graph.yml b/Tests/Fixtures/yaml/services_deep_graph.yml new file mode 100644 index 000000000..f16329aef --- /dev/null +++ b/Tests/Fixtures/yaml/services_deep_graph.yml @@ -0,0 +1,24 @@ + +services: + foo: + class: Symfony\Component\DependencyInjection\Tests\Dumper\FooForDeepGraph + public: true + arguments: + - '@bar' + - !service + class: stdClass + properties: + p2: !service + class: stdClass + properties: + p3: !service + class: stdClass + + bar: + class: stdClass + public: true + properties: + p5: !service + class: stdClass + arguments: ['@foo'] + diff --git a/Tests/Loader/DirectoryLoaderTest.php b/Tests/Loader/DirectoryLoaderTest.php index 5de657737..c7c303b68 100644 --- a/Tests/Loader/DirectoryLoaderTest.php +++ b/Tests/Loader/DirectoryLoaderTest.php @@ -12,13 +12,13 @@ namespace Symfony\Component\DependencyInjection\Tests\Loader; use PHPUnit\Framework\TestCase; +use Symfony\Component\Config\FileLocator; +use Symfony\Component\Config\Loader\LoaderResolver; use Symfony\Component\DependencyInjection\ContainerBuilder; -use Symfony\Component\DependencyInjection\Loader\PhpFileLoader; +use Symfony\Component\DependencyInjection\Loader\DirectoryLoader; use Symfony\Component\DependencyInjection\Loader\IniFileLoader; +use Symfony\Component\DependencyInjection\Loader\PhpFileLoader; use Symfony\Component\DependencyInjection\Loader\YamlFileLoader; -use Symfony\Component\DependencyInjection\Loader\DirectoryLoader; -use Symfony\Component\Config\Loader\LoaderResolver; -use Symfony\Component\Config\FileLocator; class DirectoryLoaderTest extends TestCase { @@ -37,25 +37,25 @@ protected function setUp() $locator = new FileLocator(self::$fixturesPath); $this->container = new ContainerBuilder(); $this->loader = new DirectoryLoader($this->container, $locator); - $resolver = new LoaderResolver(array( + $resolver = new LoaderResolver([ new PhpFileLoader($this->container, $locator), new IniFileLoader($this->container, $locator), new YamlFileLoader($this->container, $locator), $this->loader, - )); + ]); $this->loader->setResolver($resolver); } public function testDirectoryCanBeLoadedRecursively() { $this->loader->load('directory/'); - $this->assertEquals(array('ini' => 'ini', 'yaml' => 'yaml', 'php' => 'php'), $this->container->getParameterBag()->all(), '->load() takes a single directory'); + $this->assertEquals(['ini' => 'ini', 'yaml' => 'yaml', 'php' => 'php'], $this->container->getParameterBag()->all(), '->load() takes a single directory'); } public function testImports() { $this->loader->resolve('directory/import/import.yml')->load('directory/import/import.yml'); - $this->assertEquals(array('ini' => 'ini', 'yaml' => 'yaml'), $this->container->getParameterBag()->all(), '->load() takes a single file that imports a directory'); + $this->assertEquals(['ini' => 'ini', 'yaml' => 'yaml'], $this->container->getParameterBag()->all(), '->load() takes a single file that imports a directory'); } /** diff --git a/Tests/Loader/FileLoaderTest.php b/Tests/Loader/FileLoaderTest.php index 8a271a818..065acdf1b 100644 --- a/Tests/Loader/FileLoaderTest.php +++ b/Tests/Loader/FileLoaderTest.php @@ -11,8 +11,8 @@ namespace Symfony\Component\DependencyInjection\Tests\Loader; -use Psr\Container\ContainerInterface as PsrContainerInterface; use PHPUnit\Framework\TestCase; +use Psr\Container\ContainerInterface as PsrContainerInterface; use Symfony\Component\Config\FileLocator; use Symfony\Component\Config\Loader\LoaderResolver; use Symfony\Component\DependencyInjection\ContainerBuilder; @@ -26,10 +26,10 @@ use Symfony\Component\DependencyInjection\Loader\YamlFileLoader; use Symfony\Component\DependencyInjection\Reference; use Symfony\Component\DependencyInjection\Tests\Fixtures\Prototype\BadClasses\MissingParent; -use Symfony\Component\DependencyInjection\Tests\Fixtures\Prototype\OtherDir\AnotherSub\DeeperBaz; -use Symfony\Component\DependencyInjection\Tests\Fixtures\Prototype\OtherDir\Baz; use Symfony\Component\DependencyInjection\Tests\Fixtures\Prototype\Foo; use Symfony\Component\DependencyInjection\Tests\Fixtures\Prototype\FooInterface; +use Symfony\Component\DependencyInjection\Tests\Fixtures\Prototype\OtherDir\AnotherSub\DeeperBaz; +use Symfony\Component\DependencyInjection\Tests\Fixtures\Prototype\OtherDir\Baz; use Symfony\Component\DependencyInjection\Tests\Fixtures\Prototype\Sub\Bar; use Symfony\Component\DependencyInjection\Tests\Fixtures\Prototype\Sub\BarInterface; @@ -47,21 +47,21 @@ public function testImportWithGlobPattern() $container = new ContainerBuilder(); $loader = new TestFileLoader($container, new FileLocator(self::$fixturesPath)); - $resolver = new LoaderResolver(array( + $resolver = new LoaderResolver([ new IniFileLoader($container, new FileLocator(self::$fixturesPath.'/ini')), new XmlFileLoader($container, new FileLocator(self::$fixturesPath.'/xml')), new PhpFileLoader($container, new FileLocator(self::$fixturesPath.'/php')), new YamlFileLoader($container, new FileLocator(self::$fixturesPath.'/yaml')), - )); + ]); $loader->setResolver($resolver); $loader->import('{F}ixtures/{xml,yaml}/services2.{yml,xml}'); $actual = $container->getParameterBag()->all(); - $expected = array( + $expected = [ 'a string', 'foo' => 'bar', - 'values' => array( + 'values' => [ 0, 'integer' => 4, 100 => null, @@ -73,14 +73,14 @@ public function testImportWithGlobPattern() 'float' => 1.3, 1000.3, 'a string', - array('foo', 'bar'), - ), - 'mixedcase' => array('MixedCaseKey' => 'value'), + ['foo', 'bar'], + ], + 'mixedcase' => ['MixedCaseKey' => 'value'], 'constant' => PHP_EOL, 'bar' => '%foo%', 'escape' => '@escapeme', 'foo_bar' => new Reference('foo_bar'), - ); + ]; $this->assertEquals(array_keys($expected), array_keys($actual), '->load() imports and merges imported files'); } @@ -94,15 +94,15 @@ public function testRegisterClasses() $loader->registerClasses(new Definition(), 'Symfony\Component\DependencyInjection\Tests\Fixtures\Prototype\Sub\\', 'Prototype/%sub_dir%/*'); $this->assertEquals( - array('service_container', Bar::class), + ['service_container', Bar::class], array_keys($container->getDefinitions()) ); $this->assertEquals( - array( + [ PsrContainerInterface::class, ContainerInterface::class, BarInterface::class, - ), + ], array_keys($container->getAliases()) ); } @@ -127,11 +127,11 @@ public function testRegisterClassesWithExclude() $this->assertFalse($container->has(DeeperBaz::class)); $this->assertEquals( - array( + [ PsrContainerInterface::class, ContainerInterface::class, BarInterface::class, - ), + ], array_keys($container->getAliases()) ); } @@ -150,11 +150,11 @@ public function testNestedRegisterClasses() $this->assertTrue($container->has(Foo::class)); $this->assertEquals( - array( + [ PsrContainerInterface::class, ContainerInterface::class, FooInterface::class, - ), + ], array_keys($container->getAliases()) ); @@ -179,7 +179,7 @@ public function testMissingParentClass() $this->assertTrue($container->has(MissingParent::class)); $this->assertSame( - array('While discovering services from namespace "Symfony\Component\DependencyInjection\Tests\Fixtures\Prototype\BadClasses\", an error was thrown when processing the class "Symfony\Component\DependencyInjection\Tests\Fixtures\Prototype\BadClasses\MissingParent": "Class Symfony\Component\DependencyInjection\Tests\Fixtures\Prototype\BadClasses\MissingClass not found".'), + ['While discovering services from namespace "Symfony\Component\DependencyInjection\Tests\Fixtures\Prototype\BadClasses\", an error was thrown when processing the class "Symfony\Component\DependencyInjection\Tests\Fixtures\Prototype\BadClasses\MissingParent": "Class Symfony\Component\DependencyInjection\Tests\Fixtures\Prototype\BadClasses\MissingClass not found".'], $container->getDefinition(MissingParent::class)->getErrors() ); } @@ -222,8 +222,8 @@ public function testRegisterClassesWithIncompatibleExclude($resourcePattern, $ex public function getIncompatibleExcludeTests() { - yield array('Prototype/*', 'yaml/*', false); - yield array('Prototype/OtherDir/*', 'Prototype/*', false); + yield ['Prototype/*', 'yaml/*', false]; + yield ['Prototype/OtherDir/*', 'Prototype/*', false]; } } diff --git a/Tests/Loader/GlobFileLoaderTest.php b/Tests/Loader/GlobFileLoaderTest.php index a3be4dfd3..74822f551 100644 --- a/Tests/Loader/GlobFileLoaderTest.php +++ b/Tests/Loader/GlobFileLoaderTest.php @@ -12,10 +12,10 @@ namespace Symfony\Component\DependencyInjection\Tests\Loader; use PHPUnit\Framework\TestCase; +use Symfony\Component\Config\FileLocator; use Symfony\Component\Config\Resource\GlobResource; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Loader\GlobFileLoader; -use Symfony\Component\Config\FileLocator; class GlobFileLoaderTest extends TestCase { diff --git a/Tests/Loader/IniFileLoaderTest.php b/Tests/Loader/IniFileLoaderTest.php index 84c934c08..ce8641c75 100644 --- a/Tests/Loader/IniFileLoaderTest.php +++ b/Tests/Loader/IniFileLoaderTest.php @@ -12,9 +12,9 @@ namespace Symfony\Component\DependencyInjection\Tests\Loader; use PHPUnit\Framework\TestCase; +use Symfony\Component\Config\FileLocator; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Loader\IniFileLoader; -use Symfony\Component\Config\FileLocator; class IniFileLoaderTest extends TestCase { @@ -30,7 +30,7 @@ protected function setUp() public function testIniFileCanBeLoaded() { $this->loader->load('parameters.ini'); - $this->assertEquals(array('foo' => 'bar', 'bar' => '%foo%'), $this->container->getParameterBag()->all(), '->load() takes a single file name as its first argument'); + $this->assertEquals(['foo' => 'bar', 'bar' => '%foo%'], $this->container->getParameterBag()->all(), '->load() takes a single file name as its first argument'); } /** @@ -53,41 +53,41 @@ public function testTypeConversionsWithNativePhp($key, $value, $supported) $this->markTestSkipped(sprintf('Converting the value "%s" to "%s" is not supported by the IniFileLoader.', $key, $value)); } - $this->loader->load('types.ini'); $expected = parse_ini_file(__DIR__.'/../Fixtures/ini/types.ini', true, INI_SCANNER_TYPED); $this->assertSame($value, $expected['parameters'][$key], '->load() converts values to PHP types'); } public function getTypeConversions() { - return array( - array('true_comment', true, true), - array('true', true, true), - array('false', false, true), - array('on', true, true), - array('off', false, true), - array('yes', true, true), - array('no', false, true), - array('none', false, true), - array('null', null, true), - array('constant', PHP_VERSION, true), - array('12', 12, true), - array('12_string', '12', true), - array('12_comment', 12, true), - array('12_string_comment', '12', true), - array('12_string_comment_again', '12', true), - array('-12', -12, true), - array('1', 1, true), - array('0', 0, true), - array('0b0110', bindec('0b0110'), false), // not supported by INI_SCANNER_TYPED - array('11112222333344445555', '1111,2222,3333,4444,5555', true), - array('0777', 0777, false), // not supported by INI_SCANNER_TYPED - array('255', 0xFF, false), // not supported by INI_SCANNER_TYPED - array('100.0', 1e2, false), // not supported by INI_SCANNER_TYPED - array('-120.0', -1.2E2, false), // not supported by INI_SCANNER_TYPED - array('-10100.1', -10100.1, false), // not supported by INI_SCANNER_TYPED - array('-10,100.1', '-10,100.1', true), - ); + return [ + ['true_comment', true, true], + ['true', true, true], + ['false', false, true], + ['on', true, true], + ['off', false, true], + ['yes', true, true], + ['no', false, true], + ['none', false, true], + ['null', null, true], + ['constant', PHP_VERSION, true], + ['12', 12, true], + ['12_string', '12', true], + ['12_quoted_number', 12, false], // INI_SCANNER_RAW removes the double quotes + ['12_comment', 12, true], + ['12_string_comment', '12', true], + ['12_quoted_number_comment', 12, false], // INI_SCANNER_RAW removes the double quotes + ['-12', -12, true], + ['1', 1, true], + ['0', 0, true], + ['0b0110', bindec('0b0110'), false], // not supported by INI_SCANNER_TYPED + ['11112222333344445555', '1111,2222,3333,4444,5555', true], + ['0777', 0777, false], // not supported by INI_SCANNER_TYPED + ['255', 0xFF, false], // not supported by INI_SCANNER_TYPED + ['100.0', 1e2, false], // not supported by INI_SCANNER_TYPED + ['-120.0', -1.2E2, false], // not supported by INI_SCANNER_TYPED + ['-10100.1', -10100.1, false], // not supported by INI_SCANNER_TYPED + ['-10,100.1', '-10,100.1', true], + ]; } /** diff --git a/Tests/Loader/LoaderResolverTest.php b/Tests/Loader/LoaderResolverTest.php index cb2d6ddcc..9167e18ce 100644 --- a/Tests/Loader/LoaderResolverTest.php +++ b/Tests/Loader/LoaderResolverTest.php @@ -33,23 +33,23 @@ protected function setUp() self::$fixturesPath = realpath(__DIR__.'/../Fixtures/'); $container = new ContainerBuilder(); - $this->resolver = new LoaderResolver(array( + $this->resolver = new LoaderResolver([ new XmlFileLoader($container, new FileLocator(self::$fixturesPath.'/xml')), new YamlFileLoader($container, new FileLocator(self::$fixturesPath.'/yaml')), new IniFileLoader($container, new FileLocator(self::$fixturesPath.'/ini')), new PhpFileLoader($container, new FileLocator(self::$fixturesPath.'/php')), new ClosureLoader($container), - )); + ]); } public function provideResourcesToLoad() { - return array( - array('ini_with_wrong_ext.xml', 'ini', IniFileLoader::class), - array('xml_with_wrong_ext.php', 'xml', XmlFileLoader::class), - array('php_with_wrong_ext.yml', 'php', PhpFileLoader::class), - array('yaml_with_wrong_ext.ini', 'yaml', YamlFileLoader::class), - ); + return [ + ['ini_with_wrong_ext.xml', 'ini', IniFileLoader::class], + ['xml_with_wrong_ext.php', 'xml', XmlFileLoader::class], + ['php_with_wrong_ext.yml', 'php', PhpFileLoader::class], + ['yaml_with_wrong_ext.ini', 'yaml', YamlFileLoader::class], + ]; } /** diff --git a/Tests/Loader/PhpFileLoaderTest.php b/Tests/Loader/PhpFileLoaderTest.php index b584a6922..ae3b0bd82 100644 --- a/Tests/Loader/PhpFileLoaderTest.php +++ b/Tests/Loader/PhpFileLoaderTest.php @@ -12,11 +12,11 @@ namespace Symfony\Component\DependencyInjection\Tests\Loader; use PHPUnit\Framework\TestCase; +use Symfony\Component\Config\FileLocator; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Dumper\PhpDumper; use Symfony\Component\DependencyInjection\Dumper\YamlDumper; use Symfony\Component\DependencyInjection\Loader\PhpFileLoader; -use Symfony\Component\Config\FileLocator; class PhpFileLoaderTest extends TestCase { @@ -47,7 +47,7 @@ public function testConfigServices() $container->compile(); $dumper = new PhpDumper($container); - $this->assertStringEqualsFile($fixtures.'/php/services9_compiled.php', str_replace(str_replace('\\', '\\\\', $fixtures.DIRECTORY_SEPARATOR.'includes'.DIRECTORY_SEPARATOR), '%path%', $dumper->dump())); + $this->assertStringEqualsFile($fixtures.'/php/services9_compiled.php', str_replace(str_replace('\\', '\\\\', $fixtures.\DIRECTORY_SEPARATOR.'includes'.\DIRECTORY_SEPARATOR), '%path%', $dumper->dump())); } /** @@ -67,14 +67,14 @@ public function testConfig($file) public function provideConfig() { - yield array('basic'); - yield array('object'); - yield array('defaults'); - yield array('instanceof'); - yield array('prototype'); - yield array('child'); - yield array('php7'); - yield array('anonymous'); + yield ['basic']; + yield ['object']; + yield ['defaults']; + yield ['instanceof']; + yield ['prototype']; + yield ['child']; + yield ['php7']; + yield ['anonymous']; } /** diff --git a/Tests/Loader/XmlFileLoaderTest.php b/Tests/Loader/XmlFileLoaderTest.php index 7e0ce3871..7a57f7cf8 100644 --- a/Tests/Loader/XmlFileLoaderTest.php +++ b/Tests/Loader/XmlFileLoaderTest.php @@ -12,22 +12,23 @@ namespace Symfony\Component\DependencyInjection\Tests\Loader; use PHPUnit\Framework\TestCase; -use Symfony\Component\DependencyInjection\Argument\IteratorArgument; +use Symfony\Component\Config\FileLocator; +use Symfony\Component\Config\Loader\LoaderResolver; +use Symfony\Component\Config\Resource\FileResource; +use Symfony\Component\Config\Resource\GlobResource; use Symfony\Component\DependencyInjection\Argument\BoundArgument; +use Symfony\Component\DependencyInjection\Argument\IteratorArgument; use Symfony\Component\DependencyInjection\ContainerBuilder; -use Symfony\Component\DependencyInjection\Reference; +use Symfony\Component\DependencyInjection\Dumper\PhpDumper; +use Symfony\Component\DependencyInjection\Loader\IniFileLoader; use Symfony\Component\DependencyInjection\Loader\XmlFileLoader; use Symfony\Component\DependencyInjection\Loader\YamlFileLoader; -use Symfony\Component\DependencyInjection\Loader\IniFileLoader; -use Symfony\Component\Config\Loader\LoaderResolver; -use Symfony\Component\Config\FileLocator; -use Symfony\Component\Config\Resource\FileResource; -use Symfony\Component\Config\Resource\GlobResource; +use Symfony\Component\DependencyInjection\Reference; use Symfony\Component\DependencyInjection\Tests\Fixtures\Bar; use Symfony\Component\DependencyInjection\Tests\Fixtures\BarInterface; use Symfony\Component\DependencyInjection\Tests\Fixtures\CaseSensitiveClass; -use Symfony\Component\DependencyInjection\Tests\Fixtures\Prototype; use Symfony\Component\DependencyInjection\Tests\Fixtures\NamedArgumentsDummy; +use Symfony\Component\DependencyInjection\Tests\Fixtures\Prototype; use Symfony\Component\ExpressionLanguage\Expression; class XmlFileLoaderTest extends TestCase @@ -67,7 +68,7 @@ public function testParseFile() $this->fail('->parseFileToDOM() throws an InvalidArgumentException if the loaded file is not a valid XML file'); } catch (\Exception $e) { $this->assertInstanceOf('Symfony\\Component\\DependencyInjection\\Exception\\InvalidArgumentException', $e, '->parseFileToDOM() throws an InvalidArgumentException if the loaded file is not a valid XML file'); - $this->assertRegExp(sprintf('#^Unable to parse file ".+%s".$#', 'parameters.ini'), $e->getMessage(), '->parseFileToDOM() throws an InvalidArgumentException if the loaded file is not a valid XML file'); + $this->assertRegExp(sprintf('#^Unable to parse file ".+%s": .+.$#', 'parameters.ini'), $e->getMessage(), '->parseFileToDOM() throws an InvalidArgumentException if the loaded file is not a valid XML file'); $e = $e->getPrevious(); $this->assertInstanceOf('InvalidArgumentException', $e, '->parseFileToDOM() throws an InvalidArgumentException if the loaded file is not a valid XML file'); @@ -81,7 +82,7 @@ public function testParseFile() $this->fail('->parseFileToDOM() throws an InvalidArgumentException if the loaded file does not validate the XSD'); } catch (\Exception $e) { $this->assertInstanceOf('Symfony\\Component\\DependencyInjection\\Exception\\InvalidArgumentException', $e, '->parseFileToDOM() throws an InvalidArgumentException if the loaded file does not validate the XSD'); - $this->assertRegExp(sprintf('#^Unable to parse file ".+%s".$#', 'nonvalid.xml'), $e->getMessage(), '->parseFileToDOM() throws an InvalidArgumentException if the loaded file is not a valid XML file'); + $this->assertRegExp(sprintf('#^Unable to parse file ".+%s": .+.$#', 'nonvalid.xml'), $e->getMessage(), '->parseFileToDOM() throws an InvalidArgumentException if the loaded file is not a valid XML file'); $e = $e->getPrevious(); $this->assertInstanceOf('InvalidArgumentException', $e, '->parseFileToDOM() throws an InvalidArgumentException if the loaded file does not validate the XSD'); @@ -112,10 +113,10 @@ public function testLoadParameters() $loader->load('services2.xml'); $actual = $container->getParameterBag()->all(); - $expected = array( + $expected = [ 'a string', 'foo' => 'bar', - 'values' => array( + 'values' => [ 0, 'integer' => 4, 100 => null, @@ -127,11 +128,11 @@ public function testLoadParameters() 'float' => 1.3, 1000.3, 'a string', - array('foo', 'bar'), - ), - 'mixedcase' => array('MixedCaseKey' => 'value'), + ['foo', 'bar'], + ], + 'mixedcase' => ['MixedCaseKey' => 'value'], 'constant' => PHP_EOL, - ); + ]; $this->assertEquals($expected, $actual, '->load() converts XML values to PHP ones'); } @@ -139,19 +140,19 @@ public function testLoadParameters() public function testLoadImports() { $container = new ContainerBuilder(); - $resolver = new LoaderResolver(array( + $resolver = new LoaderResolver([ new IniFileLoader($container, new FileLocator(self::$fixturesPath.'/ini')), new YamlFileLoader($container, new FileLocator(self::$fixturesPath.'/yml')), $loader = new XmlFileLoader($container, new FileLocator(self::$fixturesPath.'/xml')), - )); + ]); $loader->setResolver($resolver); $loader->load('services4.xml'); $actual = $container->getParameterBag()->all(); - $expected = array( + $expected = [ 'a string', 'foo' => 'bar', - 'values' => array( + 'values' => [ 0, 'integer' => 4, 100 => null, @@ -163,15 +164,15 @@ public function testLoadImports() 'float' => 1.3, 1000.3, 'a string', - array('foo', 'bar'), - ), - 'mixedcase' => array('MixedCaseKey' => 'value'), + ['foo', 'bar'], + ], + 'mixedcase' => ['MixedCaseKey' => 'value'], 'constant' => PHP_EOL, 'bar' => '%foo%', 'imported_from_ini' => true, 'imported_from_yaml' => true, 'with_wrong_ext' => 'from yaml', - ); + ]; $this->assertEquals(array_keys($expected), array_keys($actual), '->load() imports and merges imported files'); $this->assertTrue($actual['imported_from_ini']); @@ -256,16 +257,16 @@ public function testLoadServices() $this->assertInstanceOf('Symfony\\Component\\DependencyInjection\\Definition', $services['foo'], '->load() converts element to Definition instances'); $this->assertEquals('FooClass', $services['foo']->getClass(), '->load() parses the class attribute'); $this->assertEquals('%path%/foo.php', $services['file']->getFile(), '->load() parses the file tag'); - $this->assertEquals(array('foo', new Reference('foo'), array(true, false)), $services['arguments']->getArguments(), '->load() parses the argument tags'); + $this->assertEquals(['foo', new Reference('foo'), [true, false]], $services['arguments']->getArguments(), '->load() parses the argument tags'); $this->assertEquals('sc_configure', $services['configurator1']->getConfigurator(), '->load() parses the configurator tag'); - $this->assertEquals(array(new Reference('baz'), 'configure'), $services['configurator2']->getConfigurator(), '->load() parses the configurator tag'); - $this->assertEquals(array('BazClass', 'configureStatic'), $services['configurator3']->getConfigurator(), '->load() parses the configurator tag'); - $this->assertEquals(array(array('setBar', array()), array('setBar', array(new Expression('service("foo").foo() ~ (container.hasParameter("foo") ? parameter("foo") : "default")')))), $services['method_call1']->getMethodCalls(), '->load() parses the method_call tag'); - $this->assertEquals(array(array('setBar', array('foo', new Reference('foo'), array(true, false)))), $services['method_call2']->getMethodCalls(), '->load() parses the method_call tag'); + $this->assertEquals([new Reference('baz'), 'configure'], $services['configurator2']->getConfigurator(), '->load() parses the configurator tag'); + $this->assertEquals(['BazClass', 'configureStatic'], $services['configurator3']->getConfigurator(), '->load() parses the configurator tag'); + $this->assertEquals([['setBar', []], ['setBar', [new Expression('service("foo").foo() ~ (container.hasParameter("foo") ? parameter("foo") : "default")')]]], $services['method_call1']->getMethodCalls(), '->load() parses the method_call tag'); + $this->assertEquals([['setBar', ['foo', new Reference('foo'), [true, false]]]], $services['method_call2']->getMethodCalls(), '->load() parses the method_call tag'); $this->assertEquals('factory', $services['new_factory1']->getFactory(), '->load() parses the factory tag'); - $this->assertEquals(array(new Reference('baz'), 'getClass'), $services['new_factory2']->getFactory(), '->load() parses the factory tag'); - $this->assertEquals(array('BazClass', 'getInstance'), $services['new_factory3']->getFactory(), '->load() parses the factory tag'); - $this->assertSame(array(null, 'getInstance'), $services['new_factory4']->getFactory(), '->load() accepts factory tag without class'); + $this->assertEquals([new Reference('baz'), 'getClass'], $services['new_factory2']->getFactory(), '->load() parses the factory tag'); + $this->assertEquals(['BazClass', 'getInstance'], $services['new_factory3']->getFactory(), '->load() parses the factory tag'); + $this->assertSame([null, 'getInstance'], $services['new_factory4']->getFactory(), '->load() accepts factory tag without class'); $aliases = $container->getAliases(); $this->assertArrayHasKey('alias_for_foo', $aliases, '->load() parses elements'); @@ -275,9 +276,9 @@ public function testLoadServices() $this->assertEquals('foo', (string) $aliases['another_alias_for_foo']); $this->assertFalse($aliases['another_alias_for_foo']->isPublic()); - $this->assertEquals(array('decorated', null, 0), $services['decorator_service']->getDecoratedService()); - $this->assertEquals(array('decorated', 'decorated.pif-pouf', 0), $services['decorator_service_with_name']->getDecoratedService()); - $this->assertEquals(array('decorated', 'decorated.pif-pouf', 5), $services['decorator_service_with_name_and_priority']->getDecoratedService()); + $this->assertEquals(['decorated', null, 0], $services['decorator_service']->getDecoratedService()); + $this->assertEquals(['decorated', 'decorated.pif-pouf', 0], $services['decorator_service_with_name']->getDecoratedService()); + $this->assertEquals(['decorated', 'decorated.pif-pouf', 5], $services['decorator_service_with_name_and_priority']->getDecoratedService()); } public function testParsesIteratorArgument() @@ -288,7 +289,7 @@ public function testParsesIteratorArgument() $lazyDefinition = $container->getDefinition('lazy_context'); - $this->assertEquals(array(new IteratorArgument(array('k1' => new Reference('foo.baz'), 'k2' => new Reference('service_container'))), new IteratorArgument(array())), $lazyDefinition->getArguments(), '->load() parses lazy arguments'); + $this->assertEquals([new IteratorArgument(['k1' => new Reference('foo.baz'), 'k2' => new Reference('service_container')]), new IteratorArgument([])], $lazyDefinition->getArguments(), '->load() parses lazy arguments'); } public function testParsesTags() @@ -358,27 +359,27 @@ public function testConvertDomElementToArray() $doc = new \DOMDocument('1.0'); $doc->loadXML(''); - $this->assertEquals(array('foo' => 'bar'), XmlFileLoader::convertDomElementToArray($doc->documentElement), '::convertDomElementToArray() converts a \DomElement to an array'); + $this->assertEquals(['foo' => 'bar'], XmlFileLoader::convertDomElementToArray($doc->documentElement), '::convertDomElementToArray() converts a \DomElement to an array'); $doc = new \DOMDocument('1.0'); $doc->loadXML('bar'); - $this->assertEquals(array('foo' => 'bar'), XmlFileLoader::convertDomElementToArray($doc->documentElement), '::convertDomElementToArray() converts a \DomElement to an array'); + $this->assertEquals(['foo' => 'bar'], XmlFileLoader::convertDomElementToArray($doc->documentElement), '::convertDomElementToArray() converts a \DomElement to an array'); $doc = new \DOMDocument('1.0'); $doc->loadXML('barbar'); - $this->assertEquals(array('foo' => array('value' => 'bar', 'foo' => 'bar')), XmlFileLoader::convertDomElementToArray($doc->documentElement), '::convertDomElementToArray() converts a \DomElement to an array'); + $this->assertEquals(['foo' => ['value' => 'bar', 'foo' => 'bar']], XmlFileLoader::convertDomElementToArray($doc->documentElement), '::convertDomElementToArray() converts a \DomElement to an array'); $doc = new \DOMDocument('1.0'); $doc->loadXML(''); - $this->assertEquals(array('foo' => null), XmlFileLoader::convertDomElementToArray($doc->documentElement), '::convertDomElementToArray() converts a \DomElement to an array'); + $this->assertEquals(['foo' => null], XmlFileLoader::convertDomElementToArray($doc->documentElement), '::convertDomElementToArray() converts a \DomElement to an array'); $doc = new \DOMDocument('1.0'); $doc->loadXML(''); - $this->assertEquals(array('foo' => null), XmlFileLoader::convertDomElementToArray($doc->documentElement), '::convertDomElementToArray() converts a \DomElement to an array'); + $this->assertEquals(['foo' => null], XmlFileLoader::convertDomElementToArray($doc->documentElement), '::convertDomElementToArray() converts a \DomElement to an array'); $doc = new \DOMDocument('1.0'); $doc->loadXML(''); - $this->assertEquals(array('foo' => array(array('foo' => 'bar'), array('foo' => 'bar'))), XmlFileLoader::convertDomElementToArray($doc->documentElement), '::convertDomElementToArray() converts a \DomElement to an array'); + $this->assertEquals(['foo' => [['foo' => 'bar'], ['foo' => 'bar']]], XmlFileLoader::convertDomElementToArray($doc->documentElement), '::convertDomElementToArray() converts a \DomElement to an array'); } public function testExtensions() @@ -427,7 +428,7 @@ public function testExtensions() $this->fail('->load() throws an InvalidArgumentException if the configuration does not validate the XSD'); } catch (\Exception $e) { $this->assertInstanceOf('Symfony\\Component\\DependencyInjection\\Exception\\InvalidArgumentException', $e, '->load() throws an InvalidArgumentException if the configuration does not validate the XSD'); - $this->assertRegExp(sprintf('#^Unable to parse file ".+%s".$#', 'services3.xml'), $e->getMessage(), '->load() throws an InvalidArgumentException if the configuration does not validate the XSD'); + $this->assertRegExp(sprintf('#^Unable to parse file ".+%s": .+.$#', 'services3.xml'), $e->getMessage(), '->load() throws an InvalidArgumentException if the configuration does not validate the XSD'); $e = $e->getPrevious(); $this->assertInstanceOf('InvalidArgumentException', $e, '->load() throws an InvalidArgumentException if the configuration does not validate the XSD'); @@ -446,7 +447,7 @@ public function testExtensions() public function testExtensionInPhar() { - if (extension_loaded('suhosin') && false === strpos(ini_get('suhosin.executor.include.whitelist'), 'phar')) { + if (\extension_loaded('suhosin') && false === strpos(ini_get('suhosin.executor.include.whitelist'), 'phar')) { $this->markTestSkipped('To run this test, add "phar" to the "suhosin.executor.include.whitelist" settings in your php.ini file.'); } @@ -464,7 +465,7 @@ public function testExtensionInPhar() $this->fail('->load() throws an InvalidArgumentException if the configuration does not validate the XSD'); } catch (\Exception $e) { $this->assertInstanceOf('Symfony\\Component\\DependencyInjection\\Exception\\InvalidArgumentException', $e, '->load() throws an InvalidArgumentException if the configuration does not validate the XSD'); - $this->assertRegExp(sprintf('#^Unable to parse file ".+%s".$#', 'services7.xml'), $e->getMessage(), '->load() throws an InvalidArgumentException if the configuration does not validate the XSD'); + $this->assertRegExp(sprintf('#^Unable to parse file ".+%s": .+.$#', 'services7.xml'), $e->getMessage(), '->load() throws an InvalidArgumentException if the configuration does not validate the XSD'); $e = $e->getPrevious(); $this->assertInstanceOf('InvalidArgumentException', $e, '->load() throws an InvalidArgumentException if the configuration does not validate the XSD'); @@ -515,7 +516,7 @@ public function testDocTypeIsNotAllowed() $this->fail('->load() throws an InvalidArgumentException if the configuration contains a document type'); } catch (\Exception $e) { $this->assertInstanceOf('Symfony\\Component\\DependencyInjection\\Exception\\InvalidArgumentException', $e, '->load() throws an InvalidArgumentException if the configuration contains a document type'); - $this->assertRegExp(sprintf('#^Unable to parse file ".+%s".$#', 'withdoctype.xml'), $e->getMessage(), '->load() throws an InvalidArgumentException if the configuration contains a document type'); + $this->assertRegExp(sprintf('#^Unable to parse file ".+%s": .+.$#', 'withdoctype.xml'), $e->getMessage(), '->load() throws an InvalidArgumentException if the configuration contains a document type'); $e = $e->getPrevious(); $this->assertInstanceOf('InvalidArgumentException', $e, '->load() throws an InvalidArgumentException if the configuration contains a document type'); @@ -532,7 +533,7 @@ public function testXmlNamespaces() $this->assertArrayHasKey('foo', $services, '->load() parses elements'); $this->assertCount(1, $services['foo']->getTag('foo.tag'), '->load parses elements'); - $this->assertEquals(array(array('setBar', array('foo'))), $services['foo']->getMethodCalls(), '->load() parses the tag'); + $this->assertEquals([['setBar', ['foo']]], $services['foo']->getMethodCalls(), '->load() parses the tag'); } public function testLoadIndexedArguments() @@ -541,7 +542,7 @@ public function testLoadIndexedArguments() $loader = new XmlFileLoader($container, new FileLocator(self::$fixturesPath.'/xml')); $loader->load('services14.xml'); - $this->assertEquals(array('index_0' => 'app'), $container->findDefinition('logger')->getArguments()); + $this->assertEquals(['index_0' => 'app'], $container->findDefinition('logger')->getArguments()); } public function testLoadInlinedServices() @@ -605,14 +606,14 @@ public function testPrototype() $ids = array_keys($container->getDefinitions()); sort($ids); - $this->assertSame(array(Prototype\Foo::class, Prototype\Sub\Bar::class, 'service_container'), $ids); + $this->assertSame([Prototype\Foo::class, Prototype\Sub\Bar::class, 'service_container'], $ids); $resources = $container->getResources(); - $fixturesDir = dirname(__DIR__).DIRECTORY_SEPARATOR.'Fixtures'.DIRECTORY_SEPARATOR; - $this->assertTrue(false !== array_search(new FileResource($fixturesDir.'xml'.DIRECTORY_SEPARATOR.'services_prototype.xml'), $resources)); - $this->assertTrue(false !== array_search(new GlobResource($fixturesDir.'Prototype', '/*', true), $resources)); + $fixturesDir = \dirname(__DIR__).\DIRECTORY_SEPARATOR.'Fixtures'.\DIRECTORY_SEPARATOR; $resources = array_map('strval', $resources); + $this->assertContains((string) (new FileResource($fixturesDir.'xml'.\DIRECTORY_SEPARATOR.'services_prototype.xml')), $resources); + $this->assertContains((string) (new GlobResource($fixturesDir.'Prototype', '/*', true)), $resources); $this->assertContains('reflection.Symfony\Component\DependencyInjection\Tests\Fixtures\Prototype\Foo', $resources); $this->assertContains('reflection.Symfony\Component\DependencyInjection\Tests\Fixtures\Prototype\Sub\Bar', $resources); } @@ -637,7 +638,7 @@ public function testArgumentWithKeyOutsideCollection() $loader = new XmlFileLoader($container, new FileLocator(self::$fixturesPath.'/xml')); $loader->load('with_key_outside_collection.xml'); - $this->assertSame(array('type' => 'foo', 'bar'), $container->getDefinition('foo')->getArguments()); + $this->assertSame(['type' => 'foo', 'bar'], $container->getDefinition('foo')->getArguments()); } public function testDefaults() @@ -647,7 +648,7 @@ public function testDefaults() $loader->load('services28.xml'); $this->assertFalse($container->getDefinition('with_defaults')->isPublic()); - $this->assertSame(array('foo' => array(array())), $container->getDefinition('with_defaults')->getTags()); + $this->assertSame(['foo' => [[]]], $container->getDefinition('with_defaults')->getTags()); $this->assertTrue($container->getDefinition('with_defaults')->isAutowired()); $this->assertArrayNotHasKey('public', $container->getDefinition('with_defaults')->getChanges()); $this->assertArrayNotHasKey('autowire', $container->getDefinition('with_defaults')->getChanges()); @@ -656,12 +657,12 @@ public function testDefaults() $this->assertTrue($container->getDefinition('no_defaults')->isPublic()); - $this->assertSame(array('foo' => array(array())), $container->getDefinition('no_defaults')->getTags()); + $this->assertSame(['foo' => [[]]], $container->getDefinition('no_defaults')->getTags()); $this->assertFalse($container->getDefinition('no_defaults')->isAutowired()); $this->assertTrue($container->getDefinition('child_def')->isPublic()); - $this->assertSame(array('foo' => array(array())), $container->getDefinition('child_def')->getTags()); + $this->assertSame(['foo' => [[]]], $container->getDefinition('child_def')->getTags()); $this->assertFalse($container->getDefinition('child_def')->isAutowired()); $definitions = $container->getDefinitions(); @@ -672,7 +673,7 @@ public function testDefaults() $this->assertSame('bar', key($definitions)); $this->assertTrue($anonymous->isPublic()); $this->assertTrue($anonymous->isAutowired()); - $this->assertSame(array('foo' => array(array())), $anonymous->getTags()); + $this->assertSame(['foo' => [[]]], $anonymous->getTags()); } public function testNamedArguments() @@ -681,12 +682,12 @@ public function testNamedArguments() $loader = new XmlFileLoader($container, new FileLocator(self::$fixturesPath.'/xml')); $loader->load('services_named_args.xml'); - $this->assertEquals(array('$apiKey' => 'ABCD', CaseSensitiveClass::class => null), $container->getDefinition(NamedArgumentsDummy::class)->getArguments()); + $this->assertEquals(['$apiKey' => 'ABCD', CaseSensitiveClass::class => null], $container->getDefinition(NamedArgumentsDummy::class)->getArguments()); $container->compile(); - $this->assertEquals(array(null, 'ABCD'), $container->getDefinition(NamedArgumentsDummy::class)->getArguments()); - $this->assertEquals(array(array('setApiKey', array('123'))), $container->getDefinition(NamedArgumentsDummy::class)->getMethodCalls()); + $this->assertEquals([null, 'ABCD'], $container->getDefinition(NamedArgumentsDummy::class)->getArguments()); + $this->assertEquals([['setApiKey', ['123']]], $container->getDefinition(NamedArgumentsDummy::class)->getMethodCalls()); } public function testInstanceof() @@ -699,7 +700,7 @@ public function testInstanceof() $definition = $container->getDefinition(Bar::class); $this->assertTrue($definition->isAutowired()); $this->assertTrue($definition->isLazy()); - $this->assertSame(array('foo' => array(array()), 'bar' => array(array())), $definition->getTags()); + $this->assertSame(['foo' => [[]], 'bar' => [[]]], $definition->getTags()); } /** @@ -771,29 +772,41 @@ public function testBindings() $container->compile(); $definition = $container->getDefinition('bar'); - $this->assertEquals(array( + $this->assertEquals([ 'NonExistent' => null, BarInterface::class => new Reference(Bar::class), - '$foo' => array(null), + '$foo' => [null], '$quz' => 'quz', '$factory' => 'factory', - ), array_map(function (BoundArgument $v) { return $v->getValues()[0]; }, $definition->getBindings())); - $this->assertEquals(array( + ], array_map(function (BoundArgument $v) { return $v->getValues()[0]; }, $definition->getBindings())); + $this->assertEquals([ 'quz', null, new Reference(Bar::class), - array(null), - ), $definition->getArguments()); + [null], + ], $definition->getArguments()); $definition = $container->getDefinition(Bar::class); - $this->assertEquals(array( + $this->assertEquals([ null, 'factory', - ), $definition->getArguments()); - $this->assertEquals(array( + ], $definition->getArguments()); + $this->assertEquals([ 'NonExistent' => null, '$quz' => 'quz', '$factory' => 'factory', - ), array_map(function (BoundArgument $v) { return $v->getValues()[0]; }, $definition->getBindings())); + ], array_map(function (BoundArgument $v) { return $v->getValues()[0]; }, $definition->getBindings())); + } + + public function testTsantosContainer() + { + $container = new ContainerBuilder(); + $loader = new XmlFileLoader($container, new FileLocator(self::$fixturesPath.'/xml')); + $loader->load('services_tsantos.xml'); + $container->compile(); + + $dumper = new PhpDumper($container); + $dump = $dumper->dump(); + $this->assertStringEqualsFile(self::$fixturesPath.'/php/services_tsantos.php', $dumper->dump()); } } diff --git a/Tests/Loader/YamlFileLoaderTest.php b/Tests/Loader/YamlFileLoaderTest.php index 8ddc15f88..aad3dbda1 100644 --- a/Tests/Loader/YamlFileLoaderTest.php +++ b/Tests/Loader/YamlFileLoaderTest.php @@ -12,23 +12,23 @@ namespace Symfony\Component\DependencyInjection\Tests\Loader; use PHPUnit\Framework\TestCase; +use Symfony\Component\Config\FileLocator; +use Symfony\Component\Config\Loader\LoaderResolver; +use Symfony\Component\Config\Resource\FileResource; +use Symfony\Component\Config\Resource\GlobResource; use Symfony\Component\DependencyInjection\Argument\BoundArgument; use Symfony\Component\DependencyInjection\Argument\IteratorArgument; use Symfony\Component\DependencyInjection\ContainerBuilder; -use Symfony\Component\DependencyInjection\Reference; -use Symfony\Component\DependencyInjection\Loader\XmlFileLoader; -use Symfony\Component\DependencyInjection\Loader\YamlFileLoader; use Symfony\Component\DependencyInjection\Loader\IniFileLoader; use Symfony\Component\DependencyInjection\Loader\PhpFileLoader; -use Symfony\Component\Config\Loader\LoaderResolver; -use Symfony\Component\Config\FileLocator; -use Symfony\Component\Config\Resource\FileResource; -use Symfony\Component\Config\Resource\GlobResource; +use Symfony\Component\DependencyInjection\Loader\XmlFileLoader; +use Symfony\Component\DependencyInjection\Loader\YamlFileLoader; +use Symfony\Component\DependencyInjection\Reference; use Symfony\Component\DependencyInjection\Tests\Fixtures\Bar; use Symfony\Component\DependencyInjection\Tests\Fixtures\BarInterface; use Symfony\Component\DependencyInjection\Tests\Fixtures\CaseSensitiveClass; -use Symfony\Component\DependencyInjection\Tests\Fixtures\Prototype; use Symfony\Component\DependencyInjection\Tests\Fixtures\NamedArgumentsDummy; +use Symfony\Component\DependencyInjection\Tests\Fixtures\Prototype; use Symfony\Component\ExpressionLanguage\Expression; class YamlFileLoaderTest extends TestCase @@ -84,17 +84,17 @@ public function testLoadInvalidFile($file) public function provideInvalidFiles() { - return array( - array('bad_parameters'), - array('bad_imports'), - array('bad_import'), - array('bad_services'), - array('bad_service'), - array('bad_calls'), - array('bad_format'), - array('nonvalid1'), - array('nonvalid2'), - ); + return [ + ['bad_parameters'], + ['bad_imports'], + ['bad_import'], + ['bad_services'], + ['bad_service'], + ['bad_calls'], + ['bad_format'], + ['nonvalid1'], + ['nonvalid2'], + ]; } public function testLoadParameters() @@ -102,33 +102,33 @@ public function testLoadParameters() $container = new ContainerBuilder(); $loader = new YamlFileLoader($container, new FileLocator(self::$fixturesPath.'/yaml')); $loader->load('services2.yml'); - $this->assertEquals(array('foo' => 'bar', 'mixedcase' => array('MixedCaseKey' => 'value'), 'values' => array(true, false, 0, 1000.3, PHP_INT_MAX), 'bar' => 'foo', 'escape' => '@escapeme', 'foo_bar' => new Reference('foo_bar')), $container->getParameterBag()->all(), '->load() converts YAML keys to lowercase'); + $this->assertEquals(['foo' => 'bar', 'mixedcase' => ['MixedCaseKey' => 'value'], 'values' => [true, false, 0, 1000.3, PHP_INT_MAX], 'bar' => 'foo', 'escape' => '@escapeme', 'foo_bar' => new Reference('foo_bar')], $container->getParameterBag()->all(), '->load() converts YAML keys to lowercase'); } public function testLoadImports() { $container = new ContainerBuilder(); - $resolver = new LoaderResolver(array( + $resolver = new LoaderResolver([ new IniFileLoader($container, new FileLocator(self::$fixturesPath.'/ini')), new XmlFileLoader($container, new FileLocator(self::$fixturesPath.'/xml')), new PhpFileLoader($container, new FileLocator(self::$fixturesPath.'/php')), $loader = new YamlFileLoader($container, new FileLocator(self::$fixturesPath.'/yaml')), - )); + ]); $loader->setResolver($resolver); $loader->load('services4.yml'); $actual = $container->getParameterBag()->all(); - $expected = array( + $expected = [ 'foo' => 'bar', - 'values' => array(true, false, PHP_INT_MAX), + 'values' => [true, false, PHP_INT_MAX], 'bar' => '%foo%', 'escape' => '@escapeme', 'foo_bar' => new Reference('foo_bar'), - 'mixedcase' => array('MixedCaseKey' => 'value'), + 'mixedcase' => ['MixedCaseKey' => 'value'], 'imported_from_ini' => true, 'imported_from_xml' => true, 'with_wrong_ext' => 'from yaml', - ); + ]; $this->assertEquals(array_keys($expected), array_keys($actual), '->load() imports and merges imported files'); $this->assertTrue($actual['imported_from_ini']); @@ -147,17 +147,17 @@ public function testLoadServices() $this->assertInstanceOf('Symfony\\Component\\DependencyInjection\\Definition', $services['foo'], '->load() converts service element to Definition instances'); $this->assertEquals('FooClass', $services['foo']->getClass(), '->load() parses the class attribute'); $this->assertEquals('%path%/foo.php', $services['file']->getFile(), '->load() parses the file tag'); - $this->assertEquals(array('foo', new Reference('foo'), array(true, false)), $services['arguments']->getArguments(), '->load() parses the argument tags'); + $this->assertEquals(['foo', new Reference('foo'), [true, false]], $services['arguments']->getArguments(), '->load() parses the argument tags'); $this->assertEquals('sc_configure', $services['configurator1']->getConfigurator(), '->load() parses the configurator tag'); - $this->assertEquals(array(new Reference('baz'), 'configure'), $services['configurator2']->getConfigurator(), '->load() parses the configurator tag'); - $this->assertEquals(array('BazClass', 'configureStatic'), $services['configurator3']->getConfigurator(), '->load() parses the configurator tag'); - $this->assertEquals(array(array('setBar', array()), array('setBar', array()), array('setBar', array(new Expression('service("foo").foo() ~ (container.hasParameter("foo") ? parameter("foo") : "default")')))), $services['method_call1']->getMethodCalls(), '->load() parses the method_call tag'); - $this->assertEquals(array(array('setBar', array('foo', new Reference('foo'), array(true, false)))), $services['method_call2']->getMethodCalls(), '->load() parses the method_call tag'); + $this->assertEquals([new Reference('baz'), 'configure'], $services['configurator2']->getConfigurator(), '->load() parses the configurator tag'); + $this->assertEquals(['BazClass', 'configureStatic'], $services['configurator3']->getConfigurator(), '->load() parses the configurator tag'); + $this->assertEquals([['setBar', []], ['setBar', []], ['setBar', [new Expression('service("foo").foo() ~ (container.hasParameter("foo") ? parameter("foo") : "default")')]]], $services['method_call1']->getMethodCalls(), '->load() parses the method_call tag'); + $this->assertEquals([['setBar', ['foo', new Reference('foo'), [true, false]]]], $services['method_call2']->getMethodCalls(), '->load() parses the method_call tag'); $this->assertEquals('factory', $services['new_factory1']->getFactory(), '->load() parses the factory tag'); - $this->assertEquals(array(new Reference('baz'), 'getClass'), $services['new_factory2']->getFactory(), '->load() parses the factory tag'); - $this->assertEquals(array('BazClass', 'getInstance'), $services['new_factory3']->getFactory(), '->load() parses the factory tag'); - $this->assertSame(array(null, 'getInstance'), $services['new_factory4']->getFactory(), '->load() accepts factory tag without class'); - $this->assertEquals(array('foo', new Reference('baz')), $services['Acme\WithShortCutArgs']->getArguments(), '->load() parses short service definition'); + $this->assertEquals([new Reference('baz'), 'getClass'], $services['new_factory2']->getFactory(), '->load() parses the factory tag'); + $this->assertEquals(['BazClass', 'getInstance'], $services['new_factory3']->getFactory(), '->load() parses the factory tag'); + $this->assertSame([null, 'getInstance'], $services['new_factory4']->getFactory(), '->load() accepts factory tag without class'); + $this->assertEquals(['foo', new Reference('baz')], $services['Acme\WithShortCutArgs']->getArguments(), '->load() parses short service definition'); $aliases = $container->getAliases(); $this->assertArrayHasKey('alias_for_foo', $aliases, '->load() parses aliases'); @@ -170,9 +170,9 @@ public function testLoadServices() $this->assertEquals('foo', (string) $aliases['another_third_alias_for_foo']); $this->assertTrue($aliases['another_third_alias_for_foo']->isPublic()); - $this->assertEquals(array('decorated', null, 0), $services['decorator_service']->getDecoratedService()); - $this->assertEquals(array('decorated', 'decorated.pif-pouf', 0), $services['decorator_service_with_name']->getDecoratedService()); - $this->assertEquals(array('decorated', 'decorated.pif-pouf', 5), $services['decorator_service_with_name_and_priority']->getDecoratedService()); + $this->assertEquals(['decorated', null, 0], $services['decorator_service']->getDecoratedService()); + $this->assertEquals(['decorated', 'decorated.pif-pouf', 0], $services['decorator_service_with_name']->getDecoratedService()); + $this->assertEquals(['decorated', 'decorated.pif-pouf', 5], $services['decorator_service_with_name_and_priority']->getDecoratedService()); } public function testLoadFactoryShortSyntax() @@ -182,8 +182,8 @@ public function testLoadFactoryShortSyntax() $loader->load('services14.yml'); $services = $container->getDefinitions(); - $this->assertEquals(array(new Reference('baz'), 'getClass'), $services['factory']->getFactory(), '->load() parses the factory tag with service:method'); - $this->assertEquals(array('FooBacFactory', 'createFooBar'), $services['factory_with_static_call']->getFactory(), '->load() parses the factory tag with Class::method'); + $this->assertEquals([new Reference('baz'), 'getClass'], $services['factory']->getFactory(), '->load() parses the factory tag with service:method'); + $this->assertEquals(['FooBacFactory', 'createFooBar'], $services['factory_with_static_call']->getFactory(), '->load() parses the factory tag with Class::method'); } public function testLoadConfiguratorShortSyntax() @@ -193,8 +193,8 @@ public function testLoadConfiguratorShortSyntax() $loader->load('services_configurator_short_syntax.yml'); $services = $container->getDefinitions(); - $this->assertEquals(array(new Reference('foo_bar_configurator'), 'configure'), $services['foo_bar']->getConfigurator(), '->load() parses the configurator tag with service:method'); - $this->assertEquals(array('FooBarConfigurator', 'configureFooBar'), $services['foo_bar_with_static_call']->getConfigurator(), '->load() parses the configurator tag with Class::method'); + $this->assertEquals([new Reference('foo_bar_configurator'), 'configure'], $services['foo_bar']->getConfigurator(), '->load() parses the configurator tag with service:method'); + $this->assertEquals(['FooBarConfigurator', 'configureFooBar'], $services['foo_bar_with_static_call']->getConfigurator(), '->load() parses the configurator tag with Class::method'); } public function testExtensions() @@ -230,7 +230,7 @@ public function testExtensionWithNullConfig() $loader->load('null_config.yml'); $container->compile(); - $this->assertSame(array(null), $container->getParameter('project.configs')); + $this->assertSame([null], $container->getParameter('project.configs')); } public function testSupports() @@ -296,9 +296,9 @@ public function testLoadYamlOnlyWithKeys() $loader->load('services21.yml'); $definition = $container->getDefinition('manager'); - $this->assertEquals(array(array('setLogger', array(new Reference('logger'))), array('setClass', array('User'))), $definition->getMethodCalls()); - $this->assertEquals(array(true), $definition->getArguments()); - $this->assertEquals(array('manager' => array(array('alias' => 'user'))), $definition->getTags()); + $this->assertEquals([['setLogger', [new Reference('logger')]], ['setClass', ['User']]], $definition->getMethodCalls()); + $this->assertEquals([true], $definition->getArguments()); + $this->assertEquals(['manager' => [['alias' => 'user']]], $definition->getTags()); } /** @@ -329,7 +329,7 @@ public function testParsesIteratorArgument() $lazyDefinition = $container->getDefinition('lazy_context'); - $this->assertEquals(array(new IteratorArgument(array('k1' => new Reference('foo.baz'), 'k2' => new Reference('service_container'))), new IteratorArgument(array())), $lazyDefinition->getArguments(), '->load() parses lazy arguments'); + $this->assertEquals([new IteratorArgument(['k1' => new Reference('foo.baz'), 'k2' => new Reference('service_container')]), new IteratorArgument([])], $lazyDefinition->getArguments(), '->load() parses lazy arguments'); } public function testAutowire() @@ -359,14 +359,14 @@ public function testPrototype() $ids = array_keys($container->getDefinitions()); sort($ids); - $this->assertSame(array(Prototype\Foo::class, Prototype\Sub\Bar::class, 'service_container'), $ids); + $this->assertSame([Prototype\Foo::class, Prototype\Sub\Bar::class, 'service_container'], $ids); $resources = $container->getResources(); - $fixturesDir = dirname(__DIR__).DIRECTORY_SEPARATOR.'Fixtures'.DIRECTORY_SEPARATOR; - $this->assertTrue(false !== array_search(new FileResource($fixturesDir.'yaml'.DIRECTORY_SEPARATOR.'services_prototype.yml'), $resources)); - $this->assertTrue(false !== array_search(new GlobResource($fixturesDir.'Prototype', '', true), $resources)); + $fixturesDir = \dirname(__DIR__).\DIRECTORY_SEPARATOR.'Fixtures'.\DIRECTORY_SEPARATOR; $resources = array_map('strval', $resources); + $this->assertContains((string) (new FileResource($fixturesDir.'yaml'.\DIRECTORY_SEPARATOR.'services_prototype.yml')), $resources); + $this->assertContains((string) (new GlobResource($fixturesDir.'Prototype', '', true)), $resources); $this->assertContains('reflection.Symfony\Component\DependencyInjection\Tests\Fixtures\Prototype\Foo', $resources); $this->assertContains('reflection.Symfony\Component\DependencyInjection\Tests\Fixtures\Prototype\Sub\Bar', $resources); } @@ -380,13 +380,13 @@ public function testPrototypeWithNamespace() $ids = array_keys($container->getDefinitions()); sort($ids); - $this->assertSame(array( + $this->assertSame([ Prototype\OtherDir\Component1\Dir1\Service1::class, Prototype\OtherDir\Component1\Dir2\Service2::class, Prototype\OtherDir\Component2\Dir1\Service4::class, Prototype\OtherDir\Component2\Dir2\Service5::class, 'service_container', - ), $ids); + ], $ids); $this->assertTrue($container->getDefinition(Prototype\OtherDir\Component1\Dir1\Service1::class)->hasTag('foo')); $this->assertTrue($container->getDefinition(Prototype\OtherDir\Component2\Dir1\Service4::class)->hasTag('foo')); @@ -417,7 +417,7 @@ public function testDefaults() $loader->load('services28.yml'); $this->assertFalse($container->getDefinition('with_defaults')->isPublic()); - $this->assertSame(array('foo' => array(array())), $container->getDefinition('with_defaults')->getTags()); + $this->assertSame(['foo' => [[]]], $container->getDefinition('with_defaults')->getTags()); $this->assertTrue($container->getDefinition('with_defaults')->isAutowired()); $this->assertArrayNotHasKey('public', $container->getDefinition('with_defaults')->getChanges()); $this->assertArrayNotHasKey('autowire', $container->getDefinition('with_defaults')->getChanges()); @@ -426,7 +426,7 @@ public function testDefaults() $this->assertFalse($container->getAlias('with_defaults_aliased_short')->isPublic()); $this->assertFalse($container->getDefinition('Acme\WithShortCutArgs')->isPublic()); - $this->assertSame(array('foo' => array(array())), $container->getDefinition('Acme\WithShortCutArgs')->getTags()); + $this->assertSame(['foo' => [[]]], $container->getDefinition('Acme\WithShortCutArgs')->getTags()); $this->assertTrue($container->getDefinition('Acme\WithShortCutArgs')->isAutowired()); $container->compile(); @@ -435,14 +435,14 @@ public function testDefaults() $this->assertTrue($container->getDefinition('no_defaults')->isPublic()); // foo tag is inherited from defaults - $this->assertSame(array('foo' => array(array())), $container->getDefinition('with_null')->getTags()); - $this->assertSame(array('foo' => array(array())), $container->getDefinition('no_defaults')->getTags()); + $this->assertSame(['foo' => [[]]], $container->getDefinition('with_null')->getTags()); + $this->assertSame(['foo' => [[]]], $container->getDefinition('no_defaults')->getTags()); $this->assertTrue($container->getDefinition('with_null')->isAutowired()); $this->assertFalse($container->getDefinition('no_defaults')->isAutowired()); $this->assertTrue($container->getDefinition('child_def')->isPublic()); - $this->assertSame(array('foo' => array(array())), $container->getDefinition('child_def')->getTags()); + $this->assertSame(['foo' => [[]]], $container->getDefinition('child_def')->getTags()); $this->assertFalse($container->getDefinition('child_def')->isAutowired()); } @@ -452,14 +452,14 @@ public function testNamedArguments() $loader = new YamlFileLoader($container, new FileLocator(self::$fixturesPath.'/yaml')); $loader->load('services_named_args.yml'); - $this->assertEquals(array(null, '$apiKey' => 'ABCD'), $container->getDefinition(NamedArgumentsDummy::class)->getArguments()); - $this->assertEquals(array('$apiKey' => 'ABCD', CaseSensitiveClass::class => null), $container->getDefinition('another_one')->getArguments()); + $this->assertEquals([null, '$apiKey' => 'ABCD'], $container->getDefinition(NamedArgumentsDummy::class)->getArguments()); + $this->assertEquals(['$apiKey' => 'ABCD', CaseSensitiveClass::class => null], $container->getDefinition('another_one')->getArguments()); $container->compile(); - $this->assertEquals(array(null, 'ABCD'), $container->getDefinition(NamedArgumentsDummy::class)->getArguments()); - $this->assertEquals(array(null, 'ABCD'), $container->getDefinition('another_one')->getArguments()); - $this->assertEquals(array(array('setApiKey', array('123'))), $container->getDefinition('another_one')->getMethodCalls()); + $this->assertEquals([null, 'ABCD'], $container->getDefinition(NamedArgumentsDummy::class)->getArguments()); + $this->assertEquals([null, 'ABCD'], $container->getDefinition('another_one')->getArguments()); + $this->assertEquals([['setApiKey', ['123']]], $container->getDefinition('another_one')->getMethodCalls()); } public function testInstanceof() @@ -472,7 +472,7 @@ public function testInstanceof() $definition = $container->getDefinition(Bar::class); $this->assertTrue($definition->isAutowired()); $this->assertTrue($definition->isLazy()); - $this->assertSame(array('foo' => array(array()), 'bar' => array(array())), $definition->getTags()); + $this->assertSame(['foo' => [[]], 'bar' => [[]]], $definition->getTags()); } /** @@ -556,7 +556,7 @@ public function testAnonymousServices() $this->assertCount(1, $args); $this->assertInstanceOf(Reference::class, $args[0]); $this->assertTrue($container->has((string) $args[0])); - $this->assertRegExp('/^\.\d+_Bar[._A-Za-z0-9]{7}$/', (string) $args[0]); + $this->assertRegExp('/^\.\d+_Bar~[._A-Za-z0-9]{7}$/', (string) $args[0]); $anonymous = $container->getDefinition((string) $args[0]); $this->assertEquals('Bar', $anonymous->getClass()); @@ -568,7 +568,7 @@ public function testAnonymousServices() $this->assertInternalType('array', $factory); $this->assertInstanceOf(Reference::class, $factory[0]); $this->assertTrue($container->has((string) $factory[0])); - $this->assertRegExp('/^\.\d+_Quz[._A-Za-z0-9]{7}$/', (string) $factory[0]); + $this->assertRegExp('/^\.\d+_Quz~[._A-Za-z0-9]{7}$/', (string) $factory[0]); $this->assertEquals('constructFoo', $factory[1]); $anonymous = $container->getDefinition((string) $factory[0]); @@ -714,29 +714,29 @@ public function testBindings() $container->compile(); $definition = $container->getDefinition('bar'); - $this->assertEquals(array( + $this->assertEquals([ 'NonExistent' => null, BarInterface::class => new Reference(Bar::class), - '$foo' => array(null), + '$foo' => [null], '$quz' => 'quz', '$factory' => 'factory', - ), array_map(function (BoundArgument $v) { return $v->getValues()[0]; }, $definition->getBindings())); - $this->assertEquals(array( + ], array_map(function (BoundArgument $v) { return $v->getValues()[0]; }, $definition->getBindings())); + $this->assertEquals([ 'quz', null, new Reference(Bar::class), - array(null), - ), $definition->getArguments()); + [null], + ], $definition->getArguments()); $definition = $container->getDefinition(Bar::class); - $this->assertEquals(array( + $this->assertEquals([ null, 'factory', - ), $definition->getArguments()); - $this->assertEquals(array( + ], $definition->getArguments()); + $this->assertEquals([ 'NonExistent' => null, '$quz' => 'quz', '$factory' => 'factory', - ), array_map(function (BoundArgument $v) { return $v->getValues()[0]; }, $definition->getBindings())); + ], array_map(function (BoundArgument $v) { return $v->getValues()[0]; }, $definition->getBindings())); } } diff --git a/Tests/ParameterBag/ContainerBagTest.php b/Tests/ParameterBag/ContainerBagTest.php index a5e358dd1..24ed685e4 100644 --- a/Tests/ParameterBag/ContainerBagTest.php +++ b/Tests/ParameterBag/ContainerBagTest.php @@ -26,15 +26,15 @@ class ContainerBagTest extends TestCase /** @var ContainerBag */ private $containerBag; - public function setUp() + protected function setUp() { - $this->parameterBag = new ParameterBag(array('foo' => 'value')); + $this->parameterBag = new ParameterBag(['foo' => 'value']); $this->containerBag = new ContainerBag(new Container($this->parameterBag)); } public function testGetAllParameters() { - $this->assertSame(array('foo' => 'value'), $this->containerBag->all()); + $this->assertSame(['foo' => 'value'], $this->containerBag->all()); } public function testHasAParameter() diff --git a/Tests/ParameterBag/EnvPlaceholderParameterBagTest.php b/Tests/ParameterBag/EnvPlaceholderParameterBagTest.php index 9abfb45d6..e7c88d2bb 100644 --- a/Tests/ParameterBag/EnvPlaceholderParameterBagTest.php +++ b/Tests/ParameterBag/EnvPlaceholderParameterBagTest.php @@ -137,7 +137,7 @@ public function testResolveThrowsOnBadDefaultValue() { $bag = new EnvPlaceholderParameterBag(); $bag->get('env(ARRAY_VAR)'); - $bag->set('env(ARRAY_VAR)', array()); + $bag->set('env(ARRAY_VAR)', []); $bag->resolve(); } @@ -158,7 +158,7 @@ public function testGetEnvAllowsNull() public function testGetThrowsOnBadDefaultValue() { $bag = new EnvPlaceholderParameterBag(); - $bag->set('env(ARRAY_VAR)', array()); + $bag->set('env(ARRAY_VAR)', []); $bag->get('env(ARRAY_VAR)'); $bag->resolve(); } diff --git a/Tests/ParameterBag/FrozenParameterBagTest.php b/Tests/ParameterBag/FrozenParameterBagTest.php index ef9a66f6c..b168e0c20 100644 --- a/Tests/ParameterBag/FrozenParameterBagTest.php +++ b/Tests/ParameterBag/FrozenParameterBagTest.php @@ -18,10 +18,10 @@ class FrozenParameterBagTest extends TestCase { public function testConstructor() { - $parameters = array( + $parameters = [ 'foo' => 'foo', 'bar' => 'bar', - ); + ]; $bag = new FrozenParameterBag($parameters); $this->assertEquals($parameters, $bag->all(), '__construct() takes an array of parameters as its first argument'); } @@ -31,7 +31,7 @@ public function testConstructor() */ public function testClear() { - $bag = new FrozenParameterBag(array()); + $bag = new FrozenParameterBag([]); $bag->clear(); } @@ -40,7 +40,7 @@ public function testClear() */ public function testSet() { - $bag = new FrozenParameterBag(array()); + $bag = new FrozenParameterBag([]); $bag->set('foo', 'bar'); } @@ -49,8 +49,8 @@ public function testSet() */ public function testAdd() { - $bag = new FrozenParameterBag(array()); - $bag->add(array()); + $bag = new FrozenParameterBag([]); + $bag->add([]); } /** @@ -58,7 +58,7 @@ public function testAdd() */ public function testRemove() { - $bag = new FrozenParameterBag(array('foo' => 'bar')); + $bag = new FrozenParameterBag(['foo' => 'bar']); $bag->remove('foo'); } } diff --git a/Tests/ParameterBag/ParameterBagTest.php b/Tests/ParameterBag/ParameterBagTest.php index c53decf8f..071cb39ce 100644 --- a/Tests/ParameterBag/ParameterBagTest.php +++ b/Tests/ParameterBag/ParameterBagTest.php @@ -12,45 +12,45 @@ namespace Symfony\Component\DependencyInjection\Tests\ParameterBag; use PHPUnit\Framework\TestCase; -use Symfony\Component\DependencyInjection\ParameterBag\ParameterBag; -use Symfony\Component\DependencyInjection\Exception\ParameterNotFoundException; use Symfony\Component\DependencyInjection\Exception\ParameterCircularReferenceException; +use Symfony\Component\DependencyInjection\Exception\ParameterNotFoundException; use Symfony\Component\DependencyInjection\Exception\RuntimeException; +use Symfony\Component\DependencyInjection\ParameterBag\ParameterBag; class ParameterBagTest extends TestCase { public function testConstructor() { - $bag = new ParameterBag($parameters = array( + $bag = new ParameterBag($parameters = [ 'foo' => 'foo', 'bar' => 'bar', - )); + ]); $this->assertEquals($parameters, $bag->all(), '__construct() takes an array of parameters as its first argument'); } public function testClear() { - $bag = new ParameterBag($parameters = array( + $bag = new ParameterBag($parameters = [ 'foo' => 'foo', 'bar' => 'bar', - )); + ]); $bag->clear(); - $this->assertEquals(array(), $bag->all(), '->clear() removes all parameters'); + $this->assertEquals([], $bag->all(), '->clear() removes all parameters'); } public function testRemove() { - $bag = new ParameterBag(array( + $bag = new ParameterBag([ 'foo' => 'foo', 'bar' => 'bar', - )); + ]); $bag->remove('foo'); - $this->assertEquals(array('bar' => 'bar'), $bag->all(), '->remove() removes a parameter'); + $this->assertEquals(['bar' => 'bar'], $bag->all(), '->remove() removes a parameter'); } public function testGetSet() { - $bag = new ParameterBag(array('foo' => 'bar')); + $bag = new ParameterBag(['foo' => 'bar']); $bag->set('bar', 'foo'); $this->assertEquals('foo', $bag->get('bar'), '->set() sets the value of a new parameter'); @@ -71,12 +71,12 @@ public function testGetSet() */ public function testGetThrowParameterNotFoundException($parameterKey, $exceptionMessage) { - $bag = new ParameterBag(array( + $bag = new ParameterBag([ 'foo' => 'foo', 'bar' => 'bar', 'baz' => 'baz', - 'fiz' => array('bar' => array('boo' => 12)), - )); + 'fiz' => ['bar' => ['boo' => 12]], + ]); if (method_exists($this, 'expectException')) { $this->expectException(ParameterNotFoundException::class); @@ -90,32 +90,32 @@ public function testGetThrowParameterNotFoundException($parameterKey, $exception public function provideGetThrowParameterNotFoundExceptionData() { - return array( - array('foo1', 'You have requested a non-existent parameter "foo1". Did you mean this: "foo"?'), - array('bag', 'You have requested a non-existent parameter "bag". Did you mean one of these: "bar", "baz"?'), - array('', 'You have requested a non-existent parameter "".'), + return [ + ['foo1', 'You have requested a non-existent parameter "foo1". Did you mean this: "foo"?'], + ['bag', 'You have requested a non-existent parameter "bag". Did you mean one of these: "bar", "baz"?'], + ['', 'You have requested a non-existent parameter "".'], - array('fiz.bar.boo', 'You have requested a non-existent parameter "fiz.bar.boo". You cannot access nested array items, do you want to inject "fiz" instead?'), - ); + ['fiz.bar.boo', 'You have requested a non-existent parameter "fiz.bar.boo". You cannot access nested array items, do you want to inject "fiz" instead?'], + ]; } public function testHas() { - $bag = new ParameterBag(array('foo' => 'bar')); + $bag = new ParameterBag(['foo' => 'bar']); $this->assertTrue($bag->has('foo'), '->has() returns true if a parameter is defined'); $this->assertFalse($bag->has('bar'), '->has() returns false if a parameter is not defined'); } public function testMixedCase() { - $bag = new ParameterBag(array( + $bag = new ParameterBag([ 'foo' => 'foo', 'bar' => 'bar', 'BAR' => 'baz', - )); + ]); $bag->remove('BAR'); - $this->assertEquals(array('foo' => 'foo', 'bar' => 'bar'), $bag->all()); + $this->assertEquals(['foo' => 'foo', 'bar' => 'bar'], $bag->all()); $bag->set('Foo', 'baz1'); $this->assertEquals('foo', $bag->get('foo')); @@ -124,29 +124,29 @@ public function testMixedCase() public function testResolveValue() { - $bag = new ParameterBag(array()); + $bag = new ParameterBag([]); $this->assertEquals('foo', $bag->resolveValue('foo'), '->resolveValue() returns its argument unmodified if no placeholders are found'); - $bag = new ParameterBag(array('foo' => 'bar')); + $bag = new ParameterBag(['foo' => 'bar']); $this->assertEquals('I\'m a bar', $bag->resolveValue('I\'m a %foo%'), '->resolveValue() replaces placeholders by their values'); - $this->assertEquals(array('bar' => 'bar'), $bag->resolveValue(array('%foo%' => '%foo%')), '->resolveValue() replaces placeholders in keys and values of arrays'); - $this->assertEquals(array('bar' => array('bar' => array('bar' => 'bar'))), $bag->resolveValue(array('%foo%' => array('%foo%' => array('%foo%' => '%foo%')))), '->resolveValue() replaces placeholders in nested arrays'); + $this->assertEquals(['bar' => 'bar'], $bag->resolveValue(['%foo%' => '%foo%']), '->resolveValue() replaces placeholders in keys and values of arrays'); + $this->assertEquals(['bar' => ['bar' => ['bar' => 'bar']]], $bag->resolveValue(['%foo%' => ['%foo%' => ['%foo%' => '%foo%']]]), '->resolveValue() replaces placeholders in nested arrays'); $this->assertEquals('I\'m a %%foo%%', $bag->resolveValue('I\'m a %%foo%%'), '->resolveValue() supports % escaping by doubling it'); $this->assertEquals('I\'m a bar %%foo bar', $bag->resolveValue('I\'m a %foo% %%foo %foo%'), '->resolveValue() supports % escaping by doubling it'); - $this->assertEquals(array('foo' => array('bar' => array('ding' => 'I\'m a bar %%foo %%bar'))), $bag->resolveValue(array('foo' => array('bar' => array('ding' => 'I\'m a bar %%foo %%bar')))), '->resolveValue() supports % escaping by doubling it'); + $this->assertEquals(['foo' => ['bar' => ['ding' => 'I\'m a bar %%foo %%bar']]], $bag->resolveValue(['foo' => ['bar' => ['ding' => 'I\'m a bar %%foo %%bar']]]), '->resolveValue() supports % escaping by doubling it'); - $bag = new ParameterBag(array('foo' => true)); + $bag = new ParameterBag(['foo' => true]); $this->assertTrue($bag->resolveValue('%foo%'), '->resolveValue() replaces arguments that are just a placeholder by their value without casting them to strings'); - $bag = new ParameterBag(array('foo' => null)); + $bag = new ParameterBag(['foo' => null]); $this->assertNull($bag->resolveValue('%foo%'), '->resolveValue() replaces arguments that are just a placeholder by their value without casting them to strings'); - $bag = new ParameterBag(array('foo' => 'bar', 'baz' => '%%%foo% %foo%%% %%foo%% %%%foo%%%')); + $bag = new ParameterBag(['foo' => 'bar', 'baz' => '%%%foo% %foo%%% %%foo%% %%%foo%%%']); $this->assertEquals('%%bar bar%% %%foo%% %%bar%%', $bag->resolveValue('%baz%'), '->resolveValue() replaces params placed besides escaped %'); - $bag = new ParameterBag(array('baz' => '%%s?%%s')); + $bag = new ParameterBag(['baz' => '%%s?%%s']); $this->assertEquals('%%s?%%s', $bag->resolveValue('%baz%'), '->resolveValue() is not replacing greedily'); - $bag = new ParameterBag(array()); + $bag = new ParameterBag([]); try { $bag->resolveValue('%foobar%'); $this->fail('->resolveValue() throws an InvalidArgumentException if a placeholder references a non-existent parameter'); @@ -161,7 +161,7 @@ public function testResolveValue() $this->assertEquals('You have requested a non-existent parameter "foobar".', $e->getMessage(), '->resolveValue() throws a ParameterNotFoundException if a placeholder references a non-existent parameter'); } - $bag = new ParameterBag(array('foo' => 'a %bar%', 'bar' => array())); + $bag = new ParameterBag(['foo' => 'a %bar%', 'bar' => []]); try { $bag->resolveValue('%foo%'); $this->fail('->resolveValue() throws a RuntimeException when a parameter embeds another non-string parameter'); @@ -169,7 +169,7 @@ public function testResolveValue() $this->assertEquals('A string value must be composed of strings and/or numbers, but found parameter "bar" of type array inside string value "a %bar%".', $e->getMessage(), '->resolveValue() throws a RuntimeException when a parameter embeds another non-string parameter'); } - $bag = new ParameterBag(array('foo' => '%bar%', 'bar' => '%foobar%', 'foobar' => '%foo%')); + $bag = new ParameterBag(['foo' => '%bar%', 'bar' => '%foobar%', 'foobar' => '%foo%']); try { $bag->resolveValue('%foo%'); $this->fail('->resolveValue() throws a ParameterCircularReferenceException when a parameter has a circular reference'); @@ -177,7 +177,7 @@ public function testResolveValue() $this->assertEquals('Circular reference detected for parameter "foo" ("foo" > "bar" > "foobar" > "foo").', $e->getMessage(), '->resolveValue() throws a ParameterCircularReferenceException when a parameter has a circular reference'); } - $bag = new ParameterBag(array('foo' => 'a %bar%', 'bar' => 'a %foobar%', 'foobar' => 'a %foo%')); + $bag = new ParameterBag(['foo' => 'a %bar%', 'bar' => 'a %foobar%', 'foobar' => 'a %foo%']); try { $bag->resolveValue('%foo%'); $this->fail('->resolveValue() throws a ParameterCircularReferenceException when a parameter has a circular reference'); @@ -185,13 +185,13 @@ public function testResolveValue() $this->assertEquals('Circular reference detected for parameter "foo" ("foo" > "bar" > "foobar" > "foo").', $e->getMessage(), '->resolveValue() throws a ParameterCircularReferenceException when a parameter has a circular reference'); } - $bag = new ParameterBag(array('host' => 'foo.bar', 'port' => 1337)); + $bag = new ParameterBag(['host' => 'foo.bar', 'port' => 1337]); $this->assertEquals('foo.bar:1337', $bag->resolveValue('%host%:%port%')); } public function testResolveIndicatesWhyAParameterIsNeeded() { - $bag = new ParameterBag(array('foo' => '%bar%')); + $bag = new ParameterBag(['foo' => '%bar%']); try { $bag->resolve(); @@ -199,7 +199,7 @@ public function testResolveIndicatesWhyAParameterIsNeeded() $this->assertEquals('The parameter "foo" has a dependency on a non-existent parameter "bar".', $e->getMessage()); } - $bag = new ParameterBag(array('foo' => '%bar%')); + $bag = new ParameterBag(['foo' => '%bar%']); try { $bag->resolve(); @@ -210,28 +210,28 @@ public function testResolveIndicatesWhyAParameterIsNeeded() public function testResolveUnescapesValue() { - $bag = new ParameterBag(array( - 'foo' => array('bar' => array('ding' => 'I\'m a bar %%foo %%bar')), + $bag = new ParameterBag([ + 'foo' => ['bar' => ['ding' => 'I\'m a bar %%foo %%bar']], 'bar' => 'I\'m a %%foo%%', - )); + ]); $bag->resolve(); $this->assertEquals('I\'m a %foo%', $bag->get('bar'), '->resolveValue() supports % escaping by doubling it'); - $this->assertEquals(array('bar' => array('ding' => 'I\'m a bar %foo %bar')), $bag->get('foo'), '->resolveValue() supports % escaping by doubling it'); + $this->assertEquals(['bar' => ['ding' => 'I\'m a bar %foo %bar']], $bag->get('foo'), '->resolveValue() supports % escaping by doubling it'); } public function testEscapeValue() { $bag = new ParameterBag(); - $bag->add(array( - 'foo' => $bag->escapeValue(array('bar' => array('ding' => 'I\'m a bar %foo %bar', 'zero' => null))), + $bag->add([ + 'foo' => $bag->escapeValue(['bar' => ['ding' => 'I\'m a bar %foo %bar', 'zero' => null]]), 'bar' => $bag->escapeValue('I\'m a %foo%'), - )); + ]); $this->assertEquals('I\'m a %%foo%%', $bag->get('bar'), '->escapeValue() escapes % by doubling it'); - $this->assertEquals(array('bar' => array('ding' => 'I\'m a bar %%foo %%bar', 'zero' => null)), $bag->get('foo'), '->escapeValue() escapes % by doubling it'); + $this->assertEquals(['bar' => ['ding' => 'I\'m a bar %%foo %%bar', 'zero' => null]], $bag->get('foo'), '->escapeValue() escapes % by doubling it'); } /** @@ -239,7 +239,7 @@ public function testEscapeValue() */ public function testResolveStringWithSpacesReturnsString($expected, $test, $description) { - $bag = new ParameterBag(array('foo' => 'bar')); + $bag = new ParameterBag(['foo' => 'bar']); try { $this->assertEquals($expected, $bag->resolveString($test), $description); @@ -250,11 +250,11 @@ public function testResolveStringWithSpacesReturnsString($expected, $test, $desc public function stringsWithSpacesProvider() { - return array( - array('bar', '%foo%', 'Parameters must be wrapped by %.'), - array('% foo %', '% foo %', 'Parameters should not have spaces.'), - array('{% set my_template = "foo" %}', '{% set my_template = "foo" %}', 'Twig-like strings are not parameters.'), - array('50% is less than 100%', '50% is less than 100%', 'Text between % signs is allowed, if there are spaces.'), - ); + return [ + ['bar', '%foo%', 'Parameters must be wrapped by %.'], + ['% foo %', '% foo %', 'Parameters should not have spaces.'], + ['{% set my_template = "foo" %}', '{% set my_template = "foo" %}', 'Twig-like strings are not parameters.'], + ['50% is less than 100%', '50% is less than 100%', 'Text between % signs is allowed, if there are spaces.'], + ]; } } diff --git a/Tests/ServiceLocatorTest.php b/Tests/ServiceLocatorTest.php index 56fac643e..aa9ebab68 100644 --- a/Tests/ServiceLocatorTest.php +++ b/Tests/ServiceLocatorTest.php @@ -20,11 +20,11 @@ class ServiceLocatorTest extends TestCase { public function testHas() { - $locator = new ServiceLocator(array( + $locator = new ServiceLocator([ 'foo' => function () { return 'bar'; }, 'bar' => function () { return 'baz'; }, function () { return 'dummy'; }, - )); + ]); $this->assertTrue($locator->has('foo')); $this->assertTrue($locator->has('bar')); @@ -33,10 +33,10 @@ function () { return 'dummy'; }, public function testGet() { - $locator = new ServiceLocator(array( + $locator = new ServiceLocator([ 'foo' => function () { return 'bar'; }, 'bar' => function () { return 'baz'; }, - )); + ]); $this->assertSame('bar', $locator->get('foo')); $this->assertSame('baz', $locator->get('bar')); @@ -45,13 +45,13 @@ public function testGet() public function testGetDoesNotMemoize() { $i = 0; - $locator = new ServiceLocator(array( + $locator = new ServiceLocator([ 'foo' => function () use (&$i) { ++$i; return 'bar'; }, - )); + ]); $this->assertSame('bar', $locator->get('foo')); $this->assertSame('bar', $locator->get('foo')); @@ -64,10 +64,10 @@ public function testGetDoesNotMemoize() */ public function testGetThrowsOnUndefinedService() { - $locator = new ServiceLocator(array( + $locator = new ServiceLocator([ 'foo' => function () { return 'bar'; }, 'bar' => function () { return 'baz'; }, - )); + ]); $locator->get('dummy'); } @@ -78,9 +78,9 @@ public function testGetThrowsOnUndefinedService() */ public function testThrowsOnUndefinedInternalService() { - $locator = new ServiceLocator(array( + $locator = new ServiceLocator([ 'foo' => function () use (&$locator) { return $locator->get('bar'); }, - )); + ]); $locator->get('foo'); } @@ -91,11 +91,11 @@ public function testThrowsOnUndefinedInternalService() */ public function testThrowsOnCircularReference() { - $locator = new ServiceLocator(array( + $locator = new ServiceLocator([ 'foo' => function () use (&$locator) { return $locator->get('bar'); }, 'bar' => function () use (&$locator) { return $locator->get('baz'); }, 'baz' => function () use (&$locator) { return $locator->get('bar'); }, - )); + ]); $locator->get('foo'); } @@ -109,18 +109,32 @@ public function testThrowsInServiceSubscriber() $container = new Container(); $container->set('foo', new \stdClass()); $subscriber = new SomeServiceSubscriber(); - $subscriber->container = new ServiceLocator(array('bar' => function () {})); + $subscriber->container = new ServiceLocator(['bar' => function () {}]); $subscriber->container = $subscriber->container->withContext('caller', $container); $subscriber->getFoo(); } + /** + * @expectedException \Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException + * @expectedExceptionMessage Service "foo" not found: even though it exists in the app's container, the container inside "foo" is a smaller service locator that is empty... Try using dependency injection instead. + */ + public function testGetThrowsServiceNotFoundException() + { + $container = new Container(); + $container->set('foo', new \stdClass()); + + $locator = new ServiceLocator([]); + $locator = $locator->withContext('foo', $container); + $locator->get('foo'); + } + public function testInvoke() { - $locator = new ServiceLocator(array( + $locator = new ServiceLocator([ 'foo' => function () { return 'bar'; }, 'bar' => function () { return 'baz'; }, - )); + ]); $this->assertSame('bar', $locator('foo')); $this->assertSame('baz', $locator('bar')); @@ -139,6 +153,6 @@ public function getFoo() public static function getSubscribedServices() { - return array('bar' => 'stdClass'); + return ['bar' => 'stdClass']; } } diff --git a/TypedReference.php b/TypedReference.php index 9d488ddbb..2bd25ab46 100644 --- a/TypedReference.php +++ b/TypedReference.php @@ -29,7 +29,7 @@ class TypedReference extends Reference public function __construct(string $id, string $type, $invalidBehavior = ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE) { if (\is_string($invalidBehavior) || 3 < \func_num_args()) { - @trigger_error(sprintf('The $requiringClass argument of "%s" is deprecated since Symfony 4.1.', __METHOD__), E_USER_DEPRECATED); + @trigger_error(sprintf('The $requiringClass argument of "%s()" is deprecated since Symfony 4.1.', __METHOD__), E_USER_DEPRECATED); $this->requiringClass = $invalidBehavior; $invalidBehavior = 3 < \func_num_args() ? \func_get_arg(3) : ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE; @@ -48,7 +48,7 @@ public function getType() */ public function getRequiringClass() { - @trigger_error(sprintf('The "%s" method is deprecated since Symfony 4.1.', __METHOD__), E_USER_DEPRECATED); + @trigger_error(sprintf('The "%s()" method is deprecated since Symfony 4.1.', __METHOD__), E_USER_DEPRECATED); return $this->requiringClass ?? ''; } @@ -58,7 +58,7 @@ public function getRequiringClass() */ public function canBeAutoregistered() { - @trigger_error(sprintf('The "%s" method is deprecated since Symfony 4.1.', __METHOD__), E_USER_DEPRECATED); + @trigger_error(sprintf('The "%s()" method is deprecated since Symfony 4.1.', __METHOD__), E_USER_DEPRECATED); return $this->requiringClass && (false !== $i = strpos($this->type, '\\')) && 0 === strncasecmp($this->type, $this->requiringClass, 1 + $i); } diff --git a/phpunit.xml.dist b/phpunit.xml.dist index 781f767d5..21dee2a80 100644 --- a/phpunit.xml.dist +++ b/phpunit.xml.dist @@ -1,7 +1,7 @@