Merge branch '3.4' into 4.1

* 3.4:
  [DI] configure inlined services before injecting them when dumping the container
  Consistently throw exceptions on a single line
  fix fopen calls
  Update .editorconfig
This commit is contained in:
Nicolas Grekas 2018-09-08 15:24:10 +02:00
commit 6fec32c0d0
67 changed files with 319 additions and 828 deletions

View File

@ -3,8 +3,17 @@ root = true
; Unix-style newlines
[*]
charset = utf-8
end_of_line = LF
insert_final_newline = true
trim_trailing_whitespace = true
[*.php]
[*.{php,html,twig}]
indent_style = space
indent_size = 4
[*.md]
max_line_length = 80
[COMMIT_EDITMSG]
max_line_length = 0

View File

@ -202,11 +202,7 @@ abstract class DoctrineType extends AbstractType
$em = $this->registry->getManagerForClass($options['class']);
if (null === $em) {
throw new RuntimeException(sprintf(
'Class "%s" seems not to be a managed Doctrine entity. '.
'Did you forget to map it?',
$options['class']
));
throw new RuntimeException(sprintf('Class "%s" seems not to be a managed Doctrine entity. Did you forget to map it?', $options['class']));
}
return $em;

View File

@ -170,14 +170,7 @@ class Router extends BaseRouter implements WarmableInterface, ServiceSubscriberI
return (string) $resolved;
}
throw new RuntimeException(sprintf(
'The container parameter "%s", used in the route configuration value "%s", '.
'must be a string or numeric, but it is of type %s.',
$match[1],
$value,
\gettype($resolved)
)
);
throw new RuntimeException(sprintf('The container parameter "%s", used in the route configuration value "%s", must be a string or numeric, but it is of type %s.', $match[1], $value, \gettype($resolved)));
}, $value);
return str_replace('%%', '%', $escapedValue);

View File

@ -97,10 +97,7 @@ class GuardAuthenticationFactory implements SecurityFactoryInterface
if ($defaultEntryPointId) {
// explode if they've configured the entry_point, but there is already one
if ($config['entry_point']) {
throw new \LogicException(sprintf(
'The guard authentication provider cannot use the "%s" entry_point because another entry point is already configured by another provider! Either remove the other provider or move the entry_point configuration as a root key under your firewall (i.e. at the same level as "guard").',
$config['entry_point']
));
throw new \LogicException(sprintf('The guard authentication provider cannot use the "%s" entry_point because another entry point is already configured by another provider! Either remove the other provider or move the entry_point configuration as a root key under your firewall (i.e. at the same level as "guard").', $config['entry_point']));
}
return $defaultEntryPointId;
@ -118,9 +115,6 @@ class GuardAuthenticationFactory implements SecurityFactoryInterface
}
// we have multiple entry points - we must ask them to configure one
throw new \LogicException(sprintf(
'Because you have multiple guard configurators, you need to set the "guard.entry_point" key to one of your configurators (%s)',
implode(', ', $authenticatorIds)
));
throw new \LogicException(sprintf('Because you have multiple guard configurators, you need to set the "guard.entry_point" key to one of your configurators (%s)', implode(', ', $authenticatorIds)));
}
}

View File

