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 31, 2021
1 parent e14684d commit 3109450
Show file tree
Hide file tree
Showing 20 changed files with 189 additions and 73 deletions.
12 changes: 10 additions & 2 deletions src/DI/Autowiring.php
Original file line number Diff line number Diff line change
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
Original file line number Diff line number Diff line change
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
Original file line number Diff line number Diff line change
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
Original file line number Diff line number Diff line change
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
9 changes: 7 additions & 2 deletions src/DI/Config/DefinitionSchema.php
Original file line number Diff line number Diff line change
Expand Up @@ -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'])) {
Expand All @@ -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
Original file line number Diff line number Diff line change
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
Original file line number Diff line number Diff line change
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
Original file line number Diff line number Diff line change
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
Original file line number Diff line number Diff line change
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
18 changes: 15 additions & 3 deletions src/DI/Definitions/AccessorDefinition.php
Original file line number Diff line number Diff line change
Expand Up @@ -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);

Expand All @@ -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);
}
Expand Down
6 changes: 5 additions & 1 deletion src/DI/Definitions/Definition.php
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
Expand Down
Loading

0 comments on commit 3109450

Please sign in to comment.