Skip to content
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

[Validator] Use Mime component to determine mime type for file validator #36868

Merged
merged 1 commit into from May 30, 2020
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
13 changes: 10 additions & 3 deletions src/Symfony/Component/Validator/Constraints/FileValidator.php
Expand Up @@ -13,8 +13,10 @@

use Symfony\Component\HttpFoundation\File\File as FileObject;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Symfony\Component\Mime\MimeTypes;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
use Symfony\Component\Validator\Exception\LogicException;
use Symfony\Component\Validator\Exception\UnexpectedTypeException;
use Symfony\Component\Validator\Exception\UnexpectedValueException;

Expand Down Expand Up @@ -170,12 +172,17 @@ public function validate($value, Constraint $constraint)
}

if ($constraint->mimeTypes) {
if (!$value instanceof FileObject) {
$value = new FileObject($value);
if ($value instanceof FileObject) {
$mime = $value->getMimeType();
} elseif (class_exists(MimeTypes::class)) {
$mime = MimeTypes::getDefault()->guessMimeType($path);
} elseif (!class_exists(FileObject::class)) {
throw new LogicException('You cannot validate the mime-type of files as the Mime component is not installed. Try running "composer require symfony/mime".');
fabpot marked this conversation as resolved.
Show resolved Hide resolved
} else {
$mime = (new FileObject($value))->getMimeType();
}

$mimeTypes = (array) $constraint->mimeTypes;
$mime = $value->getMimeType();

foreach ($mimeTypes as $mimeType) {
if ($mimeType === $mime) {
Expand Down