@ -219,15 +219,13 @@ class ArrayNode extends BaseNode implements PrototypeNodeInterface
protected function finalizeValue($value)
{
if (false === $value) {
$msg = sprintf('Unsetting key for path "%s", value: %s', $this->getPath(), json_encode($value));
throw new UnsetKeyException($msg);
throw new UnsetKeyException(sprintf('Unsetting key for path "%s", value: %s', $this->getPath(), json_encode($value)));
}
foreach ($this->children as $name => $child) {
if (!array_key_exists($name, $value)) {
if ($child->isRequired()) {
$msg = sprintf('The child node "%s" at path "%s" must be configured.', $name, $this->getPath());
$ex = new InvalidConfigurationException($msg);
$ex = new InvalidConfigurationException(sprintf('The child node "%s" at path "%s" must be configured.', $name, $this->getPath()));
$ex->setPath($this->getPath());
throw $ex;
@ -264,11 +262,7 @@ class ArrayNode extends BaseNode implements PrototypeNodeInterface
protected function validateType($value)
{
if (!\is_array($value) && (!$this->allowFalse || false !== $value)) {
$ex = new InvalidTypeException(sprintf(
'Invalid type for path "%s". Expected array, but got %s',
$this->getPath(),
\gettype($value)
));
$ex = new InvalidTypeException(sprintf('Invalid type for path "%s". Expected array, but got %s', $this->getPath(), \gettype($value)));
if ($hint = $this->getInfo()) {
$ex->addHint($hint);
}
@ -307,8 +301,7 @@ class ArrayNode extends BaseNode implements PrototypeNodeInterface
// if extra fields are present, throw exception
if (\count($value) && !$this->ignoreExtraKeys) {
$msg = sprintf('Unrecognized option%s "%s" under "%s"', 1 === \count($value) ? '' : 's', implode(', ', array_keys($value)), $this->getPath());
$ex = new InvalidConfigurationException($msg);
$ex = new InvalidConfigurationException(sprintf('Unrecognized option%s "%s" under "%s"', 1 === \count($value) ? '' : 's', implode(', ', array_keys($value)), $this->getPath()));
$ex->setPath($this->getPath());
throw $ex;
@ -365,13 +358,7 @@ class ArrayNode extends BaseNode implements PrototypeNodeInterface
// no conflict
if (!array_key_exists($k, $leftSide)) {
if (!$this->allowNewKeys) {
$ex = new InvalidConfigurationException(sprintf(
'You are not allowed to define new elements for path "%s". '
.'Please define all elements for this path in one config file. '
.'If you are trying to overwrite an element, make sure you redefine it '
.'with the same name.',
$this->getPath()
));
$ex = new InvalidConfigurationException(sprintf('You are not allowed to define new elements for path "%s". Please define all elements for this path in one config file. If you are trying to overwrite an element, make sure you redefine it with the same name.', $this->getPath()));
$ex->setPath($this->getPath());
throw $ex;

View File

@ -288,12 +288,7 @@ abstract class BaseNode implements NodeInterface
final public function merge($leftSide, $rightSide)
{
if (!$this->allowOverwrite) {
throw new ForbiddenOverwriteException(sprintf(
'Configuration path "%s" cannot be overwritten. You have to '
.'define all options for this path, and any of its sub-paths in '
.'one configuration section.',
$this->getPath()
));
throw new ForbiddenOverwriteException(sprintf('Configuration path "%s" cannot be overwritten. You have to define all options for this path, and any of its sub-paths in one configuration section.', $this->getPath()));
}
if ($leftSide !== $leftPlaceholders = self::resolvePlaceholderValue($leftSide)) {

View File

@ -26,11 +26,7 @@ class BooleanNode extends ScalarNode
protected function validateType($value)
{
if (!\is_bool($value)) {
$ex = new InvalidTypeException(sprintf(
'Invalid type for path "%s". Expected boolean, but got %s.',
$this->getPath(),
\gettype($value)
));
$ex = new InvalidTypeException(sprintf('Invalid type for path "%s". Expected boolean, but got %s.', $this->getPath(), \gettype($value)));
if ($hint = $this->getInfo()) {
$ex->addHint($hint);
}

View File

@ -468,9 +468,7 @@ class ArrayNodeDefinition extends NodeDefinition implements ParentNodeDefinition
$path = $node->getPath();
if (null !== $this->key) {
throw new InvalidDefinitionException(
sprintf('->useAttributeAsKey() is not applicable to concrete nodes at path "%s"', $path)
);
throw new InvalidDefinitionException(sprintf('->useAttributeAsKey() is not applicable to concrete nodes at path "%s"', $path));
}
if (false === $this->allowEmptyValue) {
@ -478,21 +476,15 @@ class ArrayNodeDefinition extends NodeDefinition implements ParentNodeDefinition
}
if (true === $this->atLeastOne) {
throw new InvalidDefinitionException(
sprintf('->requiresAtLeastOneElement() is not applicable to concrete nodes at path "%s"', $path)
);
throw new InvalidDefinitionException(sprintf('->requiresAtLeastOneElement() is not applicable to concrete nodes at path "%s"', $path));
}
if ($this->default) {
throw new InvalidDefinitionException(
sprintf('->defaultValue() is not applicable to concrete nodes at path "%s"', $path)
);
throw new InvalidDefinitionException(sprintf('->defaultValue() is not applicable to concrete nodes at path "%s"', $path));
}
if (false !== $this->addDefaultChildren) {
throw new InvalidDefinitionException(
sprintf('->addDefaultChildrenIfNoneSet() is not applicable to concrete nodes at path "%s"', $path)
);
throw new InvalidDefinitionException(sprintf('->addDefaultChildrenIfNoneSet() is not applicable to concrete nodes at path "%s"', $path));
}
}
@ -506,28 +498,20 @@ class ArrayNodeDefinition extends NodeDefinition implements ParentNodeDefinition
$path = $node->getPath();
if ($this->addDefaults) {
throw new InvalidDefinitionException(
sprintf('->addDefaultsIfNotSet() is not applicable to prototype nodes at path "%s"', $path)
);
throw new InvalidDefinitionException(sprintf('->addDefaultsIfNotSet() is not applicable to prototype nodes at path "%s"', $path));
}
if (false !== $this->addDefaultChildren) {
if ($this->default) {
throw new InvalidDefinitionException(
sprintf('A default value and default children might not be used together at path "%s"', $path)
);
throw new InvalidDefinitionException(sprintf('A default value and default children might not be used together at path "%s"', $path));
}
if (null !== $this->key && (null === $this->addDefaultChildren || \is_int($this->addDefaultChildren) && $this->addDefaultChildren > 0)) {
throw new InvalidDefinitionException(
sprintf('->addDefaultChildrenIfNoneSet() should set default children names as ->useAttributeAsKey() is used at path "%s"', $path)
);
throw new InvalidDefinitionException(sprintf('->addDefaultChildrenIfNoneSet() should set default children names as ->useAttributeAsKey() is used at path "%s"', $path));
}
if (null === $this->key && (\is_string($this->addDefaultChildren) || \is_array($this->addDefaultChildren))) {
throw new InvalidDefinitionException(
sprintf('->addDefaultChildrenIfNoneSet() might not set default children names as ->useAttributeAsKey() is not used at path "%s"', $path)
);
throw new InvalidDefinitionException(sprintf('->addDefaultChildrenIfNoneSet() might not set default children names as ->useAttributeAsKey() is not used at path "%s"', $path));
}
}
}

View File

@ -43,11 +43,7 @@ class EnumNode extends ScalarNode
$value = parent::finalizeValue($value);
if (!\in_array($value, $this->values, true)) {
$ex = new InvalidConfigurationException(sprintf(
'The value %s is not allowed for path "%s". Permissible values: %s',
json_encode($value),
$this->getPath(),
implode(', ', array_map('json_encode', $this->values))));
$ex = new InvalidConfigurationException(sprintf('The value %s is not allowed for path "%s". Permissible values: %s', json_encode($value), $this->getPath(), implode(', ', array_map('json_encode', $this->values))));
$ex->setPath($this->getPath());
throw $ex;

View File

@ -185,8 +185,7 @@ class PrototypedArrayNode extends ArrayNode
protected function finalizeValue($value)
{
if (false === $value) {
$msg = sprintf('Unsetting key for path "%s", value: %s', $this->getPath(), json_encode($value));
throw new UnsetKeyException($msg);
throw new UnsetKeyException(sprintf('Unsetting key for path "%s", value: %s', $this->getPath(), json_encode($value)));
}
foreach ($value as $k => $v) {
@ -199,8 +198,7 @@ class PrototypedArrayNode extends ArrayNode
}
if (\count($value) < $this->minNumberOfElements) {
$msg = sprintf('The path "%s" should have at least %d element(s) defined.', $this->getPath(), $this->minNumberOfElements);
$ex = new InvalidConfigurationException($msg);
$ex = new InvalidConfigurationException(sprintf('The path "%s" should have at least %d element(s) defined.', $this->getPath(), $this->minNumberOfElements));
$ex->setPath($this->getPath());
throw $ex;
@ -232,8 +230,7 @@ class PrototypedArrayNode extends ArrayNode
foreach ($value as $k => $v) {
if (null !== $this->keyAttribute && \is_array($v)) {
if (!isset($v[$this->keyAttribute]) && \is_int($k) && !$isAssoc) {
$msg = sprintf('The attribute "%s" must be set for path "%s".', $this->keyAttribute, $this->getPath());
$ex = new InvalidConfigurationException($msg);
$ex = new InvalidConfigurationException(sprintf('The attribute "%s" must be set for path "%s".', $this->keyAttribute, $this->getPath()));
$ex->setPath($this->getPath());
throw $ex;
@ -262,8 +259,7 @@ class PrototypedArrayNode extends ArrayNode
}
if (array_key_exists($k, $normalized)) {
$msg = sprintf('Duplicate key "%s" for path "%s".', $k, $this->getPath());
$ex = new DuplicateKeyException($msg);
$ex = new DuplicateKeyException(sprintf('Duplicate key "%s" for path "%s".', $k, $this->getPath()));
$ex->setPath($this->getPath());
throw $ex;
@ -314,11 +310,7 @@ class PrototypedArrayNode extends ArrayNode
// no conflict
if (!array_key_exists($k, $leftSide)) {
if (!$this->allowNewKeys) {
$ex = new InvalidConfigurationException(sprintf(
'You are not allowed to define new elements for path "%s". '.
'Please define all elements for this path in one config file.',
$this->getPath()
));
$ex = new InvalidConfigurationException(sprintf('You are not allowed to define new elements for path "%s". Please define all elements for this path in one config file.', $this->getPath()));
$ex->setPath($this->getPath());
throw $ex;

View File

@ -33,11 +33,7 @@ class ScalarNode extends VariableNode
protected function validateType($value)
{
if (!is_scalar($value) && null !== $value) {
$ex = new InvalidTypeException(sprintf(
'Invalid type for path "%s". Expected scalar, but got %s.',
$this->getPath(),
\gettype($value)
));
$ex = new InvalidTypeException(sprintf('Invalid type for path "%s". Expected scalar, but got %s.', $this->getPath(), \gettype($value)));
if ($hint = $this->getInfo()) {
$ex->addHint($hint);
}

View File

@ -82,11 +82,7 @@ class VariableNode extends BaseNode implements PrototypeNodeInterface
protected function finalizeValue($value)
{
if (!$this->allowEmptyValue && $this->isValueEmpty($value)) {
$ex = new InvalidConfigurationException(sprintf(
'The path "%s" cannot contain an empty value, but got %s.',
$this->getPath(),
json_encode($value)
));
$ex = new InvalidConfigurationException(sprintf('The path "%s" cannot contain an empty value, but got %s.', $this->getPath(), json_encode($value)));
if ($hint = $this->getInfo()) {
$ex->addHint($hint);
}

View File

@ -90,11 +90,7 @@ class OutputFormatterStyle implements OutputFormatterStyleInterface
}
if (!isset(static::$availableForegroundColors[$color])) {
throw new InvalidArgumentException(sprintf(
'Invalid foreground color specified: "%s". Expected one of (%s)',
$color,
implode(', ', array_keys(static::$availableForegroundColors))
));
throw new InvalidArgumentException(sprintf('Invalid foreground color specified: "%s". Expected one of (%s)', $color, implode(', ', array_keys(static::$availableForegroundColors))));
}
$this->foreground = static::$availableForegroundColors[$color];
@ -116,11 +112,7 @@ class OutputFormatterStyle implements OutputFormatterStyleInterface
}
if (!isset(static::$availableBackgroundColors[$color])) {
throw new InvalidArgumentException(sprintf(
'Invalid background color specified: "%s". Expected one of (%s)',
$color,
implode(', ', array_keys(static::$availableBackgroundColors))
));
throw new InvalidArgumentException(sprintf('Invalid background color specified: "%s". Expected one of (%s)', $color, implode(', ', array_keys(static::$availableBackgroundColors))));
}
$this->background = static::$availableBackgroundColors[$color];
@ -136,11 +128,7 @@ class OutputFormatterStyle implements OutputFormatterStyleInterface
public function setOption($option)
{
if (!isset(static::$availableOptions[$option])) {
throw new InvalidArgumentException(sprintf(
'Invalid option specified: "%s". Expected one of (%s)',
$option,
implode(', ', array_keys(static::$availableOptions))
));
throw new InvalidArgumentException(sprintf('Invalid option specified: "%s". Expected one of (%s)', $option, implode(', ', array_keys(static::$availableOptions))));
}
if (!\in_array(static::$availableOptions[$option], $this->options)) {
@ -158,11 +146,7 @@ class OutputFormatterStyle implements OutputFormatterStyleInterface
public function unsetOption($option)
{
if (!isset(static::$availableOptions[$option])) {
throw new InvalidArgumentException(sprintf(
'Invalid option specified: "%s". Expected one of (%s)',
$option,
implode(', ', array_keys(static::$availableOptions))
));
throw new InvalidArgumentException(sprintf('Invalid option specified: "%s". Expected one of (%s)', $option, implode(', ', array_keys(static::$availableOptions))));
}
$pos = array_search(static::$availableOptions[$option], $this->options);

View File

@ -133,10 +133,7 @@ class FunctionExtension extends AbstractExtension
$arguments = $function->getArguments();
foreach ($arguments as $token) {
if (!($token->isString() || $token->isIdentifier())) {
throw new ExpressionErrorException(
'Expected a single string or identifier for :contains(), got '
.implode(', ', $arguments)
);
throw new ExpressionErrorException('Expected a single string or identifier for :contains(), got '.implode(', ', $arguments));
}
}
@ -154,10 +151,7 @@ class FunctionExtension extends AbstractExtension
$arguments = $function->getArguments();
foreach ($arguments as $token) {
if (!($token->isString() || $token->isIdentifier())) {
throw new ExpressionErrorException(
'Expected a single string or identifier for :lang(), got '
.implode(', ', $arguments)
);
throw new ExpressionErrorException('Expected a single string or identifier for :lang(), got '.implode(', ', $arguments));
}
}

View File

@ -158,10 +158,7 @@ class HtmlExtension extends AbstractExtension
$arguments = $function->getArguments();
foreach ($arguments as $token) {
if (!($token->isString() || $token->isIdentifier())) {
throw new ExpressionErrorException(
'Expected a single string or identifier for :lang(), got '
.implode(', ', $arguments)
);
throw new ExpressionErrorException('Expected a single string or identifier for :lang(), got '.implode(', ', $arguments));
}
}

View File

@ -66,13 +66,7 @@ class CheckDefinitionValidityPass implements CompilerPassInterface
));
}
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

View File

@ -34,12 +34,7 @@ class CheckReferenceValidityPass extends AbstractRecursivePass
$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));
}
}

View File

@ -56,7 +56,9 @@ class PhpDumper extends Dumper
private $definitionVariables;
private $referenceVariables;
private $variableCount;
private $reservedVariables = array('instance', 'class');
private $inlinedDefinitions;
private $serviceCalls;
private $reservedVariables = array('instance', 'class', 'this');
private $expressionLanguage;
private $targetDirRegex;
private $targetDirMaxMatches;
@ -301,59 +303,6 @@ EOF;
return $this->proxyDumper;
}
private function addServiceLocalTempVariables(string $cId, Definition $definition, \SplObjectStorage $inlinedDefinitions, array $serviceCalls, bool $preInstance = false): string
{
$calls = array();
foreach ($inlinedDefinitions as $def) {
if ($preInstance && !$inlinedDefinitions[$def][1]) {
continue;
}
$this->getServiceCallsFromArguments(array($def->getArguments(), $def->getFactory()), $calls, $preInstance, $cId);
if ($def !== $definition) {
$arguments = array($def->getProperties(), $def->getMethodCalls(), $def->getConfigurator());
$this->getServiceCallsFromArguments($arguments, $calls, $preInstance && !$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 => list($callCount)) {
if ('service_container' === $id || $id === $cId || isset($this->referenceVariables[$id])) {
continue;
}
if ($callCount <= 1 && $serviceCalls[$id][0] <= 1) {
continue;
}
$name = $this->getNextVariableName();
$this->referenceVariables[$id] = new Variable($name);
$reference = ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE >= $serviceCalls[$id][1] ? new Reference($id, $serviceCalls[$id][1]) : null;
$code .= sprintf(" \$%s = %s;\n", $name, $this->getServiceCall($id, $reference));
}
if ('' !== $code) {
if ($preInstance) {
$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) {
@ -433,19 +382,19 @@ EOTXT
}
}
private function addServiceInclude(string $cId, Definition $definition, \SplObjectStorage $inlinedDefinitions, array $serviceCalls): string
private function addServiceInclude(string $cId, Definition $definition): string
{
$code = '';
if ($this->inlineRequires && !$this->isHotPath($definition)) {
$lineage = array();
foreach ($inlinedDefinitions as $def) {
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);
}
}
foreach ($serviceCalls as $id => list($callCount, $behavior)) {
foreach ($this->serviceCalls as $id => list($callCount, $behavior)) {
if ('service_container' !== $id && $id !== $cId
&& ContainerInterface::IGNORE_ON_UNINITIALIZED_REFERENCE !== $behavior
&& $this->container->has($id)
@ -461,7 +410,7 @@ EOTXT
}
}
foreach ($inlinedDefinitions as $def) {
foreach ($this->inlinedDefinitions as $def) {
if ($file = $def->getFile()) {
$code .= sprintf(" include_once %s;\n", $this->dumpValue($file));
}
@ -474,57 +423,6 @@ EOTXT
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, bool $preInstance = false): string
{
$code = '';
foreach ($inlinedDefinitions as $def) {
if ($definition === $def || isset($this->definitionVariables[$def])) {
continue;
}
if ($inlinedDefinitions[$def][0] <= 1 && !$def->getMethodCalls() && !$def->getProperties() && !$def->getConfigurator() && false === strpos($this->dumpValue($def->getClass()), '$')) {
continue;
}
if ($preInstance && !$inlinedDefinitions[$def][1]) {
continue;
}
$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, '...', $id));
}
$code .= $this->addNewInstance($def, '$'.$name, ' = ', $id);
if (!$this->hasReference($id, array($def->getProperties(), $def->getMethodCalls(), $def->getConfigurator()), true, $inlinedDefinitions)) {
$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
@ -553,14 +451,7 @@ EOTXT
$instantiation .= ' = ';
}
$code = $this->addNewInstance($definition, $return, $instantiation, $id);
$this->referenceVariables[$id] = new Variable('instance');
if (!$isSimpleInstance) {
$code .= "\n";
}
return $code;
return $this->addNewInstance($definition, $return, $instantiation, $id);
}
private function isTrivialInstance(Definition $definition): bool
@ -620,7 +511,7 @@ EOTXT
return $calls;
}
private function addServiceProperties(Definition $definition, $variableName = 'instance')
private function addServiceProperties(Definition $definition, string $variableName = 'instance')
{
$code = '';
foreach ($definition->getProperties() as $name => $value) {
@ -630,36 +521,6 @@ EOTXT
return $code;
}
/**
* @throws ServiceCircularReferenceException when the container contains a circular reference
*/
private function addServiceInlinedDefinitionsSetup(string $id, Definition $definition, \SplObjectStorage $inlinedDefinitions, bool $isSimpleInstance): string
{
$code = '';
foreach ($inlinedDefinitions as $def) {
if ($definition === $def || !$this->hasReference($id, array($def->getProperties(), $def->getMethodCalls(), $def->getConfigurator()), true, $inlinedDefinitions)) {
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, '...', $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()) {
@ -693,6 +554,7 @@ EOTXT
$this->definitionVariables = new \SplObjectStorage();
$this->referenceVariables = array();
$this->variableCount = 0;
$this->definitionVariables[$definition] = $this->referenceVariables[$id] = new Variable('instance');
$return = array();
@ -758,26 +620,10 @@ EOF;
return $asFile ? substr($code, 8).$e : $code.' '.$e." }\n";
}
$inlinedDefinitions = $this->getDefinitionsFromArguments(array($definition));
$constructorDefinitions = $this->getDefinitionsFromArguments(array($definition->getArguments(), $definition->getFactory()));
unset($constructorDefinitions[$definition]); // ensures $definition will be last
$otherDefinitions = new \SplObjectStorage();
$serviceCalls = array();
$this->serviceCalls = array();
$this->inlinedDefinitions = $this->getDefinitionsFromArguments(array($definition), null, $this->serviceCalls);
foreach ($inlinedDefinitions as $def) {
if ($def === $definition || isset($constructorDefinitions[$def])) {
$constructorDefinitions[$def] = $inlinedDefinitions[$def];
} else {
$otherDefinitions[$def] = $inlinedDefinitions[$def];
}
$arguments = array($def->getArguments(), $def->getFactory(), $def->getProperties(), $def->getMethodCalls(), $def->getConfigurator());
$this->getServiceCallsFromArguments($arguments, $serviceCalls, false, $id);
}
$isSimpleInstance = !$definition->getProperties() && !$definition->getMethodCalls() && !$definition->getConfigurator();
$preInstance = isset($this->circularReferences[$id]) && !$this->getProxyDumper()->isProxyCandidate($definition) && $definition->isShared();
$code .= $this->addServiceInclude($id, $definition, $inlinedDefinitions, $serviceCalls);
$code .= $this->addServiceInclude($id, $definition);
if ($this->getProxyDumper()->isProxyCandidate($definition)) {
$factoryCode = $asFile ? "\$this->load('%s.php', false)" : '$this->%s(false)';
@ -788,20 +634,22 @@ EOF;
$code .= sprintf(" @trigger_error(%s, E_USER_DEPRECATED);\n\n", $this->export($definition->getDeprecationMessage($id)));
}
$code .=
$this->addServiceLocalTempVariables($id, $definition, $constructorDefinitions, $serviceCalls, $preInstance).
$this->addServiceInlinedDefinitions($id, $definition, $constructorDefinitions, $isSimpleInstance, $preInstance).
$this->addServiceInstance($id, $definition, $isSimpleInstance).
$this->addServiceLocalTempVariables($id, $definition, $constructorDefinitions->offsetUnset($definition) ?: $constructorDefinitions, $serviceCalls).
$this->addServiceLocalTempVariables($id, $definition, $otherDefinitions, $serviceCalls).
$this->addServiceInlinedDefinitions($id, $definition, $constructorDefinitions, $isSimpleInstance).
$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" : '')
;
$head = $tail = '';
$arguments = array($definition->getArguments(), $definition->getFactory());
$this->addInlineVariables($head, $tail, $id, $arguments, true);
$code .= '' !== $head ? $head."\n" : '';
if ($arguments = array_filter(array($definition->getProperties(), $definition->getMethodCalls(), $definition->getConfigurator()))) {
$this->addInlineVariables($tail, $tail, $id, $arguments, false);
$tail .= '' !== $tail ? "\n" : '';
$tail .= $this->addServiceProperties($definition);
$tail .= $this->addServiceMethodCalls($definition);
$tail .= $this->addServiceConfigurator($definition);
}
$code .= $this->addServiceInstance($id, $definition, '' === $tail)
.('' !== $tail ? "\n".$tail."\n return \$instance;\n" : '');
if ($asFile) {
$code = implode("\n", array_map(function ($line) { return $line ? substr($line, 8) : $line; }, explode("\n", $code)));
@ -809,12 +657,108 @@ EOF;
$code .= " }\n";
}
$this->definitionVariables = null;
$this->referenceVariables = null;
$this->definitionVariables = $this->inlinedDefinitions = null;
$this->referenceVariables = $this->serviceCalls = null;
return $code;
}
private function addInlineVariables(string &$head, string &$tail, string $id, array $arguments, bool $forConstructor): bool
{
$hasSelfRef = false;
foreach ($arguments as $argument) {
if (\is_array($argument)) {
$hasSelfRef = $this->addInlineVariables($head, $tail, $id, $argument, $forConstructor) || $hasSelfRef;
} elseif ($argument instanceof Reference) {
$hasSelfRef = $this->addInlineReference($head, $tail, $id, $argument, $forConstructor) || $hasSelfRef;
} elseif ($argument instanceof Definition) {
$hasSelfRef = $this->addInlineService($head, $tail, $id, $argument, $forConstructor) || $hasSelfRef;
}
}
return $hasSelfRef;
}
private function addInlineReference(string &$head, string &$tail, string $id, string $targetId, bool $forConstructor): bool
{
if ('service_container' === $targetId || isset($this->referenceVariables[$targetId])) {
return isset($this->circularReferences[$id][$targetId]);
}
list($callCount, $behavior) = $this->serviceCalls[$targetId];
if (2 > $callCount && (!$forConstructor || !isset($this->circularReferences[$id][$targetId]))) {
return isset($this->circularReferences[$id][$targetId]);
}
$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 (!isset($this->circularReferences[$id][$targetId])) {
$head .= $code;
return false;
}
if (!$forConstructor) {
$tail .= $code;
return true;
}
$head .= $code.sprintf(<<<'EOTXT'
if (isset($this->%s['%s'])) {
return $this->%1$s['%2$s'];
}
EOTXT
,
$this->container->getDefinition($id)->isPublic() ? 'services' : 'privates',
$id
);
return false;
}
private function addInlineService(string &$head, string &$tail, string $id, Definition $definition, bool $forConstructor): bool
{
if (isset($this->definitionVariables[$definition])) {
return false;
}
$arguments = array($definition->getArguments(), $definition->getFactory());
if (2 > $this->inlinedDefinitions[$definition] && !$definition->getMethodCalls() && !$definition->getProperties() && !$definition->getConfigurator() && false === strpos($this->dumpValue($definition->getClass()), '$')) {
return $this->addInlineVariables($head, $tail, $id, $arguments, $forConstructor);
}
$name = $this->getNextVariableName();
$this->definitionVariables[$definition] = new Variable($name);
$code = '';
$hasSelfRef = $this->addInlineVariables($code, $tail, $id, $arguments, $forConstructor);
$code .= $this->addNewInstance($definition, '$'.$name, ' = ', $id);
$hasSelfRef ? $tail .= ('' !== $tail ? "\n" : '').$code : $head .= ('' !== $head ? "\n" : '').$code;
$code = '';
$arguments = array($definition->getProperties(), $definition->getMethodCalls(), $definition->getConfigurator());
$hasSelfRef = $this->addInlineVariables($code, $tail, $id, $arguments, false) || $hasSelfRef;
$code .= $this->addServiceProperties($definition, $name);
$code .= $this->addServiceMethodCalls($definition, $name);
$code .= $this->addServiceConfigurator($definition, $name);
if ('' !== $code) {
$hasSelfRef ? $tail .= ('' !== $tail ? "\n" : '').$code : $head .= $code;
}
return $hasSelfRef;
}
private function addServices(): string
{
$publicServices = $privateServices = '';
@ -1377,26 +1321,7 @@ EOF;
return implode(' && ', $conditions);
}
private function getServiceCallsFromArguments(array $arguments, array &$calls, bool $preInstance, string $callerId)
{
foreach ($arguments as $argument) {
if (\is_array($argument)) {
$this->getServiceCallsFromArguments($argument, $calls, $preInstance, $callerId);
} elseif ($argument instanceof Reference) {
$id = (string) $argument;
if (!isset($calls[$id])) {
$calls[$id] = array((int) ($preInstance && isset($this->circularReferences[$callerId][$id])), $argument->getInvalidBehavior());
} else {
$calls[$id][1] = min($calls[$id][1], $argument->getInvalidBehavior());
}
++$calls[$id][0];
}
}
}
private function getDefinitionsFromArguments(array $arguments, bool $isConstructorArgument = true, \SplObjectStorage $definitions = null): \SplObjectStorage
private function getDefinitionsFromArguments(array $arguments, \SplObjectStorage $definitions = null, array &$calls = array()): \SplObjectStorage
{
if (null === $definitions) {
$definitions = new \SplObjectStorage();
@ -1404,78 +1329,31 @@ EOF;
foreach ($arguments as $argument) {
if (\is_array($argument)) {
$this->getDefinitionsFromArguments($argument, $isConstructorArgument, $definitions);
$this->getDefinitionsFromArguments($argument, $definitions, $calls);
} elseif ($argument instanceof Reference) {
$id = (string) $argument;
if (!isset($calls[$id])) {
$calls[$id] = array(0, $argument->getInvalidBehavior());
} else {
$calls[$id][1] = min($calls[$id][1], $argument->getInvalidBehavior());
}
++$calls[$id][0];
} elseif (!$argument instanceof Definition) {
// no-op
} elseif (isset($definitions[$argument])) {
$def = $definitions[$argument];
$definitions[$argument] = array(1 + $def[0], $isConstructorArgument || $def[1]);
$definitions[$argument] = 1 + $definitions[$argument];
} else {
$definitions[$argument] = array(1, $isConstructorArgument);
$this->getDefinitionsFromArguments($argument->getArguments(), $isConstructorArgument, $definitions);
$this->getDefinitionsFromArguments(array($argument->getFactory()), $isConstructorArgument, $definitions);
$this->getDefinitionsFromArguments($argument->getProperties(), false, $definitions);
$this->getDefinitionsFromArguments($argument->getMethodCalls(), false, $definitions);
$this->getDefinitionsFromArguments(array($argument->getConfigurator()), false, $definitions);
// move current definition last in the list
$def = $definitions[$argument];
unset($definitions[$argument]);
$definitions[$argument] = $def;
$definitions[$argument] = 1;
$arguments = array($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, \SplObjectStorage $inlinedDefinitions = null, 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, $inlinedDefinitions, $visited)) {
return true;
}
continue;
} elseif ($argument instanceof Reference) {
$argumentId = (string) $argument;
if ($id === $argumentId) {
return true;
}
if (!$deep || isset($visited[$argumentId]) || !isset($this->circularReferences[$argumentId])) {
continue;
}
$visited[$argumentId] = true;
$service = $this->container->getDefinition($argumentId);
} elseif ($argument instanceof Definition) {
if (isset($inlinedDefinitions[$argument])) {
return true;
}
$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, $inlinedDefinitions, $visited)) {
return true;
}
}
return false;
}
/**
* @throws RuntimeException
*/
@ -1492,7 +1370,7 @@ EOF;
return sprintf('array(%s)', implode(', ', $code));
} elseif ($value instanceof ArgumentInterface) {
$scope = array($this->definitionVariables, $this->referenceVariables, $this->variableCount);
$scope = array($this->definitionVariables, $this->referenceVariables);
$this->definitionVariables = $this->referenceVariables = null;
try {
@ -1540,7 +1418,7 @@ EOF;
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)) {

View File

@ -669,13 +669,7 @@ EOF
// 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'));
}
}
}

View File

@ -654,13 +654,7 @@ class YamlFileLoader extends FileLoader
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'));
}
}

View File

@ -890,7 +890,14 @@ class PhpDumperTest extends TestCase
$dumper = new PhpDumper($container);
$dumper->dump();
$this->assertStringEqualsFile(self::$fixturesPath.'/php/services_deep_graph.php', $dumper->dump());
$this->assertStringEqualsFile(self::$fixturesPath.'/php/services_deep_graph.php', $dumper->dump(array('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) array('p2' => (object) array('p3' => (object) array())), $container->get('foo')->bClone);
}
public function testHotPathOptimizations()
@ -1041,3 +1048,14 @@ class Rot13EnvVarProcessor implements EnvVarProcessorInterface
return array('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;
}
}

View File

@ -125,6 +125,7 @@ class Symfony_DI_PhpDumper_Test_Almost_Circular_Private extends Container
$this->services['connection'] = $instance = new \stdClass($a, $b);
$a->subscriber = ($this->services['subscriber'] ?? $this->getSubscriberService());
$b->logger = ($this->services['logger'] ?? $this->getLoggerService());
return $instance;
@ -139,17 +140,19 @@ class Symfony_DI_PhpDumper_Test_Almost_Circular_Private extends Container
{
$a = new \stdClass();
$b = new \stdClass();
$c = new \stdClass();
$this->services['connection2'] = $instance = new \stdClass($a, $b);
$this->services['connection2'] = $instance = new \stdClass($a, $c);
$c = ($this->services['manager2'] ?? $this->getManager2Service());
$b = ($this->services['manager2'] ?? $this->getManager2Service());
$a->subscriber2 = new \stdClass($b);
$d = new \stdClass($instance);
$a->subscriber2 = new \stdClass($c);
$d->handler2 = new \stdClass($c);
$b->logger2 = $d;
$d->handler2 = new \stdClass($b);
$c->logger2 = $d;
return $instance;
}

View File

@ -173,6 +173,7 @@ class Symfony_DI_PhpDumper_Test_Almost_Circular_Public extends Container
$c = new \stdClass($instance);
$c->handler2 = new \stdClass(($this->services['manager2'] ?? $this->getManager2Service()));
$b->logger2 = $c;
return $instance;

View File

@ -14,7 +14,7 @@ use Symfony\Component\DependencyInjection\ParameterBag\FrozenParameterBag;
*
* @final since Symfony 3.3
*/
class ProjectServiceContainer extends Container
class Symfony_DI_PhpDumper_Test_Deep_Graph extends Container
{
private $parameters;
private $targetDirs = array();
@ -62,13 +62,13 @@ class ProjectServiceContainer extends Container
/**
* Gets the public 'bar' shared service.
*
* @return \c5
* @return \stdClass
*/
protected function getBarService()
{
$this->services['bar'] = $instance = new \c5();
$this->services['bar'] = $instance = new \stdClass();
$instance->p5 = new \c6(($this->services['foo'] ?? $this->getFooService()));
$instance->p5 = new \stdClass(($this->services['foo'] ?? $this->getFooService()));
return $instance;
}
@ -76,7 +76,7 @@ class ProjectServiceContainer extends Container
/**
* Gets the public 'foo' shared service.
*
* @return \c1
* @return \Symfony\Component\DependencyInjection\Tests\Dumper\FooForDeepGraph
*/
protected function getFooService()
{
@ -86,15 +86,11 @@ class ProjectServiceContainer extends Container
return $this->services['foo'];
}
$b = new \c2();
$this->services['foo'] = $instance = new \c1($a, $b);
$c = new \c3();
$c->p3 = new \c4();
$b = new \stdClass();
$c = new \stdClass();
$c->p3 = new \stdClass();
$b->p2 = $c;
return $instance;
return $this->services['foo'] = new \Symfony\Component\DependencyInjection\Tests\Dumper\FooForDeepGraph($a, $b);
}
}

View File

@ -101,8 +101,8 @@ class ProjectServiceContainer extends Container
*/
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());
}

View File

@ -1,24 +1,24 @@
services:
foo:
class: c1
class: Symfony\Component\DependencyInjection\Tests\Dumper\FooForDeepGraph
public: true
arguments:
- '@bar'
- !service
class: c2
class: stdClass
properties:
p2: !service
class: c3
class: stdClass
properties:
p3: !service
class: c4
class: stdClass
bar:
class: c5
class: stdClass
public: true
properties:
p5: !service
class: c6
class: stdClass
arguments: ['@foo']

View File

@ -161,7 +161,7 @@ class FilesystemTest extends FilesystemTestCase
*/
public function testCopyForOriginUrlsAndExistingLocalFileDefaultsToCopy()
{
if (!in_array('https', stream_get_wrappers())) {
if (!\in_array('https', stream_get_wrappers())) {
$this->markTestSkipped('"https" stream wrapper is not enabled.');
}
$sourceFilePath = 'https://symfony.com/images/common/logo/logo_symfony_header.png';

View File

@ -76,9 +76,7 @@ class ArrayToPartsTransformer implements DataTransformerInterface
return;
}
throw new TransformationFailedException(
sprintf('The keys "%s" should not be empty', implode('", "', $emptyKeys)
));
throw new TransformationFailedException(sprintf('The keys "%s" should not be empty', implode('", "', $emptyKeys)));
}
return $result;

View File

@ -131,9 +131,7 @@ class DateTimeToArrayTransformer extends BaseDateTimeTransformer
}
if (\count($emptyFields) > 0) {
throw new TransformationFailedException(
sprintf('The fields "%s" should not be empty', implode('", "', $emptyFields)
));
throw new TransformationFailedException(sprintf('The fields "%s" should not be empty', implode('", "', $emptyFields)));
}
if (isset($value['month']) && !ctype_digit((string) $value['month'])) {

View File

@ -80,12 +80,7 @@ class DateTimeToRfc3339Transformer extends BaseDateTimeTransformer
if (preg_match('/(\d{4})-(\d{2})-(\d{2})/', $rfc3339, $matches)) {
if (!checkdate($matches[2], $matches[3], $matches[1])) {
throw new TransformationFailedException(sprintf(
'The date "%s-%s-%s" is not a valid date.',
$matches[1],
$matches[2],
$matches[3]
));
throw new TransformationFailedException(sprintf('The date "%s-%s-%s" is not a valid date.', $matches[1], $matches[2], $matches[3]));
}
}

View File

@ -122,12 +122,7 @@ class DateTimeToStringTransformer extends BaseDateTimeTransformer
$lastErrors = \DateTime::getLastErrors();
if (0 < $lastErrors['warning_count'] || 0 < $lastErrors['error_count']) {
throw new TransformationFailedException(
implode(', ', array_merge(
array_values($lastErrors['warnings']),
array_values($lastErrors['errors'])
))
);
throw new TransformationFailedException(implode(', ', array_merge(array_values($lastErrors['warnings']), array_values($lastErrors['errors']))));
}
try {

View File

@ -201,9 +201,7 @@ class NumberToLocalizedStringTransformer implements DataTransformerInterface
$remainder = trim($remainder, " \t\n\r\0\x0b\xc2\xa0");
if ('' !== $remainder) {
throw new TransformationFailedException(
sprintf('The number contains unrecognized characters: "%s"', $remainder)
);
throw new TransformationFailedException(sprintf('The number contains unrecognized characters: "%s"', $remainder));
}
}

View File

@ -64,9 +64,7 @@ class ValueToDuplicatesTransformer implements DataTransformerInterface
foreach ($this->keys as $key) {
if (isset($array[$key]) && '' !== $array[$key] && false !== $array[$key] && array() !== $array[$key]) {
if ($array[$key] !== $result) {
throw new TransformationFailedException(
'All values in the array should be the same'
);
throw new TransformationFailedException('All values in the array should be the same');
}
} else {
$emptyKeys[] = $key;
@ -79,9 +77,7 @@ class ValueToDuplicatesTransformer implements DataTransformerInterface
return;
}
throw new TransformationFailedException(
sprintf('The keys "%s" should not be empty', implode('", "', $emptyKeys)
));
throw new TransformationFailedException(sprintf('The keys "%s" should not be empty', implode('", "', $emptyKeys)));
}
return $result;

View File

@ -128,10 +128,7 @@ class ChoiceType extends AbstractType
// Throw exception if unknown values were submitted
if (\count($unknownValues) > 0) {
throw new TransformationFailedException(sprintf(
'The choices "%s" do not exist in the choice list.',
implode('", "', array_keys($unknownValues))
));
throw new TransformationFailedException(sprintf('The choices "%s" do not exist in the choice list.', implode('", "', array_keys($unknownValues))));
}
$event->setData($data);

View File

@ -60,13 +60,7 @@ class DependencyInjectionExtension implements FormExtensionInterface
// validate result of getExtendedType() to ensure it is consistent with the service definition
if ($extension->getExtendedType() !== $name) {
throw new InvalidArgumentException(
sprintf('The extended type specified for the service "%s" does not match the actual extended type. Expected "%s", given "%s".',
$serviceId,
$name,
$extension->getExtendedType()
)
);
throw new InvalidArgumentException(sprintf('The extended type specified for the service "%s" does not match the actual extended type. Expected "%s", given "%s".', $serviceId, $name, $extension->getExtendedType()));
}
}
}

View File

@ -358,13 +358,7 @@ class Form implements \IteratorAggregate, FormInterface
? 'an instance of class '.\get_class($viewData)
: 'a(n) '.\gettype($viewData);
throw new LogicException(
'The form\'s view data is expected to be an instance of class '.
$dataClass.', but is '.$actualType.'. You can avoid this error '.
'by setting the "data_class" option to null or by adding a view '.
'transformer that transforms '.$actualType.' to an instance of '.
$dataClass.'.'
);
throw new LogicException('The form\'s view data is expected to be an instance of class '.$dataClass.', but is '.$actualType.'. You can avoid this error by setting the "data_class" option to null or by adding a view transformer that transforms '.$actualType.' to an instance of '.$dataClass.'.');
}
}
@ -861,11 +855,7 @@ class Form implements \IteratorAggregate, FormInterface
$child = $this->config->getFormFactory()->createNamed($child, $type, null, $options);
}
} elseif ($child->getConfig()->getAutoInitialize()) {
throw new RuntimeException(sprintf(
'Automatic initialization is only supported on root forms. You '.
'should set the "auto_initialize" option to false on the field "%s".',
$child->getName()
));
throw new RuntimeException(sprintf('Automatic initialization is only supported on root forms. You should set the "auto_initialize" option to false on the field "%s".', $child->getName()));
}
$this->children[$child->getName()] = $child;
@ -1039,11 +1029,7 @@ class Form implements \IteratorAggregate, FormInterface
$value = $transformer->transform($value);
}
} catch (TransformationFailedException $exception) {
throw new TransformationFailedException(
'Unable to transform value for property path "'.$this->getPropertyPath().'": '.$exception->getMessage(),
$exception->getCode(),
$exception
);
throw new TransformationFailedException('Unable to transform value for property path "'.$this->getPropertyPath().'": '.$exception->getMessage(), $exception->getCode(), $exception);
}
return $value;
@ -1067,11 +1053,7 @@ class Form implements \IteratorAggregate, FormInterface
$value = $transformers[$i]->reverseTransform($value);
}
} catch (TransformationFailedException $exception) {
throw new TransformationFailedException(
'Unable to reverse value for property path "'.$this->getPropertyPath().'": '.$exception->getMessage(),
$exception->getCode(),
$exception
);
throw new TransformationFailedException('Unable to reverse value for property path "'.$this->getPropertyPath().'": '.$exception->getMessage(), $exception->getCode(), $exception);
}
return $value;
@ -1102,11 +1084,7 @@ class Form implements \IteratorAggregate, FormInterface
$value = $transformer->transform($value);
}
} catch (TransformationFailedException $exception) {
throw new TransformationFailedException(
'Unable to transform value for property path "'.$this->getPropertyPath().'": '.$exception->getMessage(),
$exception->getCode(),
$exception
);
throw new TransformationFailedException('Unable to transform value for property path "'.$this->getPropertyPath().'": '.$exception->getMessage(), $exception->getCode(), $exception);
}
return $value;
@ -1134,11 +1112,7 @@ class Form implements \IteratorAggregate, FormInterface
$value = $transformers[$i]->reverseTransform($value);
}
} catch (TransformationFailedException $exception) {
throw new TransformationFailedException(
'Unable to reverse value for property path "'.$this->getPropertyPath().'": '.$exception->getMessage(),
$exception->getCode(),
$exception
);
throw new TransformationFailedException('Unable to reverse value for property path "'.$this->getPropertyPath().'": '.$exception->getMessage(), $exception->getCode(), $exception);
}
return $value;

