Refactor uploded file handling
This commit is contained in:
parent
7f485cee91
commit
df57a6f303
4 changed files with 60 additions and 33 deletions
42
src/Service/OfferPhotoHelper.php
Normal file
42
src/Service/OfferPhotoHelper.php
Normal 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);
|
||||
}
|
||||
|
||||
}
|
||||
}
|
Reference in a new issue