Skip to content

[HttpKernel] Add the UidValueResolver argument value resolver #44665

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Feb 24, 2022
Merged
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
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,7 @@
use Symfony\Component\HttpKernel\CacheClearer\CacheClearerInterface;
use Symfony\Component\HttpKernel\CacheWarmer\CacheWarmerInterface;
use Symfony\Component\HttpKernel\Controller\ArgumentResolver\BackedEnumValueResolver;
use Symfony\Component\HttpKernel\Controller\ArgumentResolver\UidValueResolver;
use Symfony\Component\HttpKernel\Controller\ArgumentValueResolverInterface;
use Symfony\Component\HttpKernel\DataCollector\DataCollectorInterface;
use Symfony\Component\HttpKernel\DependencyInjection\Extension;
Expand Down Expand Up @@ -416,6 +417,8 @@ public function load(array $configs, ContainerBuilder $container)
}

$this->registerUidConfiguration($config['uid'], $container, $loader);
} else {
$container->removeDefinition('argument_resolver.uid');
}

// register cache before session so both can share the connection services
Expand Down Expand Up @@ -2577,6 +2580,10 @@ private function registerUidConfiguration(array $config, ContainerBuilder $conta
$container->getDefinition('name_based_uuid.factory')
->setArguments([$config['name_based_uuid_namespace']]);
}

if (!class_exists(UidValueResolver::class)) {
$container->removeDefinition('argument_resolver.uid');
}
}

private function resolveTrustedHeaders(array $headers): int
Expand Down
6 changes: 6 additions & 0 deletions src/Symfony/Bundle/FrameworkBundle/Resources/config/web.php
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
use Symfony\Component\HttpKernel\Controller\ArgumentResolver\RequestValueResolver;
use Symfony\Component\HttpKernel\Controller\ArgumentResolver\ServiceValueResolver;
use Symfony\Component\HttpKernel\Controller\ArgumentResolver\SessionValueResolver;
use Symfony\Component\HttpKernel\Controller\ArgumentResolver\UidValueResolver;
use Symfony\Component\HttpKernel\Controller\ArgumentResolver\VariadicValueResolver;
use Symfony\Component\HttpKernel\Controller\ErrorController;
use Symfony\Component\HttpKernel\ControllerMetadata\ArgumentMetadataFactory;
Expand Down Expand Up @@ -50,6 +51,11 @@
'priority' => 105, // prior to the RequestAttributeValueResolver
])

->set('argument_resolver.uid', UidValueResolver::class)
->tag('controller.argument_value_resolver', [
'priority' => 100, // same priority than RequestAttributeValueResolver, but registered before
])

->set('argument_resolver.request_attribute', RequestAttributeValueResolver::class)
->tag('controller.argument_value_resolver', ['priority' => 100])

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Bundle\FrameworkBundle\Tests\Functional\Bundle\TestBundle\Controller;

use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Uid\Ulid;
use Symfony\Component\Uid\UuidV1;

class UidController
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Check this file for different use cases.

{
#[Route(path: '/1/uuid-v1/{userId}')]
public function anyFormat(UuidV1 $userId): Response
{
return new Response($userId);
}

#[Route(path: '/2/ulid/{id}', requirements: ['id' => '[123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz]{22}'])]
public function specificFormatInAttribute(Ulid $id): Response
{
return new Response($id);
}

#[Route(path: '/3/uuid-v1/{id<[0123456789ABCDEFGHJKMNPQRSTVWXYZabcdefghjkmnpqrstvwxyz]{26}>}')]
public function specificFormatInPath(UuidV1 $id): Response
{
return new Response($id);
}

#[Route(path: '/4/uuid-v1/{postId}/custom-uid/{commentId}')]
public function manyUids(UuidV1 $postId, TestCommentIdentifier $commentId): Response
{
return new Response($postId."\n".$commentId);
}
}

class TestCommentIdentifier extends Ulid
{
}
Original file line number Diff line number Diff line change
Expand Up @@ -60,3 +60,7 @@ array_controller:
send_email:
path: /send_email
defaults: { _controller: Symfony\Bundle\FrameworkBundle\Tests\Functional\Bundle\TestBundle\Controller\EmailController::indexAction }

uid:
resource: "../../Controller/UidController.php"
type: "annotation"
90 changes: 90 additions & 0 deletions src/Symfony/Bundle/FrameworkBundle/Tests/Functional/UidTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Bundle\FrameworkBundle\Tests\Functional;

use Symfony\Bundle\FrameworkBundle\Tests\Functional\Bundle\TestBundle\Controller\UidController;
use Symfony\Component\HttpKernel\Controller\ArgumentResolver\UidValueResolver;
use Symfony\Component\Uid\Ulid;
use Symfony\Component\Uid\UuidV1;
use Symfony\Component\Uid\UuidV4;
use Symfony\Component\Uid\UuidV6;