View File

@ -791,11 +791,7 @@ class FormConfigBuilder implements FormConfigBuilderInterface
$upperCaseMethod = strtoupper($method);
if (!\in_array($upperCaseMethod, self::$allowedMethods)) {
throw new InvalidArgumentException(sprintf(
'The form method is "%s", but should be one of "%s".',
$method,
implode('", "', self::$allowedMethods)
));
throw new InvalidArgumentException(sprintf('The form method is "%s", but should be one of "%s".', $method, implode('", "', self::$allowedMethods)));
}
$this->method = $upperCaseMethod;
@ -862,10 +858,7 @@ class FormConfigBuilder implements FormConfigBuilderInterface
}
if (!self::isValidName($name)) {
throw new InvalidArgumentException(sprintf(
'The name "%s" contains illegal characters. Names should start with a letter, digit or underscore and only contain letters, digits, numbers, underscores ("_"), hyphens ("-") and colons (":").',
$name
));
throw new InvalidArgumentException(sprintf('The name "%s" contains illegal characters. Names should start with a letter, digit or underscore and only contain letters, digits, numbers, underscores ("_"), hyphens ("-") and colons (":").', $name));
}
}

View File

@ -51,12 +51,7 @@ class FormErrorIterator implements \RecursiveIterator, \SeekableIterator, \Array
{
foreach ($errors as $error) {
if (!($error instanceof FormError || $error instanceof self)) {
throw new InvalidArgumentException(sprintf(
'The errors must be instances of '.
'"\Symfony\Component\Form\FormError" or "%s". Got: "%s".',
__CLASS__,
\is_object($error) ? \get_class($error) : \gettype($error)
));
throw new InvalidArgumentException(sprintf('The errors must be instances of "Symfony\Component\Form\FormError" or "%s". Got: "%s".', __CLASS__, \is_object($error) ? \get_class($error) : \gettype($error)));
}
}

View File

@ -36,14 +36,7 @@ abstract class FormPerformanceTestCase extends FormIntegrationTestCase
$time = microtime(true) - $s;
if (0 != $this->maxRunningTime && $time > $this->maxRunningTime) {
$this->fail(
sprintf(
'expected running time: <= %s but was: %s',
$this->maxRunningTime,
$time
)
);
$this->fail(sprintf('expected running time: <= %s but was: %s', $this->maxRunningTime, $time));
}
}

