Skip to content

[Router] Validate Request in Router #48908

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
y4roc opened this issue Jan 7, 2023 · 5 comments
Closed

[Router] Validate Request in Router #48908

y4roc opened this issue Jan 7, 2023 · 5 comments

Comments

@y4roc
Copy link

y4roc commented Jan 7, 2023

In the controller I use an attribute to which I pass as parameter the class of the RequestClass. A subscriber then loads the post content and validates it using the RequestClass. Subsequently, an instance of the RequestClass, with the values of the request, is passed as an argument to the controller method.

If the validation fails, the call throws a bad request exception.

Example:

class IndexAction {
  #[RequestValidator(class: IndexRequest::class)]
  public function __invoke(IndexRequest $request) {
    ...
  }
}
class IndexRequest {
  #[Assert\NotNull]
  #[Assert\Type(type: 'string')]
  public $username

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

Originally posted by @y4roc in #46991 (comment)

@xabbuh
Copy link
Member

xabbuh commented Jan 10, 2023

How would a generic approach for this look like? Is there really much code that could be abstracted in a reusable way or doesn't this all come down in implementing a custom argument value resolver per use case?

@y4roc
Copy link
Author

y4roc commented Jan 14, 2023

I would create a subscriber in the framework bundle which listens for a request. In the event is the controller function which is called. Using the argument before this function, the data from the request is loaded into the specified class. Then the Symfony validator validates this class. If the validator fails, an HttpBadRequest exception would be thrown.

So the router is not the right place for this, but the framework bundle is in my opinion.

@xabbuh
Copy link
Member

xabbuh commented Jan 16, 2023

Something like #47425?

@y4roc
Copy link
Author

y4roc commented Jan 16, 2023

Yes, but will create an DTO-Klass for the request, and the listener will fill them and validate it.

@BASAKSemih
Copy link
Contributor

BASAKSemih commented Jun 22, 2023

I think we can close this issue through #49138

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging a pull request may close this issue.

5 participants