Consistently throw exceptions on a single line

This commit is contained in:
Nicolas Grekas 2018-09-08 14:44:02 +02:00
parent 40fff43ea9
commit 721dc8661f
67 changed files with 130 additions and 594 deletions

View File

@ -530,10 +530,7 @@ class EntityChoiceList extends ObjectChoiceList
private function getIdentifierValues($entity) private function getIdentifierValues($entity)
{ {
if (!$this->em->contains($entity)) { if (!$this->em->contains($entity)) {
throw new RuntimeException( throw new RuntimeException('Entities passed to the choice field must be managed. Maybe persist them in the entity manager?');
'Entities passed to the choice field must be managed. Maybe '.
'persist them in the entity manager?'
);
} }
$this->em->initializeObject($entity); $this->em->initializeObject($entity);

View File

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

View File

@ -152,14 +152,7 @@ class Router extends BaseRouter implements WarmableInterface
return (string) $resolved; return (string) $resolved;
} }
throw new RuntimeException(sprintf( 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)));
'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); }, $value);
return str_replace('%%', '%', $escapedValue); return str_replace('%%', '%', $escapedValue);

View File

@ -94,10 +94,7 @@ class GuardAuthenticationFactory implements SecurityFactoryInterface
if ($defaultEntryPointId) { if ($defaultEntryPointId) {
// explode if they've configured the entry_point, but there is already one // explode if they've configured the entry_point, but there is already one
if ($config['entry_point']) { if ($config['entry_point']) {
throw new \LogicException(sprintf( 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']));
'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; return $defaultEntryPointId;
@ -115,9 +112,6 @@ class GuardAuthenticationFactory implements SecurityFactoryInterface
} }
// we have multiple entry points - we must ask them to configure one // we have multiple entry points - we must ask them to configure one
throw new \LogicException(sprintf( 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)));
'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) protected function finalizeValue($value)
{ {
if (false === $value) { if (false === $value) {
$msg = sprintf('Unsetting key for path "%s", value: %s', $this->getPath(), json_encode($value)); throw new UnsetKeyException(sprintf('Unsetting key for path "%s", value: %s', $this->getPath(), json_encode($value)));
throw new UnsetKeyException($msg);
} }
foreach ($this->children as $name => $child) { foreach ($this->children as $name => $child) {
if (!array_key_exists($name, $value)) { if (!array_key_exists($name, $value)) {
if ($child->isRequired()) { if ($child->isRequired()) {
$msg = sprintf('The child node "%s" at path "%s" must be configured.', $name, $this->getPath()); $ex = new InvalidConfigurationException(sprintf('The child node "%s" at path "%s" must be configured.', $name, $this->getPath()));
$ex = new InvalidConfigurationException($msg);
$ex->setPath($this->getPath()); $ex->setPath($this->getPath());
throw $ex; throw $ex;
@ -260,11 +258,7 @@ class ArrayNode extends BaseNode implements PrototypeNodeInterface
protected function validateType($value) protected function validateType($value)
{ {
if (!\is_array($value) && (!$this->allowFalse || false !== $value)) { if (!\is_array($value) && (!$this->allowFalse || false !== $value)) {
$ex = new InvalidTypeException(sprintf( $ex = new InvalidTypeException(sprintf('Invalid type for path "%s". Expected array, but got %s', $this->getPath(), \gettype($value)));
'Invalid type for path "%s". Expected array, but got %s',
$this->getPath(),
\gettype($value)
));
if ($hint = $this->getInfo()) { if ($hint = $this->getInfo()) {
$ex->addHint($hint); $ex->addHint($hint);
} }
@ -303,8 +297,7 @@ class ArrayNode extends BaseNode implements PrototypeNodeInterface
// if extra fields are present, throw exception // if extra fields are present, throw exception
if (\count($value) && !$this->ignoreExtraKeys) { 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(sprintf('Unrecognized option%s "%s" under "%s"', 1 === \count($value) ? '' : 's', implode(', ', array_keys($value)), $this->getPath()));
$ex = new InvalidConfigurationException($msg);
$ex->setPath($this->getPath()); $ex->setPath($this->getPath());
throw $ex; throw $ex;
@ -363,13 +356,7 @@ class ArrayNode extends BaseNode implements PrototypeNodeInterface
// no conflict // no conflict
if (!array_key_exists($k, $leftSide)) { if (!array_key_exists($k, $leftSide)) {
if (!$this->allowNewKeys) { if (!$this->allowNewKeys) {
$ex = new InvalidConfigurationException(sprintf( $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()));
'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()); $ex->setPath($this->getPath());
throw $ex; throw $ex;

View File

@ -205,12 +205,7 @@ abstract class BaseNode implements NodeInterface
final public function merge($leftSide, $rightSide) final public function merge($leftSide, $rightSide)
{ {
if (!$this->allowOverwrite) { if (!$this->allowOverwrite) {
throw new ForbiddenOverwriteException(sprintf( 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()));
'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()
));
} }
$this->validateType($leftSide); $this->validateType($leftSide);

View File

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

View File

@ -411,27 +411,19 @@ class ArrayNodeDefinition extends NodeDefinition implements ParentNodeDefinition
$path = $node->getPath(); $path = $node->getPath();
if (null !== $this->key) { if (null !== $this->key) {
throw new InvalidDefinitionException( throw new InvalidDefinitionException(sprintf('->useAttributeAsKey() is not applicable to concrete nodes at path "%s"', $path));
sprintf('->useAttributeAsKey() is not applicable to concrete nodes at path "%s"', $path)
);
} }
if (true === $this->atLeastOne) { if (true === $this->atLeastOne) {
throw new InvalidDefinitionException( throw new InvalidDefinitionException(sprintf('->requiresAtLeastOneElement() is not applicable to concrete nodes at path "%s"', $path));
sprintf('->requiresAtLeastOneElement() is not applicable to concrete nodes at path "%s"', $path)
);
} }
if ($this->default) { if ($this->default) {
throw new InvalidDefinitionException( throw new InvalidDefinitionException(sprintf('->defaultValue() is not applicable to concrete nodes at path "%s"', $path));
sprintf('->defaultValue() is not applicable to concrete nodes at path "%s"', $path)
);
} }
if (false !== $this->addDefaultChildren) { if (false !== $this->addDefaultChildren) {
throw new InvalidDefinitionException( throw new InvalidDefinitionException(sprintf('->addDefaultChildrenIfNoneSet() is not applicable to concrete nodes at path "%s"', $path));
sprintf('->addDefaultChildrenIfNoneSet() is not applicable to concrete nodes at path "%s"', $path)
);
} }
} }
@ -445,28 +437,20 @@ class ArrayNodeDefinition extends NodeDefinition implements ParentNodeDefinition
$path = $node->getPath(); $path = $node->getPath();
if ($this->addDefaults) { if ($this->addDefaults) {
throw new InvalidDefinitionException( throw new InvalidDefinitionException(sprintf('->addDefaultsIfNotSet() is not applicable to prototype nodes at path "%s"', $path));
sprintf('->addDefaultsIfNotSet() is not applicable to prototype nodes at path "%s"', $path)
);
} }
if (false !== $this->addDefaultChildren) { if (false !== $this->addDefaultChildren) {
if ($this->default) { if ($this->default) {
throw new InvalidDefinitionException( throw new InvalidDefinitionException(sprintf('A default value and default children might not be used together at path "%s"', $path));
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)) { if (null !== $this->key && (null === $this->addDefaultChildren || \is_int($this->addDefaultChildren) && $this->addDefaultChildren > 0)) {
throw new InvalidDefinitionException( throw new InvalidDefinitionException(sprintf('->addDefaultChildrenIfNoneSet() should set default children names as ->useAttributeAsKey() is used at path "%s"', $path));
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))) { if (null === $this->key && (\is_string($this->addDefaultChildren) || \is_array($this->addDefaultChildren))) {
throw new InvalidDefinitionException( throw new InvalidDefinitionException(sprintf('->addDefaultChildrenIfNoneSet() might not set default children names as ->useAttributeAsKey() is not used at path "%s"', $path));
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); $value = parent::finalizeValue($value);
if (!\in_array($value, $this->values, true)) { if (!\in_array($value, $this->values, true)) {
$ex = new InvalidConfigurationException(sprintf( $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))));
'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()); $ex->setPath($this->getPath());
throw $ex; throw $ex;

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -64,13 +64,7 @@ class CheckDefinitionValidityPass implements CompilerPassInterface
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)); 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));
} }
throw new RuntimeException(sprintf( 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));
'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 // tag attribute values must be scalars

View File

@ -94,12 +94,7 @@ class CheckReferenceValidityPass implements CompilerPassInterface
$targetDefinition = $this->getDefinition((string) $argument); $targetDefinition = $this->getDefinition((string) $argument);
if (null !== $targetDefinition && $targetDefinition->isAbstract()) { if (null !== $targetDefinition && $targetDefinition->isAbstract()) {
throw new RuntimeException(sprintf( 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, $argument));
'The definition "%s" has a reference to an abstract definition "%s". '
.'Abstract definitions cannot be the target of references.',
$this->currentId,
$argument
));
} }
$this->validateScope($argument, $targetDefinition); $this->validateScope($argument, $targetDefinition);

View File

@ -543,13 +543,7 @@ EOF
// can it be handled by an extension? // can it be handled by an extension?
if (!$this->container->hasExtension($node->namespaceURI)) { if (!$this->container->hasExtension($node->namespaceURI)) {
$extensionNamespaces = array_filter(array_map(function ($ext) { return $ext->getNamespace(); }, $this->container->getExtensions())); $extensionNamespaces = array_filter(array_map(function ($ext) { return $ext->getNamespace(); }, $this->container->getExtensions()));
throw new InvalidArgumentException(sprintf( 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'));
'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

@ -396,13 +396,7 @@ class YamlFileLoader extends FileLoader
if (!$this->container->hasExtension($namespace)) { if (!$this->container->hasExtension($namespace)) {
$extensionNamespaces = array_filter(array_map(function ($ext) { return $ext->getAlias(); }, $this->container->getExtensions())); $extensionNamespaces = array_filter(array_map(function ($ext) { return $ext->getAlias(); }, $this->container->getExtensions()));
throw new InvalidArgumentException(sprintf( 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'));
'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

@ -161,7 +161,7 @@ class FilesystemTest extends FilesystemTestCase
*/ */
public function testCopyForOriginUrlsAndExistingLocalFileDefaultsToCopy() 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.'); $this->markTestSkipped('"https" stream wrapper is not enabled.');
} }
$sourceFilePath = 'https://symfony.com/images/common/logo/logo_symfony_header.png'; $sourceFilePath = 'https://symfony.com/images/common/logo/logo_symfony_header.png';

View File

@ -70,10 +70,7 @@ class ArrayKeyChoiceList extends ArrayChoiceList
public static function toArrayKey($choice) public static function toArrayKey($choice)
{ {
if (!is_scalar($choice) && null !== $choice) { if (!is_scalar($choice) && null !== $choice) {
throw new InvalidArgumentException(sprintf( throw new InvalidArgumentException(sprintf('The value of type "%s" cannot be converted to a valid array key.', \gettype($choice)));
'The value of type "%s" cannot be converted to a valid array key.',
\gettype($choice)
));
} }
if (\is_bool($choice) || (string) (int) $choice === (string) $choice) { if (\is_bool($choice) || (string) (int) $choice === (string) $choice) {

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -66,10 +66,7 @@ class FixCheckboxInputListener implements EventSubscriberInterface
} }
if (\count($submittedValues) > 0) { if (\count($submittedValues) > 0) {
throw new TransformationFailedException(sprintf( throw new TransformationFailedException(sprintf('The following choices were not found: "%s"', implode('", "', array_keys($submittedValues))));
'The following choices were not found: "%s"',
implode('", "', array_keys($submittedValues))
));
} }
} elseif ('' === $data || null === $data) { } elseif ('' === $data || null === $data) {
// Empty values are always accepted. // Empty values are always accepted.

View File

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

View File

@ -43,13 +43,7 @@ class DependencyInjectionExtension implements FormExtensionInterface
// BC: validate result of getName() for legacy names (non-FQCN) // BC: validate result of getName() for legacy names (non-FQCN)
if ($name !== \get_class($type) && $type->getName() !== $name) { if ($name !== \get_class($type) && $type->getName() !== $name) {
throw new InvalidArgumentException( throw new InvalidArgumentException(sprintf('The type name specified for the service "%s" does not match the actual name. Expected "%s", given "%s"', $this->typeServiceIds[$name], $name, $type->getName()));
sprintf('The type name specified for the service "%s" does not match the actual name. Expected "%s", given "%s"',
$this->typeServiceIds[$name],
$name,
$type->getName()
)
);
} }
return $type; return $type;
@ -70,13 +64,7 @@ class DependencyInjectionExtension implements FormExtensionInterface
// validate result of getExtendedType() to ensure it is consistent with the service definition // validate result of getExtendedType() to ensure it is consistent with the service definition
if ($extension->getExtendedType() !== $name) { if ($extension->getExtendedType() !== $name) {
throw new InvalidArgumentException( 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()));
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

@ -359,13 +359,7 @@ class Form implements \IteratorAggregate, FormInterface
? 'an instance of class '.\get_class($viewData) ? 'an instance of class '.\get_class($viewData)
: 'a(n) '.\gettype($viewData); : 'a(n) '.\gettype($viewData);
throw new LogicException( 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.'.');
'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.'.'
);
} }
} }
@ -915,11 +909,7 @@ class Form implements \IteratorAggregate, FormInterface
$child = $this->config->getFormFactory()->createNamed($child, $type, null, $options); $child = $this->config->getFormFactory()->createNamed($child, $type, null, $options);
} }
} elseif ($child->getConfig()->getAutoInitialize()) { } elseif ($child->getConfig()->getAutoInitialize()) {
throw new RuntimeException(sprintf( 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()));
'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; $this->children[$child->getName()] = $child;
@ -1093,11 +1083,7 @@ class Form implements \IteratorAggregate, FormInterface
$value = $transformer->transform($value); $value = $transformer->transform($value);
} }
} catch (TransformationFailedException $exception) { } catch (TransformationFailedException $exception) {
throw new TransformationFailedException( throw new TransformationFailedException('Unable to transform value for property path "'.$this->getPropertyPath().'": '.$exception->getMessage(), $exception->getCode(), $exception);
'Unable to transform value for property path "'.$this->getPropertyPath().'": '.$exception->getMessage(),
$exception->getCode(),
$exception
);
} }
return $value; return $value;
@ -1121,11 +1107,7 @@ class Form implements \IteratorAggregate, FormInterface
$value = $transformers[$i]->reverseTransform($value); $value = $transformers[$i]->reverseTransform($value);
} }
} catch (TransformationFailedException $exception) { } catch (TransformationFailedException $exception) {
throw new TransformationFailedException( throw new TransformationFailedException('Unable to reverse value for property path "'.$this->getPropertyPath().'": '.$exception->getMessage(), $exception->getCode(), $exception);
'Unable to reverse value for property path "'.$this->getPropertyPath().'": '.$exception->getMessage(),
$exception->getCode(),
$exception
);
} }
return $value; return $value;
@ -1156,11 +1138,7 @@ class Form implements \IteratorAggregate, FormInterface
$value = $transformer->transform($value); $value = $transformer->transform($value);
} }
} catch (TransformationFailedException $exception) { } catch (TransformationFailedException $exception) {
throw new TransformationFailedException( throw new TransformationFailedException('Unable to transform value for property path "'.$this->getPropertyPath().'": '.$exception->getMessage(), $exception->getCode(), $exception);
'Unable to transform value for property path "'.$this->getPropertyPath().'": '.$exception->getMessage(),
$exception->getCode(),
$exception
);
} }
return $value; return $value;
@ -1188,11 +1166,7 @@ class Form implements \IteratorAggregate, FormInterface
$value = $transformers[$i]->reverseTransform($value); $value = $transformers[$i]->reverseTransform($value);
} }
} catch (TransformationFailedException $exception) { } catch (TransformationFailedException $exception) {
throw new TransformationFailedException( throw new TransformationFailedException('Unable to reverse value for property path "'.$this->getPropertyPath().'": '.$exception->getMessage(), $exception->getCode(), $exception);
'Unable to reverse value for property path "'.$this->getPropertyPath().'": '.$exception->getMessage(),
$exception->getCode(),
$exception
);
} }
return $value; return $value;

View File

@ -821,11 +821,7 @@ class FormConfigBuilder implements FormConfigBuilderInterface
$upperCaseMethod = strtoupper($method); $upperCaseMethod = strtoupper($method);
if (!\in_array($upperCaseMethod, self::$allowedMethods)) { if (!\in_array($upperCaseMethod, self::$allowedMethods)) {
throw new InvalidArgumentException(sprintf( throw new InvalidArgumentException(sprintf('The form method is "%s", but should be one of "%s".', $method, implode('", "', self::$allowedMethods)));
'The form method is "%s", but should be one of "%s".',
$method,
implode('", "', self::$allowedMethods)
));
} }
$this->method = $upperCaseMethod; $this->method = $upperCaseMethod;
@ -892,10 +888,7 @@ class FormConfigBuilder implements FormConfigBuilderInterface
} }
if (!self::isValidName($name)) { if (!self::isValidName($name)) {
throw new InvalidArgumentException(sprintf( 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));
'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

@ -50,12 +50,7 @@ class FormErrorIterator implements \RecursiveIterator, \SeekableIterator, \Array
{ {
foreach ($errors as $error) { foreach ($errors as $error) {
if (!($error instanceof FormError || $error instanceof self)) { if (!($error instanceof FormError || $error instanceof self)) {
throw new InvalidArgumentException(sprintf( 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)));
'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

@ -86,11 +86,7 @@ class ResolvedFormType implements ResolvedFormTypeInterface
// As of Symfony 2.8, getName() returns the FQCN by default // As of Symfony 2.8, getName() returns the FQCN by default
// Otherwise check that the name matches the old naming restrictions // Otherwise check that the name matches the old naming restrictions
if ($hasCustomName && !preg_match('/^[a-z0-9_]*$/i', $name)) { if ($hasCustomName && !preg_match('/^[a-z0-9_]*$/i', $name)) {
throw new InvalidArgumentException(sprintf( throw new InvalidArgumentException(sprintf('The "%s" form type name ("%s") is not valid. Names must only contain letters, numbers, and "_".', \get_class($innerType), $name));
'The "%s" form type name ("%s") is not valid. Names must only contain letters, numbers, and "_".',
\get_class($innerType),
$name
));
} }
foreach ($typeExtensions as $extension) { foreach ($typeExtensions as $extension) {

View File

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

View File

@ -43,9 +43,7 @@ class MemcacheSessionHandler implements \SessionHandlerInterface
public function __construct(\Memcache $memcache, array $options = array()) public function __construct(\Memcache $memcache, array $options = array())
{ {
if ($diff = array_diff(array_keys($options), array('prefix', 'expiretime'))) { if ($diff = array_diff(array_keys($options), array('prefix', 'expiretime'))) {
throw new \InvalidArgumentException(sprintf( throw new \InvalidArgumentException(sprintf('The following options are not supported "%s"', implode(', ', $diff)));
'The following options are not supported "%s"', implode(', ', $diff)
));
} }
$this->memcache = $memcache; $this->memcache = $memcache;

View File

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

View File

@ -86,10 +86,7 @@ abstract class Bundle implements BundleInterface
$expectedAlias = Container::underscore($basename); $expectedAlias = Container::underscore($basename);
if ($expectedAlias != $extension->getAlias()) { if ($expectedAlias != $extension->getAlias()) {
throw new \LogicException(sprintf( 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()));
'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; $this->extension = $extension;

View File

@ -265,11 +265,7 @@ abstract class Kernel implements KernelInterface, TerminableInterface
foreach ($bundles as $bundle) { foreach ($bundles as $bundle) {
if ($isResource && file_exists($file = $dir.'/'.$bundle->getName().$overridePath)) { if ($isResource && file_exists($file = $dir.'/'.$bundle->getName().$overridePath)) {
if (null !== $resourceBundle) { 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.', 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.'/'.$bundles[0]->getName().$overridePath));
$file,
$resourceBundle,
$dir.'/'.$bundles[0]->getName().$overridePath
));
} }
if ($first) { if ($first) {

View File

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

View File

@ -41,11 +41,7 @@ class IntlBundleReader implements BundleReaderInterface
// The bundle is NULL if the path does not look like a resource bundle // The bundle is NULL if the path does not look like a resource bundle
// (i.e. contain a bunch of *.res files) // (i.e. contain a bunch of *.res files)
if (null === $bundle) { if (null === $bundle) {
throw new ResourceBundleNotFoundException(sprintf( throw new ResourceBundleNotFoundException(sprintf('The resource bundle "%s/%s.res" could not be found.', $path, $locale));
'The resource bundle "%s/%s.res" could not be found.',
$path,
$locale
));
} }
// Other possible errors are U_USING_FALLBACK_WARNING and U_ZERO_ERROR, // 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)) { if (!file_exists($fileName)) {
throw new ResourceBundleNotFoundException(sprintf( throw new ResourceBundleNotFoundException(sprintf('The resource bundle "%s" does not exist.', $fileName));
'The resource bundle "%s" does not exist.',
$fileName
));
} }
if (!is_file($fileName)) { if (!is_file($fileName)) {
throw new RuntimeException(sprintf( throw new RuntimeException(sprintf('The resource bundle "%s" is not a file.', $fileName));
'The resource bundle "%s" is not a file.',
$fileName
));
} }
$data = json_decode(file_get_contents($fileName), true); $data = json_decode(file_get_contents($fileName), true);
if (null === $data) { if (null === $data) {
throw new RuntimeException(sprintf( throw new RuntimeException(sprintf('The resource bundle "%s" contains invalid JSON: %s', $fileName, json_last_error_msg()));
'The resource bundle "%s" contains invalid JSON: %s',
$fileName,
json_last_error_msg()
));
} }
return $data; return $data;

View File

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

View File

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

View File

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

View File

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

View File

@ -106,10 +106,7 @@ class TimeZoneTransformer extends Transformer
$signal = '-' == $matches['signal'] ? '+' : '-'; $signal = '-' == $matches['signal'] ? '+' : '-';
if (0 < $minutes) { if (0 < $minutes) {
throw new NotImplementedException(sprintf( 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));
'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 : ''); return 'Etc/GMT'.(0 !== $hours ? $signal.$hours : '');

View File

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

View File

@ -388,11 +388,7 @@ class OptionsResolver implements Options, OptionsResolverInterface
} }
if (!isset($this->defined[$option])) { if (!isset($this->defined[$option])) {
throw new UndefinedOptionsException(sprintf( throw new UndefinedOptionsException(sprintf('The option "%s" does not exist. Defined options are: "%s".', $option, implode('", "', array_keys($this->defined))));
'The option "%s" does not exist. Defined options are: "%s".',
$option,
implode('", "', array_keys($this->defined))
));
} }
$this->normalizers[$option] = $normalizer; $this->normalizers[$option] = $normalizer;
@ -466,11 +462,7 @@ class OptionsResolver implements Options, OptionsResolverInterface
} }
if (!isset($this->defined[$option])) { if (!isset($this->defined[$option])) {
throw new UndefinedOptionsException(sprintf( throw new UndefinedOptionsException(sprintf('The option "%s" does not exist. Defined options are: "%s".', $option, implode('", "', array_keys($this->defined))));
'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); $this->allowedValues[$option] = \is_array($allowedValues) ? $allowedValues : array($allowedValues);
@ -522,11 +514,7 @@ class OptionsResolver implements Options, OptionsResolverInterface
} }
if (!isset($this->defined[$option])) { if (!isset($this->defined[$option])) {
throw new UndefinedOptionsException(sprintf( throw new UndefinedOptionsException(sprintf('The option "%s" does not exist. Defined options are: "%s".', $option, implode('", "', array_keys($this->defined))));
'The option "%s" does not exist. Defined options are: "%s".',
$option,
implode('", "', array_keys($this->defined))
));
} }
if (!\is_array($allowedValues)) { if (!\is_array($allowedValues)) {
@ -578,11 +566,7 @@ class OptionsResolver implements Options, OptionsResolverInterface
} }
if (!isset($this->defined[$option])) { if (!isset($this->defined[$option])) {
throw new UndefinedOptionsException(sprintf( throw new UndefinedOptionsException(sprintf('The option "%s" does not exist. Defined options are: "%s".', $option, implode('", "', array_keys($this->defined))));
'The option "%s" does not exist. Defined options are: "%s".',
$option,
implode('", "', array_keys($this->defined))
));
} }
$this->allowedTypes[$option] = (array) $allowedTypes; $this->allowedTypes[$option] = (array) $allowedTypes;
@ -628,11 +612,7 @@ class OptionsResolver implements Options, OptionsResolverInterface
} }
if (!isset($this->defined[$option])) { if (!isset($this->defined[$option])) {
throw new UndefinedOptionsException(sprintf( throw new UndefinedOptionsException(sprintf('The option "%s" does not exist. Defined options are: "%s".', $option, implode('", "', array_keys($this->defined))));
'The option "%s" does not exist. Defined options are: "%s".',
$option,
implode('", "', array_keys($this->defined))
));
} }
if (!isset($this->allowedTypes[$option])) { if (!isset($this->allowedTypes[$option])) {
@ -737,11 +717,7 @@ class OptionsResolver implements Options, OptionsResolverInterface
ksort($clone->defined); ksort($clone->defined);
ksort($diff); ksort($diff);
throw new UndefinedOptionsException(sprintf( 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))));
(\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 // Override options set by the user
@ -756,10 +732,7 @@ class OptionsResolver implements Options, OptionsResolverInterface
if (\count($diff) > 0) { if (\count($diff) > 0) {
ksort($diff); ksort($diff);
throw new MissingOptionsException(sprintf( throw new MissingOptionsException(sprintf(\count($diff) > 1 ? 'The required options "%s" are missing.' : 'The required option "%s" is missing.', implode('", "', array_keys($diff))));
\count($diff) > 1 ? 'The required options "%s" are missing.' : 'The required option "%s" is missing.',
implode('", "', array_keys($diff))
));
} }
// Lock the container // Lock the container
@ -803,17 +776,10 @@ class OptionsResolver implements Options, OptionsResolverInterface
// Check whether the option is set at all // Check whether the option is set at all
if (!array_key_exists($option, $this->defaults)) { if (!array_key_exists($option, $this->defaults)) {
if (!isset($this->defined[$option])) { if (!isset($this->defined[$option])) {
throw new NoSuchOptionException(sprintf( throw new NoSuchOptionException(sprintf('The option "%s" does not exist. Defined options are: "%s".', $option, implode('", "', array_keys($this->defined))));
'The option "%s" does not exist. Defined options are: "%s".',
$option,
implode('", "', array_keys($this->defined))
));
} }
throw new NoSuchOptionException(sprintf( 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));
'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]; $value = $this->defaults[$option];
@ -823,10 +789,7 @@ class OptionsResolver implements Options, OptionsResolverInterface
// If the closure is already being called, we have a cyclic // If the closure is already being called, we have a cyclic
// dependency // dependency
if (isset($this->calling[$option])) { if (isset($this->calling[$option])) {
throw new OptionDefinitionException(sprintf( throw new OptionDefinitionException(sprintf('The options "%s" have a cyclic dependency.', implode('", "', array_keys($this->calling))));
'The options "%s" have a cyclic dependency.',
implode('", "', array_keys($this->calling))
));
} }
// The following section must be protected from cyclic // The following section must be protected from cyclic
@ -872,14 +835,7 @@ class OptionsResolver implements Options, OptionsResolverInterface
} }
if (!$valid) { if (!$valid) {
throw new InvalidOptionsException(sprintf( throw new InvalidOptionsException(sprintf('The option "%s" with value %s is expected to be of type "%s", but is of type "%s".', $option, $this->formatValue($value), implode('" or "', $this->allowedTypes[$option]), $this->formatTypeOf($value)));
'The option "%s" with value %s is expected to be of type '.
'"%s", but is of type "%s".',
$option,
$this->formatValue($value),
implode('" or "', $this->allowedTypes[$option]),
$this->formatTypeOf($value)
));
} }
} }
@ -928,10 +884,7 @@ class OptionsResolver implements Options, OptionsResolverInterface
// If the closure is already being called, we have a cyclic // If the closure is already being called, we have a cyclic
// dependency // dependency
if (isset($this->calling[$option])) { if (isset($this->calling[$option])) {
throw new OptionDefinitionException(sprintf( throw new OptionDefinitionException(sprintf('The options "%s" have a cyclic dependency.', implode('", "', array_keys($this->calling))));
'The options "%s" have a cyclic dependency.',
implode('", "', array_keys($this->calling))
));
} }
$normalizer = $this->normalizers[$option]; $normalizer = $this->normalizers[$option];

View File

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

View File

@ -77,12 +77,7 @@ class PropertyPath implements \IteratorAggregate, PropertyPathInterface
return; return;
} }
if (!\is_string($propertyPath)) { if (!\is_string($propertyPath)) {
throw new InvalidArgumentException(sprintf( 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)));
'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) { if ('' === $propertyPath) {
@ -113,12 +108,7 @@ class PropertyPath implements \IteratorAggregate, PropertyPathInterface
} }
if ('' !== $remaining) { if ('' !== $remaining) {
throw new InvalidPropertyPathException(sprintf( throw new InvalidPropertyPathException(sprintf('Could not parse property path "%s". Unexpected token "%s" at position %d', $propertyPath, $remaining[0], $position));
'Could not parse property path "%s". Unexpected token "%s" at position %d',
$propertyPath,
$remaining[0],
$position
));
} }
$this->length = \count($this->elements); $this->length = \count($this->elements);

View File

@ -209,28 +209,16 @@ class YamlFileLoader extends FileLoader
throw new \InvalidArgumentException(sprintf('The definition of "%s" in "%s" must be a YAML array.', $name, $path)); 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)) { if ($extraKeys = array_diff(array_keys($config), self::$availableKeys)) {
throw new \InvalidArgumentException(sprintf( 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)));
'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'])) { if (isset($config['resource']) && isset($config['path'])) {
throw new \InvalidArgumentException(sprintf( 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));
'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'])) { if (!isset($config['resource']) && isset($config['type'])) {
throw new \InvalidArgumentException(sprintf( 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));
'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'])) { if (!isset($config['resource']) && !isset($config['path'])) {
throw new \InvalidArgumentException(sprintf( throw new \InvalidArgumentException(sprintf('You must define a "path" for the route "%s" in file "%s".', $name, $path));
'You must define a "path" for the route "%s" in file "%s".',
$name, $path
));
} }
} }
} }

