Skip to content

[HttpKernel] #[MapUploadedFile] validation errors for files have empty propertyPath #61370

@Myks92

Description

@Myks92

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

  1. 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 {
    // ...
}
  1. Upload a file that's too large
  2. The validation error (ConstraintViolation) will have an empty propertyPath
    a

Possible Solution

Here are two potential solutions to address the issue:

  1. 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.

  2. 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.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions