Skip to content

Commit

Permalink
used sprintf() for error messages
Browse files Browse the repository at this point in the history
  • Loading branch information
dg committed Aug 29, 2021
1 parent 6c48ead commit 917b3c0
Show file tree
Hide file tree
Showing 17 changed files with 152 additions and 65 deletions.
12 changes: 10 additions & 2 deletions src/DI/Autowiring.php
Expand Up @@ -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
));
}
}

Expand Down Expand Up @@ -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
));
}
}
}
Expand Down
16 changes: 11 additions & 5 deletions src/DI/Compiler.php
Expand Up @@ -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);
Expand Down Expand Up @@ -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'?" : '.')
);
}
Expand Down
9 changes: 5 additions & 4 deletions src/DI/CompilerExtension.php
Expand Up @@ -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);
}
Expand Down
5 changes: 4 additions & 1 deletion src/DI/Config/Adapters/NeonAdapter.php
Expand Up @@ -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;
Expand Down
7 changes: 6 additions & 1 deletion src/DI/Config/DefinitionSchema.php
Expand Up @@ -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]);
Expand Down
8 changes: 4 additions & 4 deletions src/DI/Config/Loader.php
Expand Up @@ -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;

Expand Down Expand Up @@ -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));
}
}

Expand Down Expand Up @@ -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]
Expand Down
36 changes: 25 additions & 11 deletions src/DI/Container.php
Expand Up @@ -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)));
Expand All @@ -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) {
Expand Down Expand Up @@ -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));
}
}

Expand All @@ -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]);
Expand All @@ -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 {
Expand All @@ -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;
Expand All @@ -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)) {
Expand All @@ -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;
}
Expand Down Expand Up @@ -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;
}
Expand Down
14 changes: 9 additions & 5 deletions src/DI/ContainerBuilder.php
Expand Up @@ -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
));
}
}
}
Expand Down Expand Up @@ -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];
}
Expand Down Expand Up @@ -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;
}
Expand Down
8 changes: 4 additions & 4 deletions src/DI/ContainerLoader.php
Expand Up @@ -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)) {
Expand All @@ -82,15 +82,15 @@ 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
}
}
}

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);
}
Expand Down
6 changes: 5 additions & 1 deletion src/DI/Definitions/FactoryDefinition.php
Expand Up @@ -256,7 +256,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
Expand Down
2 changes: 1 addition & 1 deletion src/DI/DependencyChecker.php
Expand Up @@ -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)));
}
}

Expand Down
2 changes: 1 addition & 1 deletion src/DI/Extensions/DecoratorExtension.php
Expand Up @@ -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;
Expand Down
5 changes: 4 additions & 1 deletion src/DI/Extensions/ExtensionsExtension.php
Expand Up @@ -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));
}
Expand Down
5 changes: 4 additions & 1 deletion src/DI/Extensions/InjectExtension.php
Expand Up @@ -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));
}
Expand Down
12 changes: 10 additions & 2 deletions src/DI/Extensions/SearchExtension.php
Expand Up @@ -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) {
Expand Down Expand Up @@ -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 (
Expand Down

0 comments on commit 917b3c0

Please sign in to comment.