/**
* @see UidController
*/
class UidTest extends AbstractWebTestCase
{
protected function setUp(): void
{
parent::setUp();

self::deleteTmpDir();
}

public function testArgumentValueResolverDisabled()
{
$this->expectException(\TypeError::class);
$this->expectExceptionMessage('Symfony\Bundle\FrameworkBundle\Tests\Functional\Bundle\TestBundle\Controller\UidController::anyFormat(): Argument #1 ($userId) must be of type Symfony\Component\Uid\UuidV1, string given');

$client = $this->createClient(['test_case' => 'Uid', 'root_config' => 'config_disabled.yml']);

$client->request('GET', '/1/uuid-v1/'.new UuidV1());
}

public function testArgumentValueResolverEnabled()
{
if (!class_exists(UidValueResolver::class)) {
$this->markTestSkipped('Needs symfony/http-kernel >= 6.1');
}

$client = $this->createClient(['test_case' => 'Uid', 'root_config' => 'config_enabled.yml']);

// Any format
$client->request('GET', '/1/uuid-v1/'.$uuidV1 = new UuidV1());
$this->assertSame((string) $uuidV1, $client->getResponse()->getContent());
$client->request('GET', '/1/uuid-v1/'.$uuidV1->toBase58());
$this->assertSame((string) $uuidV1, $client->getResponse()->getContent());
$client->request('GET', '/1/uuid-v1/'.$uuidV1->toRfc4122());
$this->assertSame((string) $uuidV1, $client->getResponse()->getContent());
// Bad version
$client->request('GET', '/1/uuid-v1/'.$uuidV4 = new UuidV4());
$this->assertSame(404, $client->getResponse()->getStatusCode());

// Only base58 format
$client->request('GET', '/2/ulid/'.($ulid = new Ulid())->toBase58());
$this->assertSame((string) $ulid, $client->getResponse()->getContent());
$client->request('GET', '/2/ulid/'.$ulid);
$this->assertSame(404, $client->getResponse()->getStatusCode());
$client->request('GET', '/2/ulid/'.$ulid->toRfc4122());
$this->assertSame(404, $client->getResponse()->getStatusCode());

// Only base32 format
$client->request('GET', '/3/uuid-v1/'.$uuidV1->toBase32());
$this->assertSame((string) $uuidV1, $client->getResponse()->getContent());
$client->request('GET', '/3/uuid-v1/'.$uuidV1);
$this->assertSame(404, $client->getResponse()->getStatusCode());
$client->request('GET', '/3/uuid-v1/'.$uuidV1->toBase58());
$this->assertSame(404, $client->getResponse()->getStatusCode());
// Bad version
$client->request('GET', '/3/uuid-v1/'.(new UuidV6())->toBase32());
$this->assertSame(404, $client->getResponse()->getStatusCode());

// Any format for both
$client->request('GET', '/4/uuid-v1/'.$uuidV1.'/custom-uid/'.$ulid->toRfc4122());
$this->assertSame($uuidV1."\n".$ulid, $client->getResponse()->getContent());
$client->request('GET', '/4/uuid-v1/'.$uuidV1->toBase58().'/custom-uid/'.$ulid->toBase58());
$this->assertSame($uuidV1."\n".$ulid, $client->getResponse()->getContent());
// Bad version
$client->request('GET', '/4/uuid-v1/'.$uuidV4.'/custom-uid/'.$ulid);
$this->assertSame(404, $client->getResponse()->getStatusCode());
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

use Symfony\Bundle\FrameworkBundle\FrameworkBundle;
use Symfony\Bundle\FrameworkBundle\Tests\Functional\Bundle\TestBundle\TestBundle;

return [
new FrameworkBundle(),
new TestBundle(),
];
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
imports:
- { resource: "../config/default.yml" }
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
imports:
- { resource: "../config/default.yml" }

framework:
uid: ~
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
uid:
resource: "@TestBundle/Resources/config/routing.yml"
1 change: 1 addition & 0 deletions src/Symfony/Bundle/FrameworkBundle/composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,7 @@
"symfony/workflow": "^5.4|^6.0",
"symfony/yaml": "^5.4|^6.0",
"symfony/property-info": "^5.4|^6.0",
"symfony/uid": "^5.4|^6.0",
"symfony/web-link": "^5.4|^6.0",
"phpdocumentor/reflection-docblock": "^3.0|^4.0|^5.0",
"paragonie/sodium_compat": "^1.8",
Expand Down
1 change: 1 addition & 0 deletions src/Symfony/Component/HttpKernel/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ CHANGELOG
* Add `BackedEnumValueResolver` to resolve backed enum cases from request attributes in controller arguments
* Deprecate StreamedResponseListener, it's not needed anymore
* Add `Profiler::isEnabled()` so collaborating collector services may elect to omit themselves.
* Add the `UidValueResolver` argument value resolver

6.0
---
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Component\HttpKernel\Controller\ArgumentResolver;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Controller\ArgumentValueResolverInterface;
use Symfony\Component\HttpKernel\ControllerMetadata\ArgumentMetadata;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\Uid\AbstractUid;

final class UidValueResolver implements ArgumentValueResolverInterface
{
/**
* {@inheritdoc}
*/
public function supports(Request $request, ArgumentMetadata $argument): bool
{
return !$argument->isVariadic()
&& \is_string($request->attributes->get($argument->getName()))
&& null !== $argument->getType()
&& is_subclass_of($argument->getType(), AbstractUid::class, true);
}

/**
* {@inheritdoc}
*/
public function resolve(Request $request, ArgumentMetadata $argument): iterable
{
/** @var class-string<AbstractUid> $uidClass */
$uidClass = $argument->getType();

try {
return [$uidClass::fromString($request->attributes->get($argument->getName()))];
} catch (\InvalidArgumentException $e) {
throw new NotFoundHttpException(sprintf('The uid for the "%s" parameter is invalid.', $argument->getName()), $e);
}
}
}
Loading