View File

@ -50,9 +50,7 @@ class MemcachedSessionHandler extends AbstractSessionHandler
$this->memcached = $memcached;
if ($diff = array_diff(array_keys($options), array('prefix', 'expiretime'))) {
throw new \InvalidArgumentException(sprintf(
'The following options are not supported "%s"', implode(', ', $diff)
));
throw new \InvalidArgumentException(sprintf('The following options are not supported "%s"', implode(', ', $diff)));
}
$this->ttl = isset($options['expiretime']) ? (int) $options['expiretime'] : 86400;

View File

@ -78,10 +78,7 @@ abstract class Bundle implements BundleInterface
$expectedAlias = Container::underscore($basename);
if ($expectedAlias != $extension->getAlias()) {
throw new \LogicException(sprintf(
'Users will expect the alias of the default extension of a bundle to be the underscored version of the bundle name ("%s"). You can override "Bundle::getContainerExtension()" if you want to use "%s" or another alias.',
$expectedAlias, $extension->getAlias()
));
throw new \LogicException(sprintf('Users will expect the alias of the default extension of a bundle to be the underscored version of the bundle name ("%s"). You can override "Bundle::getContainerExtension()" if you want to use "%s" or another alias.', $expectedAlias, $extension->getAlias()));
}
$this->extension = $extension;

