pflaenz.li-Symfony/src/Service/OfferPhotoHelper.php

42 lines
1.1 KiB
PHP

<?php
namespace App\Service;
use App\Entity\Offer;
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, Offer $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);
}
}
}