Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

[Validator] [WIP] Validate controller arguments using constraints #47425

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

Closed
wants to merge 13 commits into from
Closed
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 @@ -19,14 +19,16 @@
use Symfony\Component\Validator\Constraints\NotCompromisedPasswordValidator;
use Symfony\Component\Validator\Constraints\WhenValidator;
use Symfony\Component\Validator\ContainerConstraintValidatorFactory;
use Symfony\Component\Validator\EventListener\ControllerArgumentConstraintAttributeListener;
use Symfony\Component\Validator\Mapping\Loader\PropertyInfoLoader;
use Symfony\Component\Validator\Validation;
use Symfony\Component\Validator\Validator\ValidatorInterface;
use Symfony\Component\Validator\ValidatorBuilder;

return static function (ContainerConfigurator $container) {
$container->parameters()
->set('validator.mapping.cache.file', param('kernel.cache_dir').'/validation.php');
->set('validator.mapping.cache.file', param('kernel.cache_dir').'/validation.php')
;

$container->services()
->set('validator', ValidatorInterface::class)
Expand Down Expand Up @@ -109,5 +111,11 @@
service('property_info'),
])
->tag('validator.auto_mapper')

->set('controller.controller_argument_constraint_attribute_listener', ControllerArgumentConstraintAttributeListener::class)
->args([
service('validator'),
])
->tag('kernel.event_subscriber')
;
};
44 changes: 44 additions & 0 deletions 44 src/Symfony/Component/Validator/Constraints/ControllerArgument.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
<?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\Validator\Constraints;

/**
* @author Dynèsh Hassanaly <artyum@protonmail.com>
*/
#[\Attribute(\Attribute::TARGET_PARAMETER)]
class ControllerArgument extends Composite
{
public $constraints = [];

public function __construct(mixed $constraints = null, array $groups = null, mixed $payload = null)
{
parent::__construct($constraints ?? [], $groups, $payload);
}

public function getDefaultOption(): ?string
{
return 'constraints';
}

public function getRequiredOptions(): array
{
return ['constraints'];
}

/**
* @inheritDoc
*/
protected function getCompositeOption(): string
{
return 'constraints';
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
<?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\Validator\Constraints;

use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
use Symfony\Component\Validator\Exception\UnexpectedTypeException;
use Symfony\Component\Validator\Exception\UnexpectedValueException;

/**
* @author Dynèsh Hassanaly <artyum@protonmail.com>
*/
class ControllerArgumentValidator extends ConstraintValidator
{
/**
* @inheritDoc
*/
public function validate(mixed $value, Constraint $constraint)
{
if (!$constraint instanceof ControllerArgument) {
throw new UnexpectedTypeException($constraint, ControllerArgument::class);
}

if (null === $value) {
return;
}

$context = $this->context;
$validator = $context->getValidator()->inContext($context);

foreach ($constraint->constraints as $c) {
$validator->validate($value, $c);
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
<?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\Validator\EventListener;

use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\ControllerArgumentsEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\Constraints\ControllerArgument;
use Symfony\Component\Validator\Exception\ValidationFailedException;
use Symfony\Component\Validator\Validator\ValidatorInterface;

/**
* Handles the validator constraint attributes on controller's arguments.
*
* @author Dynèsh Hassanaly <artyum@protonmail.com>
*/
class ControllerArgumentConstraintAttributeListener implements EventSubscriberInterface
{
public function __construct(private readonly ValidatorInterface $validator) {}

public function onKernelControllerArguments(ControllerArgumentsEvent $event): void
{
$controller = $event->getController();
$arguments = $event->getArguments();
$reflectionMethod = $this->getReflectionMethod($controller);

foreach ($reflectionMethod->getParameters() as $index => $reflectionParameter) {
$reflectionAttributes = $reflectionParameter->getAttributes(ControllerArgument::class);

if (!$reflectionAttributes) {
continue;
}

// this attribute cannot be repeated, so we will always one item in this array
$reflectionAttribute = $reflectionAttributes[0];

/** @var Constraint $constraint */
$constraint = $reflectionAttribute->newInstance();
$value = $arguments[$index];
$violations = $this->validator->validate($value, $constraint);

if ($violations->count() > 0) {
throw new ValidationFailedException($value, $violations);
}
}
}

public static function getSubscribedEvents(): array
{
return [KernelEvents::CONTROLLER_ARGUMENTS => ['onKernelControllerArguments', 10]];
}

private function getReflectionMethod(callable $controller): \ReflectionMethod
Copy link
Contributor Author

Choose a reason for hiding this comment

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

That's how I'm extracting the controller class + method from the event.
If you have a better way I'll take it.

Copy link
Contributor

Choose a reason for hiding this comment

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

You can use the new ControllerEvent::getControllerReflector() method

Copy link
Contributor Author

Choose a reason for hiding this comment

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

This method seems to be available only in ControllerEvent and I'm listening on ControllerArgumentsEvent 😕

Copy link
Contributor

Choose a reason for hiding this comment

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

If it's worth it, it could be easy to expose:

class ControllerArgumentsEvent extends KernelEvent
{
    // ...
    public function getControllerReflector(): \ReflectionFunctionAbstract
    {
        return $this->controllerEvent->getControllerReflector();
    }
}

Copy link
Contributor Author

Choose a reason for hiding this comment

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

That would be useful, yes. Should I create another PR to make that change and merge it into the current PR or can I change that method scope in this PR?

Copy link
Contributor

Choose a reason for hiding this comment

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

{
if (is_array($controller)) {
$class = $controller[0];
$method = $controller[1];
} else {
/** @var object $controller */
$class = $controller;
$method = '__invoke';
}

return new \ReflectionMethod($class, $method);
}
}
Morty Proxy This is a proxified and sanitized view of the page, visit original site.