View File

@ -250,11 +250,7 @@ abstract class Kernel implements KernelInterface, RebootableInterface, Terminabl
if ($isResource && file_exists($file = $dir.'/'.$bundle->getName().$overridePath)) {
if (null !== $resourceBundle) {
throw new \RuntimeException(sprintf('"%s" resource is hidden by a resource from the "%s" derived bundle. Create a "%s" file to override the bundle resource.',
$file,
$resourceBundle,
$dir.'/'.$bundle->getName().$overridePath
));
throw new \RuntimeException(sprintf('"%s" resource is hidden by a resource from the "%s" derived bundle. Create a "%s" file to override the bundle resource.', $file, $resourceBundle, $dir.'/'.$bundle->getName().$overridePath));
}
$files[] = $file;

View File

@ -37,10 +37,7 @@ class GenrbCompiler implements BundleCompilerInterface
exec('which '.$genrb, $output, $status);
if (0 !== $status) {
throw new RuntimeException(sprintf(
'The command "%s" is not installed',
$genrb
));
throw new RuntimeException(sprintf('The command "%s" is not installed', $genrb));
}
$this->genrb = ($envVars ? $envVars.' ' : '').$genrb;
@ -58,12 +55,7 @@ class GenrbCompiler implements BundleCompilerInterface
exec($this->genrb.' --quiet -e UTF-8 -d '.$targetDir.' '.$sourcePath, $output, $status);
if (0 !== $status) {
throw new RuntimeException(sprintf(
'genrb failed with status %d while compiling %s to %s.',
$status,
$sourcePath,
$targetDir
));
throw new RuntimeException(sprintf('genrb failed with status %d while compiling %s to %s.', $status, $sourcePath, $targetDir));
}
}
}

