75 lines
2.5 KiB
PHP
75 lines
2.5 KiB
PHP
|
|
<?php
|
||
|
|
|
||
|
|
declare(strict_types=1);
|
||
|
|
|
||
|
|
namespace App\Application\Article;
|
||
|
|
|
||
|
|
use App\Application\Storage\StorageManagerInterface;
|
||
|
|
use App\Domain\Article\ArticlePhoto;
|
||
|
|
use App\Domain\Article\Repository\ArticlePhotoRepositoryInterface;
|
||
|
|
use App\Domain\Article\Repository\ArticleRepositoryInterface;
|
||
|
|
use Symfony\Component\Uid\Uuid;
|
||
|
|
|
||
|
|
final class PhotoService
|
||
|
|
{
|
||
|
|
public function __construct(
|
||
|
|
private readonly ArticleRepositoryInterface $articleRepository,
|
||
|
|
private readonly ArticlePhotoRepositoryInterface $photoRepository,
|
||
|
|
private readonly StorageManagerInterface $storageManager,
|
||
|
|
) {
|
||
|
|
}
|
||
|
|
|
||
|
|
public function upload(Uuid $articleId, string $tempPath, string $originalFilename): ArticlePhoto
|
||
|
|
{
|
||
|
|
$article = $this->articleRepository->findById($articleId)
|
||
|
|
?? throw new \DomainException("Article {$articleId->toRfc4122()} not found");
|
||
|
|
|
||
|
|
$stored = $this->storageManager->store($tempPath, $originalFilename);
|
||
|
|
|
||
|
|
$existingPhotos = $this->photoRepository->findByArticle($articleId);
|
||
|
|
$isMain = 0 === \count($existingPhotos);
|
||
|
|
$sortOrder = \count($existingPhotos);
|
||
|
|
|
||
|
|
$photo = new ArticlePhoto($article, $stored->storagePath, $stored->filename, $isMain, $sortOrder);
|
||
|
|
|
||
|
|
$this->photoRepository->save($photo);
|
||
|
|
|
||
|
|
return $photo;
|
||
|
|
}
|
||
|
|
|
||
|
|
public function setMain(Uuid $photoId): void
|
||
|
|
{
|
||
|
|
$photo = $this->photoRepository->findById($photoId)
|
||
|
|
?? throw new \DomainException("Photo {$photoId->toRfc4122()} not found");
|
||
|
|
|
||
|
|
$allPhotos = $this->photoRepository->findByArticle($photo->getArticle()->getId());
|
||
|
|
foreach ($allPhotos as $p) {
|
||
|
|
$p->setIsMain($p->getId()->equals($photoId));
|
||
|
|
$this->photoRepository->save($p);
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
public function delete(Uuid $photoId): void
|
||
|
|
{
|
||
|
|
$photo = $this->photoRepository->findById($photoId)
|
||
|
|
?? throw new \DomainException("Photo {$photoId->toRfc4122()} not found");
|
||
|
|
|
||
|
|
$fullPath = $this->storageManager->getFullPath($photo->getStoragePath(), $photo->getFilename());
|
||
|
|
if (file_exists($fullPath)) {
|
||
|
|
unlink($fullPath);
|
||
|
|
}
|
||
|
|
|
||
|
|
if ($photo->isMain()) {
|
||
|
|
$articleId = $photo->getArticle()->getId();
|
||
|
|
$this->photoRepository->remove($photo);
|
||
|
|
$remaining = $this->photoRepository->findByArticle($articleId);
|
||
|
|
if ([] !== $remaining) {
|
||
|
|
$remaining[0]->setIsMain(true);
|
||
|
|
$this->photoRepository->save($remaining[0]);
|
||
|
|
}
|
||
|
|
} else {
|
||
|
|
$this->photoRepository->remove($photo);
|
||
|
|
}
|
||
|
|
}
|
||
|
|
}
|