From 310945023e8dc1bc7b641924f9a9d61b9399262d Mon Sep 17 00:00:00 2001 From: David Grudl Date: Sun, 29 Aug 2021 22:09:14 +0200 Subject: [PATCH] used sprintf() for error messages --- src/DI/Autowiring.php | 12 ++++- src/DI/Compiler.php | 16 ++++--- src/DI/CompilerExtension.php | 9 ++-- src/DI/Config/Adapters/NeonAdapter.php | 5 ++- src/DI/Config/DefinitionSchema.php | 9 +++- src/DI/Config/Loader.php | 8 ++-- src/DI/Container.php | 36 ++++++++++----- src/DI/ContainerBuilder.php | 14 +++--- src/DI/ContainerLoader.php | 8 ++-- src/DI/Definitions/AccessorDefinition.php | 18 ++++++-- src/DI/Definitions/Definition.php | 6 ++- src/DI/Definitions/FactoryDefinition.php | 18 ++++++-- src/DI/Definitions/LocatorDefinition.php | 7 ++- src/DI/DependencyChecker.php | 2 +- src/DI/Extensions/DecoratorExtension.php | 2 +- src/DI/Extensions/ExtensionsExtension.php | 5 ++- src/DI/Extensions/InjectExtension.php | 5 ++- src/DI/Extensions/SearchExtension.php | 12 ++++- src/DI/Helpers.php | 16 ++++--- src/DI/Resolver.php | 54 ++++++++++++++++------- 20 files changed, 189 insertions(+), 73 deletions(-) diff --git a/src/DI/Autowiring.php b/src/DI/Autowiring.php index f1051e83a..1b95ee0d0 100644 --- a/src/DI/Autowiring.php +++ b/src/DI/Autowiring.php @@ -66,7 +66,11 @@ public function getByType(string $type, bool $throw = false): ?string $hint = count($list) === 2 && ($tmp = strpos($list[0], '.') xor strpos($list[1], '.')) ? '. If you want to overwrite service ' . $list[$tmp ? 0 : 1] . ', give it proper name.' : ''; - throw new ServiceCreationException("Multiple services of type $type found: " . implode(', ', $list) . $hint); + throw new ServiceCreationException(sprintf( + "Multiple services of type $type found: %s%s", + implode(', ', $list), + $hint + )); } } @@ -123,7 +127,11 @@ public function rebuild(): void if ($autowiredType === ContainerBuilder::THIS_SERVICE) { $autowired[$k] = $type; } elseif (!is_a($type, $autowiredType, true)) { - throw new ServiceCreationException("Incompatible class $autowiredType in autowiring definition of service '$name'."); + throw new ServiceCreationException(sprintf( + "Incompatible class %s in autowiring definition of service '%s'.", + $autowiredType, + $name + )); } } } diff --git a/src/DI/Compiler.php b/src/DI/Compiler.php index 281d53123..f55cabe3a 100644 --- a/src/DI/Compiler.php +++ b/src/DI/Compiler.php @@ -65,12 +65,16 @@ public function addExtension(?string $name, CompilerExtension $extension) if ($name === null) { $name = '_' . count($this->extensions); } elseif (isset($this->extensions[$name])) { - throw new Nette\InvalidArgumentException("Name '$name' is already used or reserved."); + throw new Nette\InvalidArgumentException(sprintf("Name '%s' is already used or reserved.", $name)); } $lname = strtolower($name); foreach (array_keys($this->extensions) as $nm) { if ($lname === strtolower((string) $nm)) { - throw new Nette\InvalidArgumentException("Name of extension '$name' has the same name as '$nm' in a case-insensitive manner."); + throw new Nette\InvalidArgumentException(sprintf( + "Name of extension '%s' has the same name as '%s' in a case-insensitive manner.", + $name, + $nm + )); } } $this->extensions[$name] = $extension->setCompiler($this, $name); @@ -238,13 +242,15 @@ public function processExtensions(): void } if ($extra = array_diff_key($this->extensions, $extensions, $first, [self::SERVICES => 1])) { - $extra = implode("', '", array_keys($extra)); - throw new Nette\DeprecatedException("Extensions '$extra' were added while container was being compiled."); + throw new Nette\DeprecatedException(sprintf( + "Extensions '%s' were added while container was being compiled.", + implode("', '", array_keys($extra)) + )); } elseif ($extra = key(array_diff_key($this->configs, $this->extensions))) { $hint = Nette\Utils\Helpers::getSuggestion(array_keys($this->extensions), $extra); throw new InvalidConfigurationException( - "Found section '$extra' in configuration, but corresponding extension is missing" + sprintf("Found section '%s' in configuration, but corresponding extension is missing", $extra) . ($hint ? ", did you mean '$hint'?" : '.') ); } diff --git a/src/DI/CompilerExtension.php b/src/DI/CompilerExtension.php index 29eef3688..a6d45ecd8 100644 --- a/src/DI/CompilerExtension.php +++ b/src/DI/CompilerExtension.php @@ -90,10 +90,11 @@ public function validateConfig(array $expected, array $config = null, string $na if ($extra = array_diff_key((array) $config, $expected)) { $name = $name ? str_replace('.', ' › ', $name) : $this->name; $hint = Nette\Utils\Helpers::getSuggestion(array_keys($expected), key($extra)); - $extra = $hint - ? key($extra) - : implode("', '{$name} › ", array_keys($extra)); - throw new Nette\DI\InvalidConfigurationException("Unknown configuration option '{$name} › {$extra}'" . ($hint ? ", did you mean '{$name} › {$hint}'?" : '.')); + throw new Nette\DI\InvalidConfigurationException(sprintf( + "Unknown configuration option '%s › %s'", + $name, + $hint ? key($extra) : implode("', '{$name} › ", array_keys($extra)) + ) . ($hint ? ", did you mean '{$name} › {$hint}'?" : '.')); } return Nette\Schema\Helpers::merge($config, $expected); } diff --git a/src/DI/Config/Adapters/NeonAdapter.php b/src/DI/Config/Adapters/NeonAdapter.php index 43f370724..79dcc3a46 100644 --- a/src/DI/Config/Adapters/NeonAdapter.php +++ b/src/DI/Config/Adapters/NeonAdapter.php @@ -42,7 +42,10 @@ public function process(array $arr): array foreach ($arr as $key => $val) { if (is_string($key) && substr($key, -1) === self::PREVENT_MERGING_SUFFIX) { if (!is_array($val) && $val !== null) { - throw new Nette\DI\InvalidConfigurationException("Replacing operator is available only for arrays, item '$key' is not array."); + throw new Nette\DI\InvalidConfigurationException(sprintf( + "Replacing operator is available only for arrays, item '%s' is not array.", + $key + )); } $key = substr($key, 0, -1); $val[Helpers::PREVENT_MERGING] = true; diff --git a/src/DI/Config/DefinitionSchema.php b/src/DI/Config/DefinitionSchema.php index e1a394cbf..b12d647fa 100644 --- a/src/DI/Config/DefinitionSchema.php +++ b/src/DI/Config/DefinitionSchema.php @@ -95,7 +95,7 @@ public function normalize($def, Context $context) if (isset($def['class']) && !isset($def['type'])) { if ($def['class'] instanceof Statement) { $key = end($context->path); - trigger_error("Service '$key': option 'class' should be changed to 'factory'.", E_USER_DEPRECATED); + trigger_error(sprintf("Service '%s': option 'class' should be changed to 'factory'.", $key), E_USER_DEPRECATED); $def['factory'] = $def['class']; unset($def['class']); } elseif (!isset($def['factory']) && !isset($def['dynamic']) && !isset($def['imported'])) { @@ -107,7 +107,12 @@ public function normalize($def, Context $context) foreach (['class' => 'type', 'dynamic' => 'imported'] as $alias => $original) { if (array_key_exists($alias, $def)) { if (array_key_exists($original, $def)) { - throw new Nette\DI\InvalidConfigurationException("Options '$alias' and '$original' are aliases, use only '$original'."); + throw new Nette\DI\InvalidConfigurationException(sprintf( + "Options '%s' and '%s' are aliases, use only '%s'.", + $alias, + $original, + $original + )); } $def[$original] = $def[$alias]; unset($def[$alias]); diff --git a/src/DI/Config/Loader.php b/src/DI/Config/Loader.php index 6070d8971..968fd2bad 100644 --- a/src/DI/Config/Loader.php +++ b/src/DI/Config/Loader.php @@ -40,11 +40,11 @@ class Loader public function load(string $file, ?bool $merge = true): array { if (!is_file($file) || !is_readable($file)) { - throw new Nette\FileNotFoundException("File '$file' is missing or is not readable."); + throw new Nette\FileNotFoundException(sprintf("File '%s' is missing or is not readable.", $file)); } if (isset($this->loadedFiles[$file])) { - throw new Nette\InvalidStateException("Recursive included file '$file'"); + throw new Nette\InvalidStateException(sprintf("Recursive included file '%s'", $file)); } $this->loadedFiles[$file] = true; @@ -77,7 +77,7 @@ public function load(string $file, ?bool $merge = true): array public function save(array $data, string $file): void { if (file_put_contents($file, $this->getAdapter($file)->dump($data)) === false) { - throw new Nette\IOException("Cannot write file '$file'."); + throw new Nette\IOException(sprintf("Cannot write file '%s'.", $file)); } } @@ -118,7 +118,7 @@ private function getAdapter(string $file): Adapter { $extension = strtolower(pathinfo($file, PATHINFO_EXTENSION)); if (!isset($this->adapters[$extension])) { - throw new Nette\InvalidArgumentException("Unknown file extension '$file'."); + throw new Nette\InvalidArgumentException(sprintf("Unknown file extension '%s'.", $file)); } return is_object($this->adapters[$extension]) ? $this->adapters[$extension] diff --git a/src/DI/Container.php b/src/DI/Container.php index a02c802cd..f91cad7bd 100644 --- a/src/DI/Container.php +++ b/src/DI/Container.php @@ -69,7 +69,7 @@ public function addService(string $name, $service) { $name = $this->aliases[$name] ?? $name; if (isset($this->instances[$name])) { - throw new Nette\InvalidStateException("Service '$name' already exists."); + throw new Nette\InvalidStateException(sprintf("Service '%s' already exists.", $name)); } elseif (!is_object($service)) { throw new Nette\InvalidArgumentException(sprintf("Service '%s' must be a object, %s given.", $name, gettype($service))); @@ -83,7 +83,12 @@ public function addService(string $name, $service) $this->types[$name] = $type; } elseif (($expectedType = $this->getServiceType($name)) && !is_a($type, $expectedType, true)) { - throw new Nette\InvalidArgumentException("Service '$name' must be instance of $expectedType, " . ($type ? "$type given." : 'add typehint to closure.')); + throw new Nette\InvalidArgumentException(sprintf( + "Service '%s' must be instance of %s, %s.", + $name, + $expectedType, + $type ? "$type given" : 'add typehint to closure' + )); } if ($service instanceof \Closure) { @@ -153,7 +158,7 @@ public function getServiceType(string $name): string return $type ? $type->getName() : ''; } else { - throw new MissingServiceException("Service '$name' not found."); + throw new MissingServiceException(sprintf("Service '%s' not found.", $name)); } } @@ -174,7 +179,7 @@ public function hasService(string $name): bool public function isCreated(string $name): bool { if (!$this->hasService($name)) { - throw new MissingServiceException("Service '$name' not found."); + throw new MissingServiceException(sprintf("Service '%s' not found.", $name)); } $name = $this->aliases[$name] ?? $name; return isset($this->instances[$name]); @@ -195,7 +200,7 @@ public function createService(string $name, array $args = []) throw new Nette\InvalidStateException(sprintf('Circular reference detected for services: %s.', implode(', ', array_keys($this->creating)))); } elseif ($cb === null) { - throw new MissingServiceException("Service '$name' not found."); + throw new MissingServiceException(sprintf("Service '%s' not found.", $name)); } try { @@ -209,7 +214,10 @@ public function createService(string $name, array $args = []) } if (!is_object($service)) { - throw new Nette\UnexpectedValueException("Unable to create service '$name', value returned by " . ($cb instanceof \Closure ? 'closure' : "method $method()") . ' is not object.'); + throw new Nette\UnexpectedValueException(sprintf( + "Unable to create service '$name', value returned by %s is not object.", + $cb instanceof \Closure ? 'closure' : "method $method()" + )); } return $service; @@ -230,7 +238,7 @@ public function getByType(string $type, bool $throw = true) return $this->getService($names[0]); } natsort($names); - throw new MissingServiceException("Multiple services of type $type found: " . implode(', ', $names) . '.'); + throw new MissingServiceException(sprintf("Multiple services of type $type found: %s.", implode(', ', $names))); } elseif ($throw) { if (!class_exists($type) && !interface_exists($type)) { @@ -239,10 +247,16 @@ public function getByType(string $type, bool $throw = true) foreach ($this->methods as $method => $foo) { $methodType = (new \ReflectionMethod(static::class, $method))->getReturnType()->getName(); if (is_a($methodType, $type, true)) { - throw new MissingServiceException("Service of type $type is not autowired or is missing in di › export › types."); + throw new MissingServiceException(sprintf( + 'Service of type %s is not autowired or is missing in di › export › types.', + $type + )); } } - throw new MissingServiceException("Service of type $type not found. Did you add it to configuration file?"); + throw new MissingServiceException(sprintf( + 'Service of type %s not found. Did you add it to configuration file?', + $type + )); } return null; } @@ -295,13 +309,13 @@ public function createInstance(string $class, array $args = []) { $rc = new \ReflectionClass($class); if (!$rc->isInstantiable()) { - throw new ServiceCreationException("Class $class is not instantiable."); + throw new ServiceCreationException(sprintf('Class %s is not instantiable.', $class)); } elseif ($constructor = $rc->getConstructor()) { return $rc->newInstanceArgs($this->autowireArguments($constructor, $args)); } elseif ($args) { - throw new ServiceCreationException("Unable to pass arguments, class $class has no constructor."); + throw new ServiceCreationException(sprintf('Unable to pass arguments, class %s has no constructor.', $class)); } return new $class; } diff --git a/src/DI/ContainerBuilder.php b/src/DI/ContainerBuilder.php index 84076605a..30933c7b1 100644 --- a/src/DI/ContainerBuilder.php +++ b/src/DI/ContainerBuilder.php @@ -74,12 +74,16 @@ public function addDefinition(?string $name, Definition $definition = null): Def } else { $name = $this->aliases[$name] ?? $name; if (isset($this->definitions[$name])) { - throw new Nette\InvalidStateException("Service '$name' has already been added."); + throw new Nette\InvalidStateException(sprintf("Service '%s' has already been added.", $name)); } $lname = strtolower($name); foreach ($this->definitions as $nm => $foo) { if ($lname === strtolower($nm)) { - throw new Nette\InvalidStateException("Service '$name' has the same name as '$nm' in a case-insensitive manner."); + throw new Nette\InvalidStateException(sprintf( + "Service '%s' has the same name as '%s' in a case-insensitive manner.", + $name, + $nm + )); } } } @@ -135,7 +139,7 @@ public function getDefinition(string $name): Definition { $service = $this->aliases[$name] ?? $name; if (!isset($this->definitions[$service])) { - throw new MissingServiceException("Service '$name' not found."); + throw new MissingServiceException(sprintf("Service '%s' not found.", $name)); } return $this->definitions[$service]; } @@ -170,10 +174,10 @@ public function addAlias(string $alias, string $service): void throw new Nette\InvalidArgumentException(sprintf('Service name must be a non-empty string, %s given.', gettype($service))); } elseif (isset($this->aliases[$alias])) { - throw new Nette\InvalidStateException("Alias '$alias' has already been added."); + throw new Nette\InvalidStateException(sprintf("Alias '%s' has already been added.", $alias)); } elseif (isset($this->definitions[$alias])) { - throw new Nette\InvalidStateException("Service '$alias' has already been added."); + throw new Nette\InvalidStateException(sprintf("Service '%s' has already been added.", $alias)); } $this->aliases[$alias] = $service; } diff --git a/src/DI/ContainerLoader.php b/src/DI/ContainerLoader.php index 255f04362..741da3dc4 100644 --- a/src/DI/ContainerLoader.php +++ b/src/DI/ContainerLoader.php @@ -67,9 +67,9 @@ private function loadFile(string $class, callable $generator): void $handle = @fopen("$file.lock", 'c+'); // @ is escalated to exception if (!$handle) { - throw new Nette\IOException("Unable to create file '$file.lock'. " . Nette\Utils\Helpers::getLastError()); + throw new Nette\IOException(sprintf("Unable to create file '%s.lock'. %s", $file, Nette\Utils\Helpers::getLastError())); } elseif (!@flock($handle, LOCK_EX)) { // @ is escalated to exception - throw new Nette\IOException("Unable to acquire exclusive lock on '$file.lock'. " . Nette\Utils\Helpers::getLastError()); + throw new Nette\IOException(sprintf("Unable to acquire exclusive lock on '%s.lock'. %s", $file, Nette\Utils\Helpers::getLastError())); } if (!is_file($file) || $this->isExpired($file, $updatedMeta)) { @@ -82,7 +82,7 @@ private function loadFile(string $class, callable $generator): void foreach ($toWrite as $name => $content) { if (file_put_contents("$name.tmp", $content) !== strlen($content) || !rename("$name.tmp", $name)) { @unlink("$name.tmp"); // @ - file may not exist - throw new Nette\IOException("Unable to create file '$name'."); + throw new Nette\IOException(sprintf("Unable to create file '%s'.", $name)); } elseif (function_exists('opcache_invalidate')) { @opcache_invalidate($name, true); // @ can be restricted } @@ -90,7 +90,7 @@ private function loadFile(string $class, callable $generator): void } if ((@include $file) === false) { // @ - error escalated to exception - throw new Nette\IOException("Unable to include '$file'."); + throw new Nette\IOException(sprintf("Unable to include '%s'.", $file)); } flock($handle, LOCK_UN); } diff --git a/src/DI/Definitions/AccessorDefinition.php b/src/DI/Definitions/AccessorDefinition.php index 0c9bc1b3d..342832b3e 100644 --- a/src/DI/Definitions/AccessorDefinition.php +++ b/src/DI/Definitions/AccessorDefinition.php @@ -29,7 +29,11 @@ final class AccessorDefinition extends Definition public function setImplement(string $type) { if (!interface_exists($type)) { - throw new Nette\InvalidArgumentException("Service '{$this->getName()}': Interface '$type' not found."); + throw new Nette\InvalidArgumentException(sprintf( + "Service '%s': Interface '%s' not found.", + $this->getName(), + $type + )); } $rc = new \ReflectionClass($type); @@ -40,9 +44,17 @@ public function setImplement(string $type) || $method->getName() !== self::METHOD_GET || count($rc->getMethods()) > 1 ) { - throw new Nette\InvalidArgumentException("Service '{$this->getName()}': Interface $type must have just one non-static method get()."); + throw new Nette\InvalidArgumentException(sprintf( + "Service '%s': Interface %s must have just one non-static method get().", + $this->getName(), + $type + )); } elseif ($method->getNumberOfParameters()) { - throw new Nette\InvalidArgumentException("Service '{$this->getName()}': Method $type::get() must have no parameters."); + throw new Nette\InvalidArgumentException(sprintf( + "Service '%s': Method %s::get() must have no parameters.", + $this->getName(), + $type + )); } return parent::setType($type); } diff --git a/src/DI/Definitions/Definition.php b/src/DI/Definitions/Definition.php index f863d3e20..fa88e0931 100644 --- a/src/DI/Definitions/Definition.php +++ b/src/DI/Definitions/Definition.php @@ -64,7 +64,11 @@ protected function setType(?string $type) if ($type === null) { $this->type = null; } elseif (!class_exists($type) && !interface_exists($type)) { - throw new Nette\InvalidArgumentException("Service '$this->name': Class or interface '$type' not found."); + throw new Nette\InvalidArgumentException(sprintf( + "Service '%s': Class or interface '%s' not found.", + $this->name, + $type + )); } else { $this->type = Nette\DI\Helpers::normalizeClass($type); } diff --git a/src/DI/Definitions/FactoryDefinition.php b/src/DI/Definitions/FactoryDefinition.php index 004f57b5a..766670a0f 100644 --- a/src/DI/Definitions/FactoryDefinition.php +++ b/src/DI/Definitions/FactoryDefinition.php @@ -38,12 +38,20 @@ public function __construct() public function setImplement(string $type) { if (!interface_exists($type)) { - throw new Nette\InvalidArgumentException("Service '{$this->getName()}': Interface '$type' not found."); + throw new Nette\InvalidArgumentException(sprintf( + "Service '%s': Interface '%s' not found.", + $this->getName(), + $type + )); } $rc = new \ReflectionClass($type); $method = $rc->getMethods()[0] ?? null; if (!$method || $method->isStatic() || $method->name !== self::METHOD_CREATE || count($rc->getMethods()) > 1) { - throw new Nette\InvalidArgumentException("Service '{$this->getName()}': Interface $type must have just one non-static method create()."); + throw new Nette\InvalidArgumentException(sprintf( + "Service '%s': Interface %s must have just one non-static method create().", + $this->getName(), + $type + )); } return parent::setType($type); } @@ -252,7 +260,11 @@ private function completeParameters(Nette\DI\Resolver $resolver): void } elseif (!$this->resultDefinition->getSetup()) { $hint = Nette\Utils\Helpers::getSuggestion(array_keys($ctorParams), $param->name); - throw new ServiceCreationException("Unused parameter \${$param->name} when implementing method $interface::create()" . ($hint ? ", did you mean \${$hint}?" : '.')); + throw new ServiceCreationException(sprintf( + 'Unused parameter $%s when implementing method %s::create()', + $param->name, + $interface + ) . ($hint ? ", did you mean \${$hint}?" : '.')); } $paramDef = PHP_VERSION_ID < 80000 diff --git a/src/DI/Definitions/LocatorDefinition.php b/src/DI/Definitions/LocatorDefinition.php index d8a1dcc63..7e63ae9ae 100644 --- a/src/DI/Definitions/LocatorDefinition.php +++ b/src/DI/Definitions/LocatorDefinition.php @@ -104,7 +104,12 @@ public function complete(Nette\DI\Resolver $resolver): void $this->references = []; foreach ($resolver->getContainerBuilder()->findByTag($this->tagged) as $name => $tag) { if (isset($this->references[$tag])) { - trigger_error("Service '{$this->getName()}': duplicated tag '$this->tagged' with value '$tag'.", E_USER_NOTICE); + trigger_error(sprintf( + "Service '%s': duplicated tag '%s' with value '%s'.", + $this->getName(), + $this->tagged, + $tag + ), E_USER_NOTICE); } $this->references[$tag] = new Reference($name); } diff --git a/src/DI/DependencyChecker.php b/src/DI/DependencyChecker.php index 60f075c57..0a713f35c 100644 --- a/src/DI/DependencyChecker.php +++ b/src/DI/DependencyChecker.php @@ -64,7 +64,7 @@ public function export(): array $functions[] = rtrim(Reflection::toString($dep), '()'); } else { - throw new Nette\InvalidStateException('Unexpected dependency ' . gettype($dep)); + throw new Nette\InvalidStateException(sprintf('Unexpected dependency %s', gettype($dep))); } } diff --git a/src/DI/Extensions/DecoratorExtension.php b/src/DI/Extensions/DecoratorExtension.php index 91efc27cb..02cfa2940 100644 --- a/src/DI/Extensions/DecoratorExtension.php +++ b/src/DI/Extensions/DecoratorExtension.php @@ -35,7 +35,7 @@ public function beforeCompile() $this->getContainerBuilder()->resolve(); foreach ($this->config as $type => $info) { if (!class_exists($type) && !interface_exists($type)) { - throw new Nette\DI\InvalidConfigurationException("Decorated class '$type' not found."); + throw new Nette\DI\InvalidConfigurationException(sprintf("Decorated class '%s' not found.", $type)); } if ($info->inject !== null) { $info->tags[InjectExtension::TAG_INJECT] = $info->inject; diff --git a/src/DI/Extensions/ExtensionsExtension.php b/src/DI/Extensions/ExtensionsExtension.php index 753125788..50b76258d 100644 --- a/src/DI/Extensions/ExtensionsExtension.php +++ b/src/DI/Extensions/ExtensionsExtension.php @@ -34,7 +34,10 @@ public function loadConfiguration() [$class, $args] = [$class->getEntity(), $class->arguments]; } if (!is_a($class, Nette\DI\CompilerExtension::class, true)) { - throw new Nette\DI\InvalidConfigurationException("Extension '$class' not found or is not Nette\\DI\\CompilerExtension descendant."); + throw new Nette\DI\InvalidConfigurationException(sprintf( + "Extension '%s' not found or is not Nette\\DI\\CompilerExtension descendant.", + $class + )); } $this->compiler->addExtension($name, (new \ReflectionClass($class))->newInstanceArgs($args)); } diff --git a/src/DI/Extensions/InjectExtension.php b/src/DI/Extensions/InjectExtension.php index 30bc1afc3..e6dae2cd9 100644 --- a/src/DI/Extensions/InjectExtension.php +++ b/src/DI/Extensions/InjectExtension.php @@ -117,7 +117,10 @@ public static function getInjectProperties(string $class): array if ($type = Reflection::getPropertyType($rp)) { } elseif (!$hasAttr && ($type = DI\Helpers::parseAnnotation($rp, 'var'))) { if (strpos($type, '|') !== false) { - throw new Nette\InvalidStateException('The ' . Reflection::toString($rp) . ' is not expected to have a union type.'); + throw new Nette\InvalidStateException(sprintf( + 'The %s is not expected to have a union type.', + Reflection::toString($rp) + )); } $type = Reflection::expandClassName($type, Reflection::getPropertyDeclaringClass($rp)); } diff --git a/src/DI/Extensions/SearchExtension.php b/src/DI/Extensions/SearchExtension.php index 5c1d0a41f..2eae2dc41 100644 --- a/src/DI/Extensions/SearchExtension.php +++ b/src/DI/Extensions/SearchExtension.php @@ -61,7 +61,12 @@ public function loadConfiguration() { foreach (array_filter($this->config) as $name => $batch) { if (!is_dir($batch->in)) { - throw new Nette\DI\InvalidConfigurationException("Option '{$this->name} › {$name} › in' must be valid directory name, '{$batch->in}' given."); + throw new Nette\DI\InvalidConfigurationException(sprintf( + "Option '%s › %s › in' must be valid directory name, '%s' given.", + $this->name, + $name, + $batch->in + )); } foreach ($this->findClasses($batch) as $class) { @@ -90,7 +95,10 @@ public function findClasses(\stdClass $config): array $found = []; foreach ($classes as $class) { if (!class_exists($class) && !interface_exists($class) && !trait_exists($class)) { - throw new Nette\InvalidStateException("Class $class was found, but it cannot be loaded by autoloading."); + throw new Nette\InvalidStateException(sprintf( + 'Class %s was found, but it cannot be loaded by autoloading.', + $class + )); } $rc = new \ReflectionClass($class); if ( diff --git a/src/DI/Helpers.php b/src/DI/Helpers.php index b6d11d45c..88bd69d9f 100644 --- a/src/DI/Helpers.php +++ b/src/DI/Helpers.php @@ -62,7 +62,10 @@ public static function expand($var, array $params, $recursive = false) $res[] = '%'; } elseif (isset($recursive[$part])) { - throw new Nette\InvalidArgumentException(sprintf('Circular reference detected for variables: %s.', implode(', ', array_keys($recursive)))); + throw new Nette\InvalidArgumentException(sprintf( + 'Circular reference detected for variables: %s.', + implode(', ', array_keys($recursive)) + )); } else { $val = $params; @@ -72,7 +75,7 @@ public static function expand($var, array $params, $recursive = false) } elseif ($val instanceof DynamicParameter) { $val = new DynamicParameter($val . '[' . var_export($key, true) . ']'); } else { - throw new Nette\InvalidArgumentException("Missing parameter '$part'."); + throw new Nette\InvalidArgumentException(sprintf("Missing parameter '%s'.", $part)); } } if ($recursive) { @@ -84,7 +87,7 @@ public static function expand($var, array $params, $recursive = false) if ($val instanceof DynamicParameter) { $php = true; } elseif (!is_scalar($val)) { - throw new Nette\InvalidArgumentException("Unable to concatenate non-scalar parameter '$part' into '$var'."); + throw new Nette\InvalidArgumentException(sprintf("Unable to concatenate non-scalar parameter '%s' into '%s'.", $part, $var)); } $res[] = $val; } @@ -245,7 +248,10 @@ public static function convertType($value, string $type) return $norm; } } - $value = is_scalar($value) ? "'$value'" : gettype($value); - throw new Nette\InvalidStateException("Cannot convert $value to $type."); + throw new Nette\InvalidStateException(sprintf( + 'Cannot convert %s to %s.', + is_scalar($value) ? "'$value'" : gettype($value), + $type + )); } } diff --git a/src/DI/Resolver.php b/src/DI/Resolver.php index e0acfdd67..1323e6c1c 100644 --- a/src/DI/Resolver.php +++ b/src/DI/Resolver.php @@ -188,7 +188,11 @@ public function completeStatement(Statement $statement, bool $currentServiceAllo case $entity === 'not': if (count($arguments) > 1) { - throw new ServiceCreationException("Function $entity() expects at most 1 parameter, " . count($arguments) . ' given.'); + throw new ServiceCreationException(sprintf( + 'Function %s() expects at most 1 parameter, %s given.', + $entity, + count($arguments) + )); } $entity = ['', '!']; break; @@ -198,7 +202,11 @@ public function completeStatement(Statement $statement, bool $currentServiceAllo case $entity === 'float': case $entity === 'string': if (count($arguments) > 1) { - throw new ServiceCreationException("Function $entity() expects at most 1 parameter, " . count($arguments) . ' given.'); + throw new ServiceCreationException(sprintf( + 'Function %s() expects at most 1 parameter, %s given.', + $entity, + count($arguments) + )); } $arguments = [$arguments[0], $entity]; $entity = [Helpers::class, 'convertType']; @@ -208,15 +216,17 @@ public function completeStatement(Statement $statement, bool $currentServiceAllo if (!class_exists($entity)) { throw new ServiceCreationException(sprintf("Class '%s' not found.", $entity)); } elseif ((new ReflectionClass($entity))->isAbstract()) { - throw new ServiceCreationException("Class $entity is abstract."); + throw new ServiceCreationException(sprintf('Class %s is abstract.', $entity)); } elseif (($rm = (new ReflectionClass($entity))->getConstructor()) !== null && !$rm->isPublic()) { - $visibility = $rm->isProtected() ? 'protected' : 'private'; - throw new ServiceCreationException("Class $entity has $visibility constructor."); + throw new ServiceCreationException(sprintf('Class %s has %s constructor.', $entity, $rm->isProtected() ? 'protected' : 'private')); } elseif ($constructor = (new ReflectionClass($entity))->getConstructor()) { $arguments = self::autowireArguments($constructor, $arguments, $getter); $this->addDependency($constructor); } elseif ($arguments) { - throw new ServiceCreationException("Unable to pass arguments, class $entity has no constructor."); + throw new ServiceCreationException(sprintf( + 'Unable to pass arguments, class %s has no constructor.', + $entity + )); } break; @@ -226,15 +236,21 @@ public function completeStatement(Statement $statement, bool $currentServiceAllo case is_array($entity): if (!preg_match('#^\$?(\\\\?' . PhpHelpers::PHP_IDENT . ')+(\[\])?$#D', $entity[1])) { - throw new ServiceCreationException("Expected function, method or property name, '$entity[1]' given."); + throw new ServiceCreationException(sprintf( + "Expected function, method or property name, '%s' given.", + $entity[1] + )); } switch (true) { case $entity[0] === '': // function call if (!Nette\Utils\Arrays::isList($arguments)) { - throw new ServiceCreationException("Unable to pass specified arguments to $entity[0]."); + throw new ServiceCreationException(sprintf( + 'Unable to pass specified arguments to %s.', + $entity[0] + )); } elseif (!function_exists($entity[1])) { - throw new ServiceCreationException("Function $entity[1] doesn't exist."); + throw new ServiceCreationException(sprintf("Function %s doesn't exist.", $entity[1])); } $rf = new \ReflectionFunction($entity[1]); $arguments = self::autowireArguments($rf, $arguments, $getter); @@ -250,7 +266,7 @@ public function completeStatement(Statement $statement, bool $currentServiceAllo if ($entity[1][0] === '$') { // property getter, setter or appender Validators::assert($arguments, 'list:0..1', "setup arguments for '" . Nette\Utils\Callback::toString($entity) . "'"); if (!$arguments && substr($entity[1], -2) === '[]') { - throw new ServiceCreationException("Missing argument for $entity[1]."); + throw new ServiceCreationException(sprintf('Missing argument for %s.', $entity[1])); } } elseif ( $type = $entity[0] instanceof Reference @@ -261,13 +277,13 @@ public function completeStatement(Statement $statement, bool $currentServiceAllo if ($rc->hasMethod($entity[1])) { $rm = $rc->getMethod($entity[1]); if (!$rm->isPublic()) { - throw new ServiceCreationException("$type::$entity[1]() is not callable."); + throw new ServiceCreationException(sprintf('%s::%s() is not callable.', $type, $entity[1])); } $arguments = self::autowireArguments($rm, $arguments, $getter); $this->addDependency($rm); } elseif (!Nette\Utils\Arrays::isList($arguments)) { - throw new ServiceCreationException("Unable to pass specified arguments to $type::$entity[1]()."); + throw new ServiceCreationException(sprintf('Unable to pass specified arguments to %s::%s().', $type, $entity[1])); } } } @@ -329,7 +345,7 @@ private function normalizeEntity(Statement $statement) if ($item instanceof Definition) { $name = current(array_keys($this->builder->getDefinitions(), $item, true)); if ($name === false) { - throw new ServiceCreationException("Service '{$item->getName()}' not found in definitions."); + throw new ServiceCreationException(sprintf("Service '%s' not found in definitions.", $item->getName())); } $item = new Reference($name); } @@ -351,7 +367,7 @@ public function normalizeReference(Reference $ref): Reference return $ref; } elseif ($ref->isName()) { if (!$this->builder->hasDefinition($service)) { - throw new ServiceCreationException("Reference to missing service '$service'."); + throw new ServiceCreationException(sprintf("Reference to missing service '%s'.", $service)); } return $this->currentService && $service === $this->currentService->getName() ? new Reference(Reference::SELF) @@ -525,7 +541,10 @@ public static function autowireArguments( $optCount = 0; } if ($arguments) { - throw new ServiceCreationException('Unable to pass specified arguments to ' . Reflection::toString($method) . '.'); + throw new ServiceCreationException(sprintf( + 'Unable to pass specified arguments to %s.', + Reflection::toString($method) + )); } elseif ($optCount) { $res = array_slice($res, 0, -$optCount); } @@ -544,7 +563,10 @@ private static function autowireArgument(\ReflectionParameter $parameter, callab { $desc = Reflection::toString($parameter); if ($parameter->getType() instanceof \ReflectionIntersectionType) { - throw new ServiceCreationException("Parameter $desc has intersection type, so its value must be specified."); + throw new ServiceCreationException(sprintf( + 'Parameter %s has intersection type, so its value must be specified.', + $desc + )); } $types = array_diff(Reflection::getParameterTypes($parameter), ['null']);