View File

@ -40,11 +40,7 @@ class IntlBundleReader implements BundleReaderInterface
// The bundle is NULL if the path does not look like a resource bundle
// (i.e. contain a bunch of *.res files)
if (null === $bundle) {
throw new ResourceBundleNotFoundException(sprintf(
'The resource bundle "%s/%s.res" could not be found.',
$path,
$locale
));
throw new ResourceBundleNotFoundException(sprintf('The resource bundle "%s/%s.res" could not be found.', $path, $locale));
}
// Other possible errors are U_USING_FALLBACK_WARNING and U_ZERO_ERROR,

View File

@ -36,27 +36,17 @@ class JsonBundleReader implements BundleReaderInterface
}
if (!file_exists($fileName)) {
throw new ResourceBundleNotFoundException(sprintf(
'The resource bundle "%s" does not exist.',
$fileName
));
throw new ResourceBundleNotFoundException(sprintf('The resource bundle "%s" does not exist.', $fileName));
}
if (!is_file($fileName)) {
throw new RuntimeException(sprintf(
'The resource bundle "%s" is not a file.',
$fileName
));
throw new RuntimeException(sprintf('The resource bundle "%s" is not a file.', $fileName));
}
$data = json_decode(file_get_contents($fileName), true);
if (null === $data) {
throw new RuntimeException(sprintf(
'The resource bundle "%s" contains invalid JSON: %s',
$fileName,
json_last_error_msg()
));
throw new RuntimeException(sprintf('The resource bundle "%s" contains invalid JSON: %s', $fileName, json_last_error_msg()));
}
return $data;

View File

@ -36,19 +36,11 @@ class PhpBundleReader implements BundleReaderInterface
}
if (!file_exists($fileName)) {
throw new ResourceBundleNotFoundException(sprintf(
'The resource bundle "%s/%s.php" does not exist.',
$path,
$locale
));
throw new ResourceBundleNotFoundException(sprintf('The resource bundle "%s/%s.php" does not exist.', $path, $locale));
}
if (!is_file($fileName)) {
throw new RuntimeException(sprintf(
'The resource bundle "%s/%s.php" is not a file.',
$path,
$locale
));
throw new RuntimeException(sprintf('The resource bundle "%s/%s.php" is not a file.', $path, $locale));
}
return include $fileName;

View File

@ -173,32 +173,19 @@ class LanguageDataGenerator extends AbstractDataGenerator
if (isset(self::$preferredAlpha2ToAlpha3Mapping[$language])) {
// Validate to prevent typos
if (!isset($aliases[self::$preferredAlpha2ToAlpha3Mapping[$language]])) {
throw new RuntimeException(
'The statically set three-letter mapping '.
self::$preferredAlpha2ToAlpha3Mapping[$language].' '.
'for the language code '.$language.' seems to be '.
'invalid. Typo?'
);
throw new RuntimeException('The statically set three-letter mapping '.self::$preferredAlpha2ToAlpha3Mapping[$language].' for the language code '.$language.' seems to be invalid. Typo?');
}
$alpha3 = self::$preferredAlpha2ToAlpha3Mapping[$language];
$alpha2 = $aliases[$alpha3]['replacement'];
if ($language !== $alpha2) {
throw new RuntimeException(
'The statically set three-letter mapping '.$alpha3.' '.
'for the language code '.$language.' seems to be '.
'an alias for '.$alpha2.'. Wrong mapping?'
);
throw new RuntimeException('The statically set three-letter mapping '.$alpha3.' for the language code '.$language.' seems to be an alias for '.$alpha2.'. Wrong mapping?');
}
$alpha2ToAlpha3[$language] = $alpha3;
} elseif (isset($alpha2ToAlpha3[$language])) {
throw new RuntimeException(
'Multiple three-letter mappings exist for the language '.
'code '.$language.'. Please add one of them to the '.
'property $preferredAlpha2ToAlpha3Mapping.'
);
throw new RuntimeException('Multiple three-letter mappings exist for the language code '.$language.'. Please add one of them to the property $preferredAlpha2ToAlpha3Mapping.');
} else {
$alpha2ToAlpha3[$language] = $alias;
}

View File

@ -36,10 +36,7 @@ class RecursiveArrayAccess
}
}
throw new OutOfBoundsException(sprintf(
'The index %s does not exist.',
$index
));
throw new OutOfBoundsException(sprintf('The index %s does not exist.', $index));
}
return $array;

View File

@ -53,10 +53,7 @@ class RingBuffer implements \ArrayAccess
public function offsetGet($key)
{
if (!isset($this->indices[$key])) {
throw new OutOfBoundsException(sprintf(
'The index "%s" does not exist.',
$key
));
throw new OutOfBoundsException(sprintf('The index "%s" does not exist.', $key));
}
return $this->values[$this->indices[$key]];

View File

@ -106,10 +106,7 @@ class TimezoneTransformer extends Transformer
$signal = '-' == $matches['signal'] ? '+' : '-';
if (0 < $minutes) {
throw new NotImplementedException(sprintf(
'It is not possible to use a GMT time zone with minutes offset different than zero (0). GMT time zone tried: %s.',
$formattedTimeZone
));
throw new NotImplementedException(sprintf('It is not possible to use a GMT time zone with minutes offset different than zero (0). GMT time zone tried: %s.', $formattedTimeZone));
}
return 'Etc/GMT'.(0 !== $hours ? $signal.$hours : '');

View File

@ -360,10 +360,7 @@ class NumberFormatter
}
if (self::CURRENCY == $this->style) {
throw new NotImplementedException(sprintf(
'%s() method does not support the formatting of currencies (instance with CURRENCY style). %s',
__METHOD__, NotImplementedException::INTL_INSTALL_MESSAGE
));
throw new NotImplementedException(sprintf('%s() method does not support the formatting of currencies (instance with CURRENCY style). %s', __METHOD__, NotImplementedException::INTL_INSTALL_MESSAGE));
}
// Only the default type is supported.

View File

