diff --git a/src/Symfony/Component/Mime/FileinfoMimeTypeGuesser.php b/src/Symfony/Component/Mime/FileinfoMimeTypeGuesser.php index d65239af25b0c..733023eb38766 100644 --- a/src/Symfony/Component/Mime/FileinfoMimeTypeGuesser.php +++ b/src/Symfony/Component/Mime/FileinfoMimeTypeGuesser.php @@ -13,6 +13,7 @@ use Symfony\Component\Mime\Exception\InvalidArgumentException; use Symfony\Component\Mime\Exception\LogicException; +use Symfony\Component\Mime\Exception\RuntimeException; /** * Guesses the MIME type using the PECL extension FileInfo. @@ -21,6 +22,11 @@ */ class FileinfoMimeTypeGuesser implements MimeTypeGuesserInterface { + /** + * @var array + */ + private static $finfoCache = []; + /** * @param string|null $magicFile A magic file to use with the finfo instance * @@ -46,10 +52,12 @@ public function guessMimeType(string $path): ?string throw new LogicException(\sprintf('The "%s" guesser is not supported.', __CLASS__)); } - if (false === $finfo = new \finfo(\FILEINFO_MIME_TYPE, $this->magicFile)) { - return null; + try { + $finfo = self::$finfoCache[$this->magicFile] ??= new \finfo(\FILEINFO_MIME_TYPE, $this->magicFile); + } catch (\Exception $e) { + throw new RuntimeException($e->getMessage()); } - $mimeType = $finfo->file($path); + $mimeType = $finfo->file($path) ?: null; if ($mimeType && 0 === (\strlen($mimeType) % 2)) { $mimeStart = substr($mimeType, 0, \strlen($mimeType) >> 1);