Skip to content

Commit

Permalink
Resolver: added support for named variadics [Closes #289]
Browse files Browse the repository at this point in the history
partially reverts 8e6357f
  • Loading branch information
dg committed Sep 21, 2023
1 parent e75e5ad commit dc0e9f7
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 5 deletions.
18 changes: 16 additions & 2 deletions src/DI/Resolver.php
Original file line number Diff line number Diff line change
Expand Up @@ -548,10 +548,24 @@ public static function autowireArguments(
'Cannot use positional argument after named or omitted argument in %s.',
Reflection::toString($param)
));

} elseif (array_key_exists($paramName, $arguments)) {
if (!is_array($arguments[$paramName])) {
throw new ServiceCreationException(sprintf(
'Parameter %s must be array, %s given.',
Reflection::toString($param),
gettype($arguments[$paramName])
));
}

$res = array_merge($res, $arguments[$paramName]);
unset($arguments[$paramName]);

} else {
$res = array_merge($res, $arguments);
$arguments = [];
}

$res = array_merge($res, $arguments);
$arguments = [];
$optCount = 0;
break;

Expand Down
19 changes: 19 additions & 0 deletions tests/DI/Resolver.autowireArguments.errors.phpt
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,25 @@ Assert::exception(function () {
);
}, Nette\DI\ServiceCreationException::class, 'Parameter $x in {closure}%a?% has no class type or default value, so its value must be specified.');

// non-array named variadics
Assert::exception(function () {
Resolver::autowireArguments(
new ReflectionFunction(function (...$args) {}),
['args' => 1],
function () {}
);
}, Nette\DI\ServiceCreationException::class, 'Parameter $args in {closure}() must be array, integer given.');


// bad variadics (this is actually what PHP allows)
Assert::exception(function () {
Resolver::autowireArguments(
new ReflectionFunction(function (...$args) {}),
[1, 'args' => []],
function () {}
);
}, Nette\DI\ServiceCreationException::class, 'Unable to pass specified arguments to {closure}%a?%.');


// bad variadics
if (PHP_VERSION_ID >= 80000) {
Expand Down
6 changes: 3 additions & 3 deletions tests/DI/Resolver.autowireArguments.phpt
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,7 @@ Assert::equal(
)
);

// variadics
// positional variadics
Assert::equal(
[1, 2, 3],
Resolver::autowireArguments(
Expand All @@ -118,9 +118,9 @@ Assert::equal(
)
);

// name of variadics is ignored
// named variadics
Assert::equal(
['args' => [1, 2, 3]],
[1, 2, 3],
Resolver::autowireArguments(
new ReflectionFunction(function (...$args) {}),
['args' => [1, 2, 3]],
Expand Down

0 comments on commit dc0e9f7

Please sign in to comment.