@ -381,11 +381,7 @@ class OptionsResolver implements Options
}
if (!isset($this->defined[$option])) {
throw new UndefinedOptionsException(sprintf(
'The option "%s" does not exist. Defined options are: "%s".',
$option,
implode('", "', array_keys($this->defined))
));
throw new UndefinedOptionsException(sprintf('The option "%s" does not exist. Defined options are: "%s".', $option, implode('", "', array_keys($this->defined))));
}
$this->normalizers[$option] = $normalizer;
@ -424,11 +420,7 @@ class OptionsResolver implements Options
}
if (!isset($this->defined[$option])) {
throw new UndefinedOptionsException(sprintf(
'The option "%s" does not exist. Defined options are: "%s".',
$option,
implode('", "', array_keys($this->defined))
));
throw new UndefinedOptionsException(sprintf('The option "%s" does not exist. Defined options are: "%s".', $option, implode('", "', array_keys($this->defined))));
}
$this->allowedValues[$option] = \is_array($allowedValues) ? $allowedValues : array($allowedValues);
@ -469,11 +461,7 @@ class OptionsResolver implements Options
}
if (!isset($this->defined[$option])) {
throw new UndefinedOptionsException(sprintf(
'The option "%s" does not exist. Defined options are: "%s".',
$option,
implode('", "', array_keys($this->defined))
));
throw new UndefinedOptionsException(sprintf('The option "%s" does not exist. Defined options are: "%s".', $option, implode('", "', array_keys($this->defined))));
}
if (!\is_array($allowedValues)) {
@ -514,11 +502,7 @@ class OptionsResolver implements Options
}
if (!isset($this->defined[$option])) {
throw new UndefinedOptionsException(sprintf(
'The option "%s" does not exist. Defined options are: "%s".',
$option,
implode('", "', array_keys($this->defined))
));
throw new UndefinedOptionsException(sprintf('The option "%s" does not exist. Defined options are: "%s".', $option, implode('", "', array_keys($this->defined))));
}
$this->allowedTypes[$option] = (array) $allowedTypes;
@ -553,11 +537,7 @@ class OptionsResolver implements Options
}
if (!isset($this->defined[$option])) {
throw new UndefinedOptionsException(sprintf(
'The option "%s" does not exist. Defined options are: "%s".',
$option,
implode('", "', array_keys($this->defined))
));
throw new UndefinedOptionsException(sprintf('The option "%s" does not exist. Defined options are: "%s".', $option, implode('", "', array_keys($this->defined))));
}
if (!isset($this->allowedTypes[$option])) {
@ -662,11 +642,7 @@ class OptionsResolver implements Options
ksort($clone->defined);
ksort($diff);
throw new UndefinedOptionsException(sprintf(
(\count($diff) > 1 ? 'The options "%s" do not exist.' : 'The option "%s" does not exist.').' Defined options are: "%s".',
implode('", "', array_keys($diff)),
implode('", "', array_keys($clone->defined))
));
throw new UndefinedOptionsException(sprintf((\count($diff) > 1 ? 'The options "%s" do not exist.' : 'The option "%s" does not exist.').' Defined options are: "%s".', implode('", "', array_keys($diff)), implode('", "', array_keys($clone->defined))));
}
// Override options set by the user
@ -681,10 +657,7 @@ class OptionsResolver implements Options
if (\count($diff) > 0) {
ksort($diff);
throw new MissingOptionsException(sprintf(
\count($diff) > 1 ? 'The required options "%s" are missing.' : 'The required option "%s" is missing.',
implode('", "', array_keys($diff))
));
throw new MissingOptionsException(sprintf(\count($diff) > 1 ? 'The required options "%s" are missing.' : 'The required option "%s" is missing.', implode('", "', array_keys($diff))));
}
// Lock the container
@ -728,17 +701,10 @@ class OptionsResolver implements Options
// Check whether the option is set at all
if (!array_key_exists($option, $this->defaults)) {
if (!isset($this->defined[$option])) {
throw new NoSuchOptionException(sprintf(
'The option "%s" does not exist. Defined options are: "%s".',
$option,
implode('", "', array_keys($this->defined))
));
throw new NoSuchOptionException(sprintf('The option "%s" does not exist. Defined options are: "%s".', $option, implode('", "', array_keys($this->defined))));
}
throw new NoSuchOptionException(sprintf(
'The optional option "%s" has no value set. You should make sure it is set with "isset" before reading it.',
$option
));
throw new NoSuchOptionException(sprintf('The optional option "%s" has no value set. You should make sure it is set with "isset" before reading it.', $option));
}
$value = $this->defaults[$option];
@ -748,10 +714,7 @@ class OptionsResolver implements Options
// If the closure is already being called, we have a cyclic
// dependency
if (isset($this->calling[$option])) {
throw new OptionDefinitionException(sprintf(
'The options "%s" have a cyclic dependency.',
implode('", "', array_keys($this->calling))
));
throw new OptionDefinitionException(sprintf('The options "%s" have a cyclic dependency.', implode('", "', array_keys($this->calling))));
}
// The following section must be protected from cyclic
@ -838,10 +801,7 @@ class OptionsResolver implements Options
// If the closure is already being called, we have a cyclic
// dependency
if (isset($this->calling[$option])) {
throw new OptionDefinitionException(sprintf(
'The options "%s" have a cyclic dependency.',
implode('", "', array_keys($this->calling))
));
throw new OptionDefinitionException(sprintf('The options "%s" have a cyclic dependency.', implode('", "', array_keys($this->calling))));
}
$normalizer = $this->normalizers[$option];

View File

@ -1392,8 +1392,8 @@ class Process implements \IteratorAggregate
$this->exitcode = null;
$this->fallbackStatus = array();
$this->processInformation = null;
$this->stdout = fopen('php://temp/maxmemory:'.(1024 * 1024), 'wb+');
$this->stderr = fopen('php://temp/maxmemory:'.(1024 * 1024), 'wb+');
$this->stdout = fopen('php://temp/maxmemory:'.(1024 * 1024), 'w+b');
$this->stderr = fopen('php://temp/maxmemory:'.(1024 * 1024), 'w+b');
$this->process = null;
$this->latestSignal = null;
$this->status = self::STATUS_READY;

View File

@ -272,22 +272,13 @@ class PropertyAccessor implements PropertyAccessorInterface
if (!$ignoreInvalidIndices) {
if (!\is_array($zval[self::VALUE])) {
if (!$zval[self::VALUE] instanceof \Traversable) {
throw new NoSuchIndexException(sprintf(
'Cannot read index "%s" while trying to traverse path "%s".',
$property,
(string) $propertyPath
));
throw new NoSuchIndexException(sprintf('Cannot read index "%s" while trying to traverse path "%s".', $property, (string) $propertyPath));
}
$zval[self::VALUE] = iterator_to_array($zval[self::VALUE]);
}
throw new NoSuchIndexException(sprintf(
'Cannot read index "%s" while trying to traverse path "%s". Available indices are "%s".',
$property,
(string) $propertyPath,
print_r(array_keys($zval[self::VALUE]), true)
));
throw new NoSuchIndexException(sprintf('Cannot read index "%s" while trying to traverse path "%s". Available indices are "%s".', $property, (string) $propertyPath, print_r(array_keys($zval[self::VALUE]), true)));
}
if ($i + 1 < $propertyPath->getLength()) {

View File

@ -77,12 +77,7 @@ class PropertyPath implements \IteratorAggregate, PropertyPathInterface
return;
}
if (!\is_string($propertyPath)) {
throw new InvalidArgumentException(sprintf(
'The property path constructor needs a string or an instance of '.
'"Symfony\Component\PropertyAccess\PropertyPath". '.
'Got: "%s"',
\is_object($propertyPath) ? \get_class($propertyPath) : \gettype($propertyPath)
));
throw new InvalidArgumentException(sprintf('The property path constructor needs a string or an instance of "Symfony\Component\PropertyAccess\PropertyPath". Got: "%s"', \is_object($propertyPath) ? \get_class($propertyPath) : \gettype($propertyPath)));
}
if ('' === $propertyPath) {
@ -113,12 +108,7 @@ class PropertyPath implements \IteratorAggregate, PropertyPathInterface
}
if ('' !== $remaining) {
throw new InvalidPropertyPathException(sprintf(
'Could not parse property path "%s". Unexpected token "%s" at position %d',
$propertyPath,
$remaining[0],
$position
));
throw new InvalidPropertyPathException(sprintf('Could not parse property path "%s". Unexpected token "%s" at position %d', $propertyPath, $remaining[0], $position));
}
$this->length = \count($this->elements);

View File

@ -244,28 +244,16 @@ class YamlFileLoader extends FileLoader
throw new \InvalidArgumentException(sprintf('The definition of "%s" in "%s" must be a YAML array.', $name, $path));
}
if ($extraKeys = array_diff(array_keys($config), self::$availableKeys)) {
throw new \InvalidArgumentException(sprintf(
'The routing file "%s" contains unsupported keys for "%s": "%s". Expected one of: "%s".',
$path, $name, implode('", "', $extraKeys), implode('", "', self::$availableKeys)
));
throw new \InvalidArgumentException(sprintf('The routing file "%s" contains unsupported keys for "%s": "%s". Expected one of: "%s".', $path, $name, implode('", "', $extraKeys), implode('", "', self::$availableKeys)));
}
if (isset($config['resource']) && isset($config['path'])) {
throw new \InvalidArgumentException(sprintf(
'The routing file "%s" must not specify both the "resource" key and the "path" key for "%s". Choose between an import and a route definition.',
$path, $name
));
throw new \InvalidArgumentException(sprintf('The routing file "%s" must not specify both the "resource" key and the "path" key for "%s". Choose between an import and a route definition.', $path, $name));
}
if (!isset($config['resource']) && isset($config['type'])) {
throw new \InvalidArgumentException(sprintf(
'The "type" key for the route definition "%s" in "%s" is unsupported. It is only available for imports in combination with the "resource" key.',
$name, $path
));
throw new \InvalidArgumentException(sprintf('The "type" key for the route definition "%s" in "%s" is unsupported. It is only available for imports in combination with the "resource" key.', $name, $path));
}
if (!isset($config['resource']) && !isset($config['path'])) {
throw new \InvalidArgumentException(sprintf(
'You must define a "path" for the route "%s" in file "%s".',
$name, $path
));
throw new \InvalidArgumentException(sprintf('You must define a "path" for the route "%s" in file "%s".', $name, $path));
}
if (isset($config['controller']) && isset($config['defaults']['_controller'])) {
throw new \InvalidArgumentException(sprintf('The routing file "%s" must not specify both the "controller" key and the defaults key "_controller" for "%s".', $path, $name));

View File

@ -192,10 +192,7 @@ class GuardAuthenticationListener implements ListenerInterface
}
if (!$response instanceof Response) {
throw new \LogicException(sprintf(
'%s::onAuthenticationSuccess *must* return a Response if you want to use the remember me functionality. Return a Response, or set remember_me to false under the guard configuration.',
\get_class($guardAuthenticator)
));
throw new \LogicException(sprintf('%s::onAuthenticationSuccess *must* return a Response if you want to use the remember me functionality. Return a Response, or set remember_me to false under the guard configuration.', \get_class($guardAuthenticator)));
}
$this->rememberMeServices->loginSuccess($request, $response, $token);

View File

