Skip to content
Merged

Dev #35

Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
70 changes: 64 additions & 6 deletions src/Compiler/ServiceInvocationGenerator.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,12 @@
namespace Maduser\Argon\Container\Compiler;

use Maduser\Argon\Container\ArgonContainer;
use Maduser\Argon\Container\ServiceDescriptor;
use Maduser\Argon\Container\Support\StringHelper;
use Nette\PhpGenerator\ClassType;
use ReflectionException;
use ReflectionMethod;
use ReflectionNamedType;

final class ServiceInvocationGenerator
{
Expand All @@ -33,12 +37,21 @@ public function generate(ClassType $class): void
}
}

$mergedArgsLine = 'array_merge([' . implode(", ", $compiledArgs) . '], $args)';
$body = <<<PHP
{$controllerFetch}
\$mergedArgs = {$mergedArgsLine};
return \$controller->{$method}(...\$mergedArgs);
PHP;
$casts = $this->buildPrimitiveCastLines($descriptor, $method);
$indent = str_repeat(' ', 20);

$lines = [
$indent . $controllerFetch,
$indent . '$mergedArgs = ' . 'array_merge([' . implode(", ", $compiledArgs) . '], $args);',
];

foreach ($casts as $castLine) {
$lines[] = $indent . $castLine;
}

$lines[] = $indent . "return \$controller->{$method}(...\$mergedArgs);";

$body = implode("\n", $lines);

$class->addMethod($compiledMethodName)
->setPublic()
Expand All @@ -56,4 +69,49 @@ private function buildMethodInvokerName(string $serviceId, string $method): stri

return 'invoke_' . $sanitizedService . '__' . $sanitizedMethod;
}

/**
* @return list<string>
*/
private function buildPrimitiveCastLines(ServiceDescriptor $descriptor, string $method): array
{
$concrete = $descriptor->getConcrete();

if (!is_string($concrete) || !class_exists($concrete)) {
return [];
}

try {
$reflection = new ReflectionMethod($concrete, $method);
} catch (ReflectionException) {
return [];
}

$casts = [];

foreach ($reflection->getParameters() as $parameter) {
$type = $parameter->getType();

if (!$type instanceof ReflectionNamedType || !$type->isBuiltin()) {
continue;
}

$name = $parameter->getName();
$condition = "array_key_exists('{$name}', \$mergedArgs) && \$mergedArgs['{$name}'] !== null";

switch ($type->getName()) {
case 'int':
$casts[] = "if ({$condition}) { \$mergedArgs['{$name}'] = (int) \$mergedArgs['{$name}']; }";
break;
case 'float':
case 'double':
$casts[] = "if ({$condition}) { \$mergedArgs['{$name}'] = (float) \$mergedArgs['{$name}']; }";
break;
default:
break;
}
}

return $casts;
}
}
92 changes: 92 additions & 0 deletions tests/unit/Container/Compiler/ServiceInvocationGeneratorTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
<?php

declare(strict_types=1);

namespace Tests\Unit\Container\Compiler;

use Maduser\Argon\Container\ArgonContainer;
use Maduser\Argon\Container\Compiler\ServiceInvocationGenerator;
use Maduser\Argon\Container\Support\StringHelper;
use Nette\PhpGenerator\ClassType;
use PHPUnit\Framework\TestCase;
use Tests\Unit\Container\Compiler\Stubs\ServiceDependency;
use Tests\Unit\Container\Compiler\Stubs\ServiceWithTypedMethods;

final class ServiceInvocationGeneratorTest extends TestCase
{
public function testGenerateCreatesInvokerWithCastsAndServiceReferences(): void
{
$container = new ArgonContainer();
$container->set(ServiceWithTypedMethods::class)
->defineInvocation('handle', [
'id' => '42',
'ratio' => '3.5',
'dependency' => '@dependency.service',
'note' => 'test',
]);
$container->set('dependency.service', static fn() => new ServiceDependency());

$generator = new ServiceInvocationGenerator($container);
$class = new ClassType('CompiledContainer');

$generator->generate($class);

$methodName = 'invoke_'
. StringHelper::sanitizeIdentifier(ServiceWithTypedMethods::class)
. '__handle';

self::assertTrue($class->hasMethod($methodName));
$method = $class->getMethod($methodName);
self::assertSame('mixed', $method->getReturnType());

$parameters = $method->getParameters();
self::assertArrayHasKey('args', $parameters);
$argsParameter = $parameters['args'];
self::assertSame('array', $argsParameter->getType());
self::assertTrue($argsParameter->hasDefaultValue());
self::assertSame([], $argsParameter->getDefaultValue());

$body = $method->getBody();
$escapedServiceClass = str_replace('\\', '\\\\', ServiceWithTypedMethods::class);
self::assertStringContainsString("\$controller = \$this->get('{$escapedServiceClass}');", $body);
self::assertStringContainsString("\$this->get('dependency.service')", $body);
self::assertStringContainsString("(int) \$mergedArgs['id']", $body);
self::assertStringContainsString("(float) \$mergedArgs['ratio']", $body);
}

public function testGenerateSkipsPrimitiveCastsForNonClassAndMissingMethod(): void
{
$container = new ArgonContainer();
$container->set('closure.service', static fn() => new ServiceWithTypedMethods())
->defineInvocation('handle', ['id' => 1]);
$container->set(ServiceWithTypedMethods::class)
->defineInvocation('undefinedMethod', []);

$generator = new ServiceInvocationGenerator($container);
$class = new ClassType('CompiledContainer');

$generator->generate($class);

$closureInvokerName = 'invoke_'
. StringHelper::sanitizeIdentifier('closure.service')
. '__handle';
$missingInvokerName = 'invoke_'
. StringHelper::sanitizeIdentifier(ServiceWithTypedMethods::class)
. '__undefinedMethod';

self::assertTrue($class->hasMethod($closureInvokerName));
self::assertTrue($class->hasMethod($missingInvokerName));
$closureMethod = $class->getMethod($closureInvokerName);
$missingMethod = $class->getMethod($missingInvokerName);

$escapedServiceClass = str_replace('\\', '\\\\', ServiceWithTypedMethods::class);

$closureBody = $closureMethod->getBody();
self::assertStringNotContainsString('(int)', $closureBody);
self::assertStringNotContainsString('(float)', $closureBody);

$missingBody = $missingMethod->getBody();
self::assertStringContainsString("\$controller = \$this->get('{$escapedServiceClass}');", $missingBody);
self::assertStringContainsString("\$controller->undefinedMethod(...\$mergedArgs);", $missingBody);
}
}
9 changes: 9 additions & 0 deletions tests/unit/Container/Compiler/Stubs/ServiceDependency.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
<?php

declare(strict_types=1);

namespace Tests\Unit\Container\Compiler\Stubs;

final class ServiceDependency
{
}
13 changes: 13 additions & 0 deletions tests/unit/Container/Compiler/Stubs/ServiceWithTypedMethods.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
<?php

declare(strict_types=1);

namespace Tests\Unit\Container\Compiler\Stubs;

final class ServiceWithTypedMethods
{
public function handle(int $id, float $ratio, ServiceDependency $dependency, ?string $note = null): array
{
return [$id, $ratio, $dependency, $note];
}
}