Refactor uploded file handling

This commit is contained in:
Jannis Portmann 2021-07-14 13:47:42 +02:00
parent 7f485cee91
commit df57a6f303
4 changed files with 60 additions and 33 deletions

View file

@ -0,0 +1,42 @@
<?php
namespace App\Service;
use App\Entity\Offering;
use Psr\Log\LoggerInterface;
use Symfony\Component\Filesystem\Exception\IOExceptionInterface;
use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\HttpFoundation\File\UploadedFile;
class OfferPhotoHelper
{
private $logger;
public function __construct(LoggerInterface $logger)
{
$this->filesystem = new Filesystem();
}
public function uploadOfferPhoto(string $photoDir, UploadedFile $photo, Offering $offer)
{
$filename = uniqid().'.'.$photo->guessExtension();
try {
$photo->move($photoDir, $filename);
} catch (FileException $e) {
// unable to upload the photo, give up
$this->addFlash("error", "There was an error uploading the photo: ".$e);
return $this->redirectToRoute('new_offer');
}
$offer->setPhotoFilename($filename);
}
public function deleteOfferPhoto(string $photoDir, string $filename)
{
$file = $photoDir . '/' . $filename;
if($this->filesystem->exists($file)) {
$this->filesystem->remove($file);
}
}
}