Skip to content

Commit

Permalink
bug #36868 [Validator] Use Mime component to determine mime type for …
Browse files Browse the repository at this point in the history
…file validator (pierredup)

This PR was merged into the 4.4 branch.

Discussion
----------

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

| Q             | A
| ------------- | ---
| Branch?       | 4.4
| Bug fix?      | yes
| New feature?  | no
| Deprecations? | no
| Tickets       | N/A
| License       | MIT
| Doc PR        | N/A

When validating the mime type for a file, the Validator component relies on the `Symfony\Component\HttpFoundation\File\File` class, but if the HttpFoundation component is not installed, then you just get the error

```
PHP Fatal error:  Uncaught Error: Class 'Symfony\Component\HttpFoundation\File\File' not found
```

This PR uses the Mime component to get the mime type for a file and throws an exception if the Mime component is not installed.

Commits
-------

4728833 [Validator] Use Mime component to determine mime type for file validator
  • Loading branch information
fabpot committed May 30, 2020
2 parents 96d2d19 + 4728833 commit 5e0e9a8
Showing 1 changed file with 10 additions and 3 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

0 comments on commit 5e0e9a8

Please sign in to comment.