<?php
// api/src/EventSubscriber/BookMailSubscriber.php
namespace App\EventSubscriber\Api;
use ApiPlatform\Core\EventListener\EventPriorities;
use App\Entity\Company;
use App\Entity\User;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\ViewEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\PropertyAccess\PropertyAccess;
final class UploadSubscriber implements EventSubscriberInterface
{
/**
* @var string
*/
private $cacheDir;
/**
* @var ContainerInterface
*/
private $container;
/**
* @var array
*/
private $mappings;
public function __construct(ContainerInterface $container, $cacheDir)
{
$this->cacheDir = $cacheDir;
$this->container = $container;
$this->mappings = $this->container->getParameter('vich_uploader.mappings');
}
public static function getSubscribedEvents()
{
return [
KernelEvents::VIEW => ['PRE_WRITE', EventPriorities::PRE_WRITE],
];
}
public function PRE_WRITE(\Symfony\Component\HttpKernel\Event\ViewEvent $event)
{
$object = $event->getControllerResult();
if ($object instanceof Company) {
$this->handleUpload($object, 'logo', 'company_logo');
}
if ($object instanceof User && $object->getCompany() instanceof Company) {
$this->handleUpload($object->getCompany(), 'logo', 'company_logo');
}
$event->setControllerResult($object);
}
public function handleUpload($object, $property, $mappingName)
{
$propertyAccessor = PropertyAccess::createPropertyAccessor();
$file = $propertyAccessor->getValue($object, $property);
$temporaryFilePath = $this->cacheDir . '/upload/company_logos/' . $file;
// dump($file, $temporaryFilePath);
// exit();
if (file_exists($temporaryFilePath)) {
$mapping = $this->mappings[$mappingName];
$targetDirectory = $mapping['upload_destination'];
$file = new \SplFileInfo($temporaryFilePath);
$fileName = $file->getBasename('.' . $file->getExtension());
$i = 1;
while (file_exists($targetDirectory . '/' . $fileName . '.' . $file->getExtension())) {
$fileName = $file->getBasename('.' . $file->getExtension()) . $i;
++$i;
}
$targetFilePath = $targetDirectory . '/' . $fileName . '.' . $file->getExtension();
if (!is_dir($targetDirectory)) {
mkdir($targetDirectory, 0777, true);
}
rename($temporaryFilePath, $targetFilePath);
rmdir(dirname($temporaryFilePath));
$propertyAccessor->setValue($object, $property, basename($targetFilePath));
}
}
}