src/EventSubscriber/Api/UploadSubscriber.php line 47

Open in your IDE?
  1. <?php
  2. // api/src/EventSubscriber/BookMailSubscriber.php
  3. namespace App\EventSubscriber\Api;
  4. use ApiPlatform\Core\EventListener\EventPriorities;
  5. use App\Entity\Company;
  6. use App\Entity\User;
  7. use Symfony\Component\DependencyInjection\ContainerInterface;
  8. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  9. use Symfony\Component\HttpKernel\Event\ViewEvent;
  10. use Symfony\Component\HttpKernel\KernelEvents;
  11. use Symfony\Component\PropertyAccess\PropertyAccess;
  12. final class UploadSubscriber implements EventSubscriberInterface
  13. {
  14. /**
  15. * @var string
  16. */
  17. private $cacheDir;
  18. /**
  19. * @var ContainerInterface
  20. */
  21. private $container;
  22. /**
  23. * @var array
  24. */
  25. private $mappings;
  26. public function __construct(ContainerInterface $container, $cacheDir)
  27. {
  28. $this->cacheDir = $cacheDir;
  29. $this->container = $container;
  30. $this->mappings = $this->container->getParameter('vich_uploader.mappings');
  31. }
  32. public static function getSubscribedEvents()
  33. {
  34. return [
  35. KernelEvents::VIEW => ['PRE_WRITE', EventPriorities::PRE_WRITE],
  36. ];
  37. }
  38. public function PRE_WRITE(\Symfony\Component\HttpKernel\Event\ViewEvent $event)
  39. {
  40. $object = $event->getControllerResult();
  41. if ($object instanceof Company) {
  42. $this->handleUpload($object, 'logo', 'company_logo');
  43. }
  44. if ($object instanceof User && $object->getCompany() instanceof Company) {
  45. $this->handleUpload($object->getCompany(), 'logo', 'company_logo');
  46. }
  47. $event->setControllerResult($object);
  48. }
  49. public function handleUpload($object, $property, $mappingName)
  50. {
  51. $propertyAccessor = PropertyAccess::createPropertyAccessor();
  52. $file = $propertyAccessor->getValue($object, $property);
  53. $temporaryFilePath = $this->cacheDir . '/upload/company_logos/' . $file;
  54. // dump($file, $temporaryFilePath);
  55. // exit();
  56. if (file_exists($temporaryFilePath)) {
  57. $mapping = $this->mappings[$mappingName];
  58. $targetDirectory = $mapping['upload_destination'];
  59. $file = new \SplFileInfo($temporaryFilePath);
  60. $fileName = $file->getBasename('.' . $file->getExtension());
  61. $i = 1;
  62. while (file_exists($targetDirectory . '/' . $fileName . '.' . $file->getExtension())) {
  63. $fileName = $file->getBasename('.' . $file->getExtension()) . $i;
  64. ++$i;
  65. }
  66. $targetFilePath = $targetDirectory . '/' . $fileName . '.' . $file->getExtension();
  67. if (!is_dir($targetDirectory)) {
  68. mkdir($targetDirectory, 0777, true);
  69. }
  70. rename($temporaryFilePath, $targetFilePath);
  71. rmdir(dirname($temporaryFilePath));
  72. $propertyAccessor->setValue($object, $property, basename($targetFilePath));
  73. }
  74. }
  75. }