Skip to content

Commit d9017b2

Browse files
committed
feat(testing): add named arguments support to MakeExtension
- Support both named and positional arguments for better clarity - Maintain backward compatibility with existing tests - Named arguments take priority over positional arguments - Refactor to use match expression for cleaner code - Remove inline comments as per project conventions
1 parent 41f88b4 commit d9017b2

1 file changed

Lines changed: 35 additions & 1 deletion

File tree

src/Testing/MakeExtension.php

Lines changed: 35 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,10 @@
44

55
namespace Constructo\Testing;
66

7+
use InvalidArgumentException;
78
use ReflectionClass;
89
use ReflectionException;
10+
use ReflectionParameter;
911

1012
/**
1113
* @phpstan-ignore trait.unused
@@ -22,6 +24,38 @@ trait MakeExtension
2224
*/
2325
protected function make(string $class, array $args = []): object
2426
{
25-
return (new ReflectionClass($class))->newInstanceArgs(array_values($args));
27+
$reflection = new ReflectionClass($class);
28+
$constructor = $reflection->getConstructor();
29+
30+
if ($constructor === null) {
31+
return $reflection->newInstance();
32+
}
33+
34+
$orderedArgs = [];
35+
$position = 0;
36+
foreach ($constructor->getParameters() as $param) {
37+
$orderedArgs[] = $this->resolveParameter($param, $args, $class, $position);
38+
$position++;
39+
}
40+
41+
return $reflection->newInstanceArgs($orderedArgs);
42+
}
43+
44+
/**
45+
* @throws ReflectionException
46+
*/
47+
private function resolveParameter(ReflectionParameter $param, array $args, string $class, int $position): mixed
48+
{
49+
$name = $param->getName();
50+
51+
return match (true) {
52+
array_key_exists($name, $args) => $args[$name],
53+
array_key_exists($position, $args) => $args[$position],
54+
$param->isDefaultValueAvailable() => $param->getDefaultValue(),
55+
$param->allowsNull() => null,
56+
default => throw new InvalidArgumentException(
57+
sprintf('Missing required parameter: $%s for class %s', $name, $class)
58+
),
59+
};
2660
}
2761
}

0 commit comments

Comments
 (0)