vendor/sulu/sulu/src/Sulu/Bundle/MediaBundle/FileInspector/UploadFileSubscriber.php line 50

Open in your IDE?
  1. <?php
  2. declare(strict_types=1);
  3. /*
  4. * This file is part of Sulu.
  5. *
  6. * (c) Sulu GmbH
  7. *
  8. * This source file is subject to the MIT license that is bundled
  9. * with this source code in the file LICENSE.
  10. */
  11. namespace Sulu\Bundle\MediaBundle\FileInspector;
  12. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  13. use Symfony\Component\HttpFoundation\File\UploadedFile;
  14. use Symfony\Component\HttpKernel\Event\RequestEvent;
  15. use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
  16. /**
  17. * @internal
  18. */
  19. final class UploadFileSubscriber implements EventSubscriberInterface
  20. {
  21. /**
  22. * @return array<string, string>
  23. */
  24. public static function getSubscribedEvents(): array
  25. {
  26. return [
  27. 'kernel.request' => 'onKernelRequest',
  28. ];
  29. }
  30. /**
  31. * @var FileInspectorInterface[]
  32. */
  33. private array $fileInspectors;
  34. /**
  35. * @param iterable<FileInspectorInterface> $fileInspectors
  36. */
  37. public function __construct(
  38. iterable $fileInspectors,
  39. ) {
  40. $this->fileInspectors = \iterator_to_array($fileInspectors);
  41. }
  42. public function onKernelRequest(RequestEvent $event): void
  43. {
  44. $request = $event->getRequest();
  45. $request->files->replace($this->inspectFiles($request->files->all()));
  46. }
  47. /**
  48. * @param array<string, mixed> $files
  49. *
  50. * @return array<string, mixed>
  51. */
  52. private function inspectFiles(array $files): array
  53. {
  54. /**
  55. * @var string $key
  56. * @var UploadedFile|array<string, mixed>|null $file
  57. */
  58. foreach ($files as $key => $file) {
  59. if (\is_array($file)) {
  60. $files[$key] = $this->inspectFiles($file);
  61. continue;
  62. }
  63. if (null === $file) {
  64. continue;
  65. }
  66. $mimeType = $file->getMimeType() ?: $file->getClientMimeType();
  67. foreach ($this->fileInspectors as $fileInspector) {
  68. if (null !== $mimeType && $fileInspector->supports($mimeType)) {
  69. try {
  70. $files[$key] = $fileInspector->inspect($file);
  71. } catch (UnsafeFileException $exception) {
  72. throw new BadRequestHttpException($exception->getMessage(), $exception);
  73. }
  74. }
  75. }
  76. }
  77. return $files;
  78. }
  79. }