@ -79,11 +79,7 @@ class GuardAuthenticatorHandler
return $response;
}
throw new \UnexpectedValueException(sprintf(
'The %s::onAuthenticationSuccess method must return null or a Response object. You returned %s.',
\get_class($guardAuthenticator),
\is_object($response) ? \get_class($response) : \gettype($response)
));
throw new \UnexpectedValueException(sprintf('The %s::onAuthenticationSuccess method must return null or a Response object. You returned %s.', \get_class($guardAuthenticator), \is_object($response) ? \get_class($response) : \gettype($response)));
}
/**
@ -113,11 +109,7 @@ class GuardAuthenticatorHandler
return $response;
}
throw new \UnexpectedValueException(sprintf(
'The %s::onAuthenticationFailure method must return null or a Response object. You returned %s.',
\get_class($guardAuthenticator),
\is_object($response) ? \get_class($response) : \gettype($response)
));
throw new \UnexpectedValueException(sprintf('The %s::onAuthenticationFailure method must return null or a Response object. You returned %s.', \get_class($guardAuthenticator), \is_object($response) ? \get_class($response) : \gettype($response)));
}
/**

View File

@ -124,10 +124,7 @@ abstract class AbstractNormalizer implements NormalizerInterface, DenormalizerIn
{
foreach ($callbacks as $attribute => $callback) {
if (!\is_callable($callback)) {
throw new InvalidArgumentException(sprintf(
'The given callback for attribute "%s" is not callable.',
$attribute
));
throw new InvalidArgumentException(sprintf('The given callback for attribute "%s" is not callable.', $attribute));
}
}
$this->callbacks = $callbacks;
@ -386,13 +383,7 @@ abstract class AbstractNormalizer implements NormalizerInterface, DenormalizerIn
} elseif ($constructorParameter->isDefaultValueAvailable()) {
$params[] = $constructorParameter->getDefaultValue();
} else {
throw new MissingConstructorArgumentsException(
sprintf(
'Cannot create an instance of %s from serialized data because its constructor requires parameter "%s" to be present.',
$class,
$constructorParameter->name
)
);
throw new MissingConstructorArgumentsException(sprintf('Cannot create an instance of %s from serialized data because its constructor requires parameter "%s" to be present.', $class, $constructorParameter->name));
}
}

View File

@ -28,7 +28,7 @@ class CsvFileDumper extends FileDumper
*/
public function formatCatalogue(MessageCatalogue $messages, $domain, array $options = array())
{
$handle = fopen('php://memory', 'rb+');
$handle = fopen('php://memory', 'r+b');
foreach ($messages->all($domain) as $source => $target) {
fputcsv($handle, array($source, $target), $this->delimiter, $this->enclosure);

View File

@ -70,11 +70,7 @@ abstract class Constraint
public static function getErrorName($errorCode)
{
if (!isset(static::$errorNames[$errorCode])) {
throw new InvalidArgumentException(sprintf(
'The error code "%s" does not exist for constraint of type "%s".',
$errorCode,
\get_called_class()
));
throw new InvalidArgumentException(sprintf('The error code "%s" does not exist for constraint of type "%s".', $errorCode, \get_called_class()));
}
return static::$errorNames[$errorCode];
@ -137,9 +133,7 @@ abstract class Constraint
$option = $this->getDefaultOption();
if (null === $option) {
throw new ConstraintDefinitionException(
sprintf('No default option is configured for constraint %s', \get_class($this))
);
throw new ConstraintDefinitionException(sprintf('No default option is configured for constraint %s', \get_class($this)));
}
if (array_key_exists($option, $knownOptions)) {
@ -151,17 +145,11 @@ abstract class Constraint
}
if (\count($invalidOptions) > 0) {
throw new InvalidOptionsException(
sprintf('The options "%s" do not exist in constraint %s', implode('", "', $invalidOptions), \get_class($this)),
$invalidOptions
);
throw new InvalidOptionsException(sprintf('The options "%s" do not exist in constraint %s', implode('", "', $invalidOptions), \get_class($this)), $invalidOptions);
}
if (\count($missingOptions) > 0) {
throw new MissingOptionsException(
sprintf('The options "%s" must be set for constraint %s', implode('", "', array_keys($missingOptions)), \get_class($this)),
array_keys($missingOptions)
);
throw new MissingOptionsException(sprintf('The options "%s" must be set for constraint %s', implode('", "', array_keys($missingOptions)), \get_class($this)), array_keys($missingOptions));
}
}

View File

@ -99,13 +99,7 @@ abstract class Composite extends Constraint
$excessGroups = array_diff($constraint->groups, $this->groups);
if (\count($excessGroups) > 0) {
throw new ConstraintDefinitionException(sprintf(
'The group(s) "%s" passed to the constraint %s '.
'should also be passed to its containing constraint %s',
implode('", "', $excessGroups),
\get_class($constraint),
\get_class($this)
));
throw new ConstraintDefinitionException(sprintf('The group(s) "%s" passed to the constraint %s should also be passed to its containing constraint %s', implode('", "', $excessGroups), \get_class($constraint), \get_class($this)));
}
} else {
$constraint->groups = $this->groups;

View File

@ -26,10 +26,7 @@ class Traverse extends Constraint
public function __construct($options = null)
{
if (\is_array($options) && array_key_exists('groups', $options)) {
throw new ConstraintDefinitionException(sprintf(
'The option "groups" is not supported by the constraint %s',
__CLASS__
));
throw new ConstraintDefinitionException(sprintf('The option "groups" is not supported by the constraint %s', __CLASS__));
}
parent::__construct($options);

View File

@ -175,17 +175,11 @@ class ClassMetadata extends GenericMetadata implements ClassMetadataInterface
public function addConstraint(Constraint $constraint)
{
if (!\in_array(Constraint::CLASS_CONSTRAINT, (array) $constraint->getTargets())) {
throw new ConstraintDefinitionException(sprintf(
'The constraint "%s" cannot be put on classes.',
\get_class($constraint)
));
throw new ConstraintDefinitionException(sprintf('The constraint "%s" cannot be put on classes.', \get_class($constraint)));
}
if ($constraint instanceof Valid) {
throw new ConstraintDefinitionException(sprintf(
'The constraint "%s" cannot be put on classes.',
\get_class($constraint)
));
throw new ConstraintDefinitionException(sprintf('The constraint "%s" cannot be put on classes.', \get_class($constraint)));
}
if ($constraint instanceof Traverse) {

View File

@ -122,11 +122,7 @@ class GenericMetadata implements MetadataInterface
public function addConstraint(Constraint $constraint)
{
if ($constraint instanceof Traverse) {
throw new ConstraintDefinitionException(sprintf(
'The constraint "%s" can only be put on classes. Please use '.
'"Symfony\Component\Validator\Constraints\Valid" instead.',
\get_class($constraint)
));
throw new ConstraintDefinitionException(sprintf('The constraint "%s" can only be put on classes. Please use "Symfony\Component\Validator\Constraints\Valid" instead.', \get_class($constraint)));
}
if ($constraint instanceof Valid && null === $constraint->groups) {

View File

@ -72,10 +72,7 @@ abstract class MemberMetadata extends GenericMetadata implements PropertyMetadat
public function addConstraint(Constraint $constraint)
{
if (!\in_array(Constraint::PROPERTY_CONSTRAINT, (array) $constraint->getTargets())) {
throw new ConstraintDefinitionException(sprintf(
'The constraint %s cannot be put on properties or getters',
\get_class($constraint)
));
throw new ConstraintDefinitionException(sprintf('The constraint %s cannot be put on properties or getters', \get_class($constraint)));
}
parent::addConstraint($constraint);

View File

@ -161,11 +161,7 @@ class RecursiveContextualValidator implements ContextualValidatorInterface
return $this;
}
throw new RuntimeException(sprintf(
'Cannot validate values of type "%s" automatically. Please '.
'provide a constraint.',
\gettype($value)
));
throw new RuntimeException(sprintf('Cannot validate values of type "%s" automatically. Please provide a constraint.', \gettype($value)));
}
/**
@ -176,12 +172,7 @@ class RecursiveContextualValidator implements ContextualValidatorInterface
$classMetadata = $this->metadataFactory->getMetadataFor($object);
if (!$classMetadata instanceof ClassMetadataInterface) {
throw new ValidatorException(sprintf(
'The metadata factory should return instances of '.
'"\Symfony\Component\Validator\Mapping\ClassMetadataInterface", '.
'got: "%s".',
\is_object($classMetadata) ? \get_class($classMetadata) : \gettype($classMetadata)
));
throw new ValidatorException(sprintf('The metadata factory should return instances of "\Symfony\Component\Validator\Mapping\ClassMetadataInterface", got: "%s".', \is_object($classMetadata) ? \get_class($classMetadata) : \gettype($classMetadata)));
}
$propertyMetadatas = $classMetadata->getPropertyMetadata($propertyName);
@ -225,12 +216,7 @@ class RecursiveContextualValidator implements ContextualValidatorInterface
$classMetadata = $this->metadataFactory->getMetadataFor($objectOrClass);
if (!$classMetadata instanceof ClassMetadataInterface) {
throw new ValidatorException(sprintf(
'The metadata factory should return instances of '.
'"\Symfony\Component\Validator\Mapping\ClassMetadataInterface", '.
'got: "%s".',
\is_object($classMetadata) ? \get_class($classMetadata) : \gettype($classMetadata)
));
throw new ValidatorException(sprintf('The metadata factory should return instances of "\Symfony\Component\Validator\Mapping\ClassMetadataInterface", got: "%s".', \is_object($classMetadata) ? \get_class($classMetadata) : \gettype($classMetadata)));
}
$propertyMetadatas = $classMetadata->getPropertyMetadata($propertyName);
@ -328,12 +314,7 @@ class RecursiveContextualValidator implements ContextualValidatorInterface
$classMetadata = $this->metadataFactory->getMetadataFor($object);
if (!$classMetadata instanceof ClassMetadataInterface) {
throw new UnsupportedMetadataException(sprintf(
'The metadata factory should return instances of '.
'"Symfony\Component\Validator\Mapping\ClassMetadataInterface", '.
'got: "%s".',
\is_object($classMetadata) ? \get_class($classMetadata) : \gettype($classMetadata)
));
throw new UnsupportedMetadataException(sprintf('The metadata factory should return instances of "Symfony\Component\Validator\Mapping\ClassMetadataInterface", got: "%s".', \is_object($classMetadata) ? \get_class($classMetadata) : \gettype($classMetadata)));
}
$this->validateClassNode(
@ -555,12 +536,7 @@ class RecursiveContextualValidator implements ContextualValidatorInterface
// returns two metadata objects, not just one
foreach ($metadata->getPropertyMetadata($propertyName) as $propertyMetadata) {
if (!$propertyMetadata instanceof PropertyMetadataInterface) {
throw new UnsupportedMetadataException(sprintf(
'The property metadata instances should implement '.
'"Symfony\Component\Validator\Mapping\PropertyMetadataInterface", '.
'got: "%s".',
\is_object($propertyMetadata) ? \get_class($propertyMetadata) : \gettype($propertyMetadata)
));
throw new UnsupportedMetadataException(sprintf('The property metadata instances should implement "Symfony\Component\Validator\Mapping\PropertyMetadataInterface", got: "%s".', \is_object($propertyMetadata) ? \get_class($propertyMetadata) : \gettype($propertyMetadata)));
}
$propertyValue = $propertyMetadata->getPropertyValue($object);
@ -597,11 +573,7 @@ class RecursiveContextualValidator implements ContextualValidatorInterface
// If TRAVERSE, fail if we have no Traversable
if (!$object instanceof \Traversable) {
throw new ConstraintDefinitionException(sprintf(
'Traversal was enabled for "%s", but this class '.
'does not implement "\Traversable".',
\get_class($object)
));
throw new ConstraintDefinitionException(sprintf('Traversal was enabled for "%s", but this class does not implement "\Traversable".', \get_class($object)));
}
$this->validateEachObjectIn(