8000 [WIP] Request validator by y4roc · Pull Request #49002 · symfony/symfony · GitHub
[go: up one dir, main page]

Skip to content

[WIP] Request validator #49002

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 4 commits into from
Closed
Show file tree
Hide file tree
Changes from 1 commit
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
Next Next commit
add RequestValidator
  • Loading branch information
Thomas Hanke committed Jan 20, 2023
commit ce650a9a38df56b8914779022f001671246e2a35
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
use Symfony\Component\Validator\Constraints\NotCompromisedPasswordValidator;
use Symfony\Component\Validator\Constraints\WhenValidator;
use Symfony\Component\Validator\ContainerConstraintValidatorFactory;
use Symfony\Component\Validator\EventListener\RequestValidationSubscriber;
use Symfony\Component\Validator\Mapping\Loader\PropertyInfoLoader;
use Symfony\Component\Validator\Validation;
use Symfony\Component\Validator\Validator\ValidatorInterface;
Expand Down Expand Up @@ -109,5 +110,12 @@
service('property_info'),
])
->tag('validator.auto_mapper')

->set('validator.request_validator', RequestValidationSubscriber::class)
->args([
service('serializer')->nullOnInvalid(),
service('validator')
])
->tag('kernel.event_subscriber')
;
};
29 changes: 29 additions & 0 deletions src/Symfony/Component/Validator/Attribute/RequestValidator.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
<?php

namespace Symfony\Component\Validator\Attribute;

#[\Attribute(\Attribute::TARGET_FUNCTION)]
final class RequestValidator
{
private string $class;
private ?string $finalize;

public function __construct(
string $class,
?string $finalize = null
)
{
$this->class = $class;
$this->finalize = $finalize;
}

public function getClass(): string
{
return $this->class;
}

public function getFinalize(): ?string
{
return $this->finalize;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
<?php

namespace Symfony\Component\Validator\EventListener;

use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\ControllerArgumentsEvent;
use Symfony\Component\Serializer\SerializerInterface;
use Symfony\Component\Validator\Attribute\RequestValidator;
use Symfony\Component\Validator\Exception\ValidationFailedException;
use Symfony\Component\Validator\Validator\ValidatorInterface;

class RequestValidationSubscriber implements EventSubscriberInterface
{
public function __construct(readonly ?SerializerInterface $serializer = null, readonly ValidatorInterface $validator)
{
}

public static function getSubscribedEvents()
{
return [
ControllerArgumentsEvent::class => 'validateRequest'
];
}

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

$attributes = $reflectionMethod->getAttributes(RequestValidator::class, \ReflectionAttribute::IS_INSTANCEOF);

if(count($attributes) === 0) {
return;
}

// only first attribute can validate
$attribute = $attributes[0];

$class = $attribute->getArguments()['class'];

$object = new $class();

// if serializer is installed serialize input body
if(null !== $this->serializer) {
$object = $this->serializer->deserialize($request->getContent(), $class, 'json');
}

// set input variables in object
foreach ($request->request as $key => $input) {
$object->{$key} = $input;
}

// set parameter variables in object
foreach ($request->attributes as $key => $parameter) {
$object->{$key} = $parameter;
}

$violations = $this->validator->validate($object);

if(count($violations) > 0) {
throw new ValidationFailedException(sprintf("Validation of %s failed!", $class), $violations);
}

foreach ($arguments as $index => $argument) {
if(!$argument instanceof $class) {
continue;
}
$arguments[$index] = $object;
}

$event->setArguments($arguments);
}

private function getReflectionMethod(callable $controller): \ReflectionMethod
{
if (is_array($controller)) {
$class = $controller[0];
$method = $controller[1];
} else {
/** @var object $controller */
$class = $controller;
$method = '__invoke';
}

return new \ReflectionMethod($class, $method);
}
}
0