ArgumentMetadata example

class UserValueResolverTest extends TestCase
{
    /** * In Symfony 7, keep this test case but remove the call to supports(). * * @group legacy */
    public function testSupportsFailsWithNoType()
    {
        $tokenStorage = new TokenStorage();
        $resolver = new UserValueResolver($tokenStorage);
        $metadata = new ArgumentMetadata('foo', null, false, false, null);

        $this->assertSame([]$resolver->resolve(Request::create('/')$metadata));
        $this->assertFalse($resolver->supports(Request::create('/')$metadata));
    }

    /** * In Symfony 7, keep this test case but remove the call to supports(). * * @group legacy */
    public function testSupportsFailsWhenDefaultValAndNoUser()
    {
use Symfony\Component\Stopwatch\Stopwatch;

class TraceableValueResolverTest extends TestCase
{
    /** * @group legacy */
    public function testTimingsInSupports()
    {
        $stopwatch = new Stopwatch();
        $resolver = new TraceableValueResolver(new ResolverStub()$stopwatch);
        $argument = new ArgumentMetadata('dummy', 'string', false, false, null);
        $request = new Request();

        $this->assertTrue($resolver->supports($request$argument));

        $event = $stopwatch->getEvent(ResolverStub::class.'::supports');
        $this->assertCount(1, $event->getPeriods());
    }

    public function testTimingsInResolve()
    {
        $stopwatch = new Stopwatch();
        
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

class EntityValueResolverTest extends TestCase
{
    public function testResolveWithoutClass()
    {
        $manager = $this->getMockBuilder(ObjectManager::class)->getMock();
        $registry = $this->createRegistry($manager);
        $resolver = new EntityValueResolver($registry);

        $request = new Request();
        $argument = new ArgumentMetadata('arg', null, false, false, null);

        $this->assertSame([]$resolver->resolve($request$argument));
    }

    public function testResolveWithoutAttribute()
    {
        $manager = $this->getMockBuilder(ObjectManager::class)->getMock();
        $registry = $this->createRegistry($manager);
        $resolver = new EntityValueResolver($registry, null, new MapEntity(disabled: true));

        $request = new Request();
        

    public static function provideTestResolve(): iterable
    {
        yield 'parameter found and array' => [
            Request::create('/', 'GET', ['ids' => ['1', '2']]),
            new ArgumentMetadata('ids', 'array', false, false, false, attributes: [new MapQueryParameter()]),
            [['1', '2']],
            null,
        ];
        yield 'parameter found and array variadic' => [
            Request::create('/', 'GET', ['ids' => [['1', '2']['2']]]),
            new ArgumentMetadata('ids', 'array', true, false, false, attributes: [new MapQueryParameter()]),
            [['1', '2']['2']],
            null,
        ];
        yield 'parameter found and array variadic with parameter not array failure' => [
            Request::create('/', 'GET', ['ids' => [['1', '2'], 1]]),
            
use Symfony\Component\Validator\ValidatorBuilder;

class RequestPayloadValueResolverTest extends TestCase
{
    public function testNotTypedArgument()
    {
        $resolver = new RequestPayloadValueResolver(
            new Serializer(),
            $this->createMock(ValidatorInterface::class),
        );

        $argument = new ArgumentMetadata('notTyped', null, false, false, null, false, [
            MapRequestPayload::class => new MapRequestPayload(),
        ]);
        $request = Request::create('/', 'POST', server: ['HTTP_CONTENT_TYPE' => 'application/json']);

        $kernel = $this->createMock(HttpKernelInterface::class);
        $arguments = $resolver->resolve($request$argument);
        $event = new ControllerArgumentsEvent($kernelfunction D) {}$arguments$request, HttpKernelInterface::MAIN_REQUEST);

        $this->expectException(\LogicException::class);
        $this->expectExceptionMessage('Could not resolve the "$notTyped" controller argument: argument should be typed.');

        
class ServiceValueResolverTest extends TestCase
{
    /** * In Symfony 7, keep this test case but remove the call to supports(). * * @group legacy */
    public function testDoNotSupportWhenControllerDoNotExists()
    {
        $resolver = new ServiceValueResolver(new ServiceLocator([]));
        $argument = new ArgumentMetadata('dummy', DummyService::class, false, false, null);
        $request = $this->requestWithAttributes(['_controller' => 'my_controller']);

        $this->assertSame([]$resolver->resolve($request$argument));
        $this->assertFalse($resolver->supports($request$argument));
    }

    public function testExistingController()
    {
        $resolver = new ServiceValueResolver(new ServiceLocator([
            'App\\Controller\\Mine::method' => fn () => new ServiceLocator([
                'dummy' => fn () => new DummyService(),
            ]),
class SecurityTokenValueResolverTest extends TestCase
{
    public function testResolveSucceedsWithTokenInterface()
    {
        $user = new InMemoryUser('username', 'password');
        $token = new UsernamePasswordToken($user, 'provider');
        $tokenStorage = new TokenStorage();
        $tokenStorage->setToken($token);

        $resolver = new SecurityTokenValueResolver($tokenStorage);
        $metadata = new ArgumentMetadata('foo', TokenInterface::class, false, false, null);

        $this->assertSame([$token]$resolver->resolve(Request::create('/')$metadata));
    }

    public function testResolveSucceedsWithSubclassType()
    {
        $user = new InMemoryUser('username', 'password');
        $token = new UsernamePasswordToken($user, 'provider');
        $tokenStorage = new TokenStorage();
        $tokenStorage->setToken($token);

        
namespace Symfony\Component\HttpKernel\Tests\ControllerMetadata;

use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpKernel\ControllerMetadata\ArgumentMetadata;
use Symfony\Component\HttpKernel\Tests\Fixtures\Attribute\Foo;

class ArgumentMetadataTest extends TestCase
{
    public function testWithBcLayerWithDefault()
    {
        $argument = new ArgumentMetadata('foo', 'string', false, true, 'default value');

        $this->assertFalse($argument->isNullable());
    }

    public function testDefaultValueAvailable()
    {
        $argument = new ArgumentMetadata('foo', 'string', false, true, 'default value', true);

        $this->assertTrue($argument->isNullable());
        $this->assertTrue($argument->hasDefaultValue());
        $this->assertSame('default value', $argument->getDefaultValue());
    }
$arguments = [];
        $reflector ??= new \ReflectionFunction($controller(...));

        foreach ($reflector->getParameters() as $param) {
            $attributes = [];
            foreach ($param->getAttributes() as $reflectionAttribute) {
                if (class_exists($reflectionAttribute->getName())) {
                    $attributes[] = $reflectionAttribute->newInstance();
                }
            }

            $arguments[] = new ArgumentMetadata($param->getName()$this->getType($param)$param->isVariadic()$param->isDefaultValueAvailable()$param->isDefaultValueAvailable() ? $param->getDefaultValue() : null, $param->allowsNull()$attributes);
        }

        return $arguments;
    }

    /** * Returns an associated type to the given parameter if available. */
    private function getType(\ReflectionParameter $parameter): ?string
    {
        if (!$type = $parameter->getType()) {
            
$resolver->resolve($request$metadata);
    }

    private static function createRequest(array $attributes = []): Request
    {
        return new Request([][]$attributes);
    }

    private static function createArgumentMetadata(string $name, string $type, bool $variadic = false): ArgumentMetadata
    {
        return new ArgumentMetadata($name$type$variadic, false, null);
    }
}
yield [\DateTime::class];
        yield [FooDateTime::class];
    }

    /** * @group legacy */
    public function testSupports()
    {
        $resolver = new DateTimeValueResolver();

        $argument = new ArgumentMetadata('dummy', \DateTime::class, false, false, null);
        $request = self::requestWithAttributes(['dummy' => 'now']);
        $this->assertTrue($resolver->supports($request$argument));

        $argument = new ArgumentMetadata('dummy', FooDateTime::class, false, false, null);
        $request = self::requestWithAttributes(['dummy' => 'now']);
        $this->assertTrue($resolver->supports($request$argument));

        $argument = new ArgumentMetadata('dummy', \stdClass::class, false, false, null);
        $request = self::requestWithAttributes(['dummy' => 'now']);
        $this->assertFalse($resolver->supports($request$argument));
    }

    
protected function setUp(): void
    {
        $this->factory = new ArgumentMetadataFactory();
    }

    public function testSignature1()
    {
        $arguments = $this->factory->createArgumentMetadata($this->signature1(...));

        $this->assertEquals([
            new ArgumentMetadata('foo', self::class, false, false, null),
            new ArgumentMetadata('bar', 'array', false, false, null),
            new ArgumentMetadata('baz', 'callable', false, false, null),
        ]$arguments);
    }

    public function testSignature2()
    {
        $arguments = $this->factory->createArgumentMetadata($this->signature2(...));

        $this->assertEquals([
            new ArgumentMetadata('foo', self::class, false, true, null, true),
            
use Symfony\Component\HttpKernel\Controller\ArgumentResolver\NotTaggedControllerValueResolver;
use Symfony\Component\HttpKernel\ControllerMetadata\ArgumentMetadata;

class NotTaggedControllerValueResolverTest extends TestCase
{
    /** * @group legacy */
    public function testDoSupportWhenControllerDoNotExists()
    {
        $resolver = new NotTaggedControllerValueResolver(new ServiceLocator([]));
        $argument = new ArgumentMetadata('dummy', \stdClass::class, false, false, null);
        $request = $this->requestWithAttributes(['_controller' => 'my_controller']);

        $this->assertTrue($resolver->supports($request$argument));
    }

    /** * In Symfony 7, keep this test case but remove the call to supports(). * * @group legacy */
    public function testDoNotSupportWhenControllerExists()
    {
$arguments = [];
        $reflector ??= new \ReflectionFunction($controller(...));

        foreach ($reflector->getParameters() as $param) {
            $attributes = [];
            foreach ($param->getAttributes() as $reflectionAttribute) {
                if (class_exists($reflectionAttribute->getName())) {
                    $attributes[] = $reflectionAttribute->newInstance();
                }
            }

            $arguments[] = new ArgumentMetadata($param->getName()$this->getType($param)$param->isVariadic()$param->isDefaultValueAvailable()$param->isDefaultValueAvailable() ? $param->getDefaultValue() : null, $param->allowsNull()$attributes);
        }

        return $arguments;
    }

    /** * Returns an associated type to the given parameter if available. */
    private function getType(\ReflectionParameter $parameter): ?string
    {
        if (!$type = $parameter->getType()) {
            

        if (!$expected) {
            $this->assertSame([](new UidValueResolver())->resolve($request$argument));
        }

        $this->assertSame($expected(new UidValueResolver())->supports($request$argument));
    }

    public static function provideSupports()
    {
        return [
            'Variadic argument' => [false, new Request([][]['foo' => (string) $uuidV4 = new UuidV4()])new ArgumentMetadata('foo', UuidV4::class, true, false, null)],
            'No attribute for argument' => [false, new Request([][][])new ArgumentMetadata('foo', UuidV4::class, false, false, null)],
            'Attribute is not a string' => [false, new Request([][]['foo' => ['bar']])new ArgumentMetadata('foo', UuidV4::class, false, false, null)],
            'Argument has no type' => [false, new Request([][]['foo' => (string) $uuidV4])new ArgumentMetadata('foo', null, false, false, null)],
            'Argument type is not a class' => [false, new Request([][]['foo' => (string) $uuidV4])new ArgumentMetadata('foo', 'string', false, false, null)],
            'Argument type is not a subclass of AbstractUid' => [false, new Request([][]['foo' => (string) $uuidV4])new ArgumentMetadata('foo', UlidFactory::class, false, false, null)],
            'AbstractUid is not supported' => [false, new Request([][]['foo' => (string) $uuidV4])new ArgumentMetadata('foo', AbstractUid::class, false, false, null)],
            'Custom abstract subclass is supported but will fail in resolve' => [true, new Request([][]['foo' => (string) $uuidV4])new ArgumentMetadata('foo', TestAbstractCustomUid::class, false, false, null)],
            'Known subclass' => [true, new Request([][]['foo' => (string) $uuidV4])new ArgumentMetadata('foo', UuidV4::class, false, false, null)],
            'Format does not matter' => [true, new Request([][]['foo' => (string) $uuidV4])new ArgumentMetadata('foo', Ulid::class, false, false, null)],
            'Custom subclass' => [true, new Request([][]['foo' => '01FPND7BD15ZV07X5VGDXAJ8VD'])new ArgumentMetadata('foo', TestCustomUid::class, false, false, null)],
        ];
    }
Home | Imprint | This part of the site doesn't use cookies.