Skip to content

Commit 09dc302

Browse files
committed
[Validator] Use Mime component to determine mime type for file validator
1 parent 96d2d19 commit 09dc302

File tree

2 files changed

+12
-5
lines changed

2 files changed

+12
-5
lines changed

src/Symfony/Component/Validator/Constraints/FileValidator.php

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -13,8 +13,10 @@
1313

1414
use Symfony\Component\HttpFoundation\File\File as FileObject;
1515
use Symfony\Component\HttpFoundation\File\UploadedFile;
16+
use Symfony\Component\Mime\MimeTypes;
1617
use Symfony\Component\Validator\Constraint;
1718
use Symfony\Component\Validator\ConstraintValidator;
19+
use Symfony\Component\Validator\Exception\LogicException;
1820
use Symfony\Component\Validator\Exception\UnexpectedTypeException;
1921
use Symfony\Component\Validator\Exception\UnexpectedValueException;
2022

@@ -170,12 +172,17 @@ public function validate($value, Constraint $constraint)
170172
}
171173

172174
if ($constraint->mimeTypes) {
173-
if (!$value instanceof FileObject) {
174-
$value = new FileObject($value);
175+
if ($value instanceof FileObject) {
176+
$mime = $value->getMimeType();
177+
} elseif (class_exists(MimeTypes::class)) {
178+
$mime = MimeTypes::getDefault()->guessMimeType($path);
179+
} elseif (!class_exists(FileObject::class)) {
180+
throw new LogicException('You cannot validate the mime-type of files as the Mime component is not installed. Try running "composer require symfony/mime".');
181+
} else {
182+
$mime = (new FileObject($value))->getMimeType();
175183
}
176184

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

180187
foreach ($mimeTypes as $mimeType) {
181188
if ($mimeType === $mime) {

src/Symfony/Component/Validator/Tests/Constraints/FileValidatorTest.php

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -294,10 +294,10 @@ public function testValidMimeType()
294294
$file
295295
->expects($this->once())
296296
->method('getMimeType')
297-
->willReturn('image/jpg');
297+
->willReturn('image/jpeg');
298298

299299
$constraint = new File([
300-
'mimeTypes' => ['image/png', 'image/jpg'],
300+
'mimeTypes' => ['image/png', 'image/jpeg'],
301301
]);
302302

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

0 commit comments

Comments
 (0)