Skip to content

Commit ec017d5

Browse files
committed
[Validator] Use Mime component to determine mime type for file validator
1 parent 425e8b9 commit ec017d5

File tree

1 file changed

+10
-3
lines changed

1 file changed

+10
-3
lines changed

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) {

0 commit comments

Comments
 (0)