-
-
Notifications
You must be signed in to change notification settings - Fork 9.7k
Description
Symfony version(s) affected
7.3
Description
When using MapUploadedFile
attribute with validation, the generated ConstraintViolation
files have an empty propertyPath
, which makes it difficult to map validation errors to the correct form fields.
Expected behavior
The propertyPath
of the ConstraintViolation
should be set to the name of the file field (or attribute) (e.g., "file").
Actual behavior
The propertyPath
is an empty string.
How to reproduce
- Create a controller with a file upload:
use Symfony\Component\Validator\Constraints as Assert;
// ...
#[Route('/file', methods: ['PUT'])]
public function upload(
#[MapUploadedFile([
new Assert\File(mimeTypes: ['image/png', 'image/jpeg']),
])]
UploadedFile $file
): Response {
// ...
}
- Upload a file that's too large
- The validation error (
ConstraintViolation
) will have an empty propertyPath
a
Possible Solution
Here are two potential solutions to address the issue:
-
Automatic Property Path Resolution:
Update RequestPayloadValueResolver to automatically set the propertyPath to the parameter name when handling MapUploadedFile attributes.
This would be the most developer-friendly approach as it requires no additional configuration. -
Explicit Property Path Option:
Add a propertyPath option to the MapUploadedFile attribute, allowing developers to specify a custom path:
Additional Context
This issue is particularly problematic in API contexts where clients expect consistent error structures. The current workaround requires using reflection to fix the property paths after validation, which is not ideal.
The fix would be backward-compatible since it only adds the missing property path information without changing the validation logic.
Related Components
Symfony\Component\HttpKernel\Controller\ArgumentResolver\RequestPayloadValueResolver
Symfony\Component\HttpKernel\Attribute\MapUploadedFile
Symfony\Component\Validator\ConstraintViolation
Example of Expected Behavior
After the fix, a validation error for a file upload should look like:
{
"code": 422,
"message": "Validation Failed",
"errors": {
"file": "The file is too large. Allowed maximum size is 1M."
}
}
Instead of the current behavior where the error might be at the root level due to the empty property path.