Skip to content

Commit

Permalink
[Validator] Use Mime component to determine mime type for file validator
Browse files Browse the repository at this point in the history
  • Loading branch information
pierredup committed May 29, 2020
1 parent 96d2d19 commit 09dc302
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 5 deletions.
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".');
} else {
$mime = (new FileObject($value))->getMimeType();
}

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

foreach ($mimeTypes as $mimeType) {
if ($mimeType === $mime) {
Expand Down
Expand Up @@ -294,10 +294,10 @@ public function testValidMimeType()
$file
->expects($this->once())
->method('getMimeType')
->willReturn('image/jpg');
->willReturn('image/jpeg');

$constraint = new File([
'mimeTypes' => ['image/png', 'image/jpg'],
'mimeTypes' => ['image/png', 'image/jpeg'],
]);

$this->validator->validate($file, $constraint);
Expand Down

0 comments on commit 09dc302

Please sign in to comment.