View File

@ -190,10 +190,7 @@ class GuardAuthenticationListener implements ListenerInterface
} }
if (!$response instanceof Response) { if (!$response instanceof Response) {
throw new \LogicException(sprintf( 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)));
'%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); $this->rememberMeServices->loginSuccess($request, $response, $token);

View File

@ -84,11 +84,7 @@ class GuardAuthenticatorHandler
return $response; return $response;
} }
throw new \UnexpectedValueException(sprintf( 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)));
'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)
));
} }
/** /**
@ -132,11 +128,7 @@ class GuardAuthenticatorHandler
return $response; return $response;
} }
throw new \UnexpectedValueException(sprintf( 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)));
'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

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

View File

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

View File

@ -35,10 +35,7 @@ abstract class AbstractComparison extends Constraint
} }
if (\is_array($options) && !isset($options['value'])) { if (\is_array($options) && !isset($options['value'])) {
throw new ConstraintDefinitionException(sprintf( throw new ConstraintDefinitionException(sprintf('The %s constraint requires the "value" option to be set.', \get_class($this)));
'The %s constraint requires the "value" option to be set.',
\get_class($this)
));
} }
parent::__construct($options); parent::__construct($options);

View File

@ -33,10 +33,7 @@ class CallbackValidator extends ConstraintValidator
} }
if (null !== $constraint->callback && null !== $constraint->methods) { if (null !== $constraint->callback && null !== $constraint->methods) {
throw new ConstraintDefinitionException( throw new ConstraintDefinitionException('The Callback constraint supports either the option "callback" or "methods", but not both at the same time.');
'The Callback constraint supports either the option "callback" '.
'or "methods", but not both at the same time.'
);
} }
// has to be an array so that we can differentiate between callables // has to be an array so that we can differentiate between callables

View File

@ -99,13 +99,7 @@ abstract class Composite extends Constraint
$excessGroups = array_diff($constraint->groups, $this->groups); $excessGroups = array_diff($constraint->groups, $this->groups);
if (\count($excessGroups) > 0) { if (\count($excessGroups) > 0) {
throw new ConstraintDefinitionException(sprintf( 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)));
'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 { } else {
$constraint->groups = $this->groups; $constraint->groups = $this->groups;

View File

@ -145,10 +145,7 @@ class GroupSequence implements \ArrayAccess, \IteratorAggregate, \Countable
@trigger_error('The '.__METHOD__.' method is deprecated since Symfony 2.5 and will be removed in 3.0.', E_USER_DEPRECATED); @trigger_error('The '.__METHOD__.' method is deprecated since Symfony 2.5 and will be removed in 3.0.', E_USER_DEPRECATED);
if (!isset($this->groups[$offset])) { if (!isset($this->groups[$offset])) {
throw new OutOfBoundsException(sprintf( throw new OutOfBoundsException(sprintf('The offset "%s" does not exist.', $offset));
'The offset "%s" does not exist.',
$offset
));
} }
return $this->groups[$offset]; return $this->groups[$offset];

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -34,13 +34,8 @@ class Validator implements ValidatorInterface, Mapping\Factory\MetadataFactoryIn
private $translationDomain; private $translationDomain;
private $objectInitializers; private $objectInitializers;
public function __construct( public function __construct(MetadataFactoryInterface $metadataFactory, ConstraintValidatorFactoryInterface $validatorFactory, TranslatorInterface $translator, $translationDomain = 'validators', array $objectInitializers = array())
MetadataFactoryInterface $metadataFactory, {
ConstraintValidatorFactoryInterface $validatorFactory,
TranslatorInterface $translator,
$translationDomain = 'validators',
array $objectInitializers = array()
) {
$this->metadataFactory = $metadataFactory; $this->metadataFactory = $metadataFactory;
$this->validatorFactory = $validatorFactory; $this->validatorFactory = $validatorFactory;
$this->translator = $translator; $this->translator = $translator;
@ -175,12 +170,7 @@ class Validator implements ValidatorInterface, Mapping\Factory\MetadataFactoryIn
// //
// * Otherwise the validated group is propagated. // * Otherwise the validated group is propagated.
throw new ValidatorException( throw new ValidatorException(sprintf('The constraint %s cannot be validated. Use the method validate() instead.', \get_class($constraint)));
sprintf(
'The constraint %s cannot be validated. Use the method validate() instead.',
\get_class($constraint)
)
);
} }
$context->validateValue($value, $constraint, '', $groups); $context->validateValue($value, $constraint, '', $groups);

View File

@ -162,11 +162,7 @@ class RecursiveContextualValidator implements ContextualValidatorInterface
return $this; return $this;
} }
throw new RuntimeException(sprintf( throw new RuntimeException(sprintf('Cannot validate values of type "%s" automatically. Please provide a constraint.', \gettype($value)));
'Cannot validate values of type "%s" automatically. Please '.
'provide a constraint.',
\gettype($value)
));
} }
/** /**
@ -179,12 +175,7 @@ class RecursiveContextualValidator implements ContextualValidatorInterface
if (!$classMetadata instanceof ClassMetadataInterface) { if (!$classMetadata instanceof ClassMetadataInterface) {
// Cannot be UnsupportedMetadataException because of BC with // Cannot be UnsupportedMetadataException because of BC with
// Symfony < 2.5 // Symfony < 2.5
throw new ValidatorException(sprintf( 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)));
'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); $propertyMetadatas = $classMetadata->getPropertyMetadata($propertyName);
@ -230,12 +221,7 @@ class RecursiveContextualValidator implements ContextualValidatorInterface
if (!$classMetadata instanceof ClassMetadataInterface) { if (!$classMetadata instanceof ClassMetadataInterface) {
// Cannot be UnsupportedMetadataException because of BC with // Cannot be UnsupportedMetadataException because of BC with
// Symfony < 2.5 // Symfony < 2.5
throw new ValidatorException(sprintf( 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)));
'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); $propertyMetadatas = $classMetadata->getPropertyMetadata($propertyName);
@ -331,12 +317,7 @@ class RecursiveContextualValidator implements ContextualValidatorInterface
$classMetadata = $this->metadataFactory->getMetadataFor($object); $classMetadata = $this->metadataFactory->getMetadataFor($object);
if (!$classMetadata instanceof ClassMetadataInterface) { if (!$classMetadata instanceof ClassMetadataInterface) {
throw new UnsupportedMetadataException(sprintf( 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)));
'The metadata factory should return instances of '.
'"Symfony\Component\Validator\Mapping\ClassMetadataInterface", '.
'got: "%s".',
\is_object($classMetadata) ? \get_class($classMetadata) : \gettype($classMetadata)
));
} }
$this->validateClassNode( $this->validateClassNode(
@ -572,12 +553,7 @@ class RecursiveContextualValidator implements ContextualValidatorInterface
// returns two metadata objects, not just one // returns two metadata objects, not just one
foreach ($metadata->getPropertyMetadata($propertyName) as $propertyMetadata) { foreach ($metadata->getPropertyMetadata($propertyName) as $propertyMetadata) {
if (!$propertyMetadata instanceof PropertyMetadataInterface) { if (!$propertyMetadata instanceof PropertyMetadataInterface) {
throw new UnsupportedMetadataException(sprintf( 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)));
'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); $propertyValue = $propertyMetadata->getPropertyValue($object);
@ -618,11 +594,7 @@ class RecursiveContextualValidator implements ContextualValidatorInterface
if (!$object instanceof \Traversable) { if (!$object instanceof \Traversable) {
// Must throw a ConstraintDefinitionException for backwards // Must throw a ConstraintDefinitionException for backwards
// compatibility reasons with Symfony < 2.5 // compatibility reasons with Symfony < 2.5
throw new ConstraintDefinitionException(sprintf( throw new ConstraintDefinitionException(sprintf('Traversal was enabled for "%s", but this class does not implement "\Traversable".', \get_class($object)));
'Traversal was enabled for "%s", but this class '.
'does not implement "\Traversable".',
\get_class($object)
));
} }
$this->validateEachObjectIn( $this->validateEachObjectIn(