<?php
namespace App\EventListener;
use App\Service\ImageResizer;
use Symfony\Component\HttpFoundation\File\File;
use Vich\UploaderBundle\Event\Event;
class UploadedImagesListener
{
public function onVichUploaderPostUpload(Event $event)
{
$mapping = $event->getMapping();
$object = $event->getObject();
$file = $mapping->getFile($object);
$ext = $file->guessExtension();
if (!in_array($ext, ['jpg', 'png', 'jpeg'])) {
return;
}
$filePath = $file->getPathname();
$name = str_replace('.', '', uniqid('', true)).'.'.$ext;
$newFilePath = $file->getPath().'/'.$name;
if (!ImageResizer::resizeImage($filePath, $newFilePath)) {
return;
}
// Set new file info
$newFile = new File($newFilePath, false);
$mapping->setFileName($object, $name);
$mapping->writeProperty($object, 'size', $newFile->getSize());
$dimensions = @getimagesize($newFile);
$mapping->writeProperty($object, 'dimensions', array_splice($dimensions, 0, 2));
}
}