Files
Toiminnanohjaus/app/Modules/Inventory/Application/UseCases/ChangeStockItemImage.php
T
2026-11-26 16:18:59 +02:00

54 lines
1.7 KiB
PHP

<?php
declare(strict_types=1);
namespace App\Modules\Inventory\Application\UseCases;
use App\Modules\Inventory\Application\Contracts\StockItemImages;
use App\Modules\Inventory\Domain\Contracts\StockItemRepository;
use App\Modules\Inventory\Domain\Exceptions\InvalidStockImage;
use App\Modules\Inventory\Domain\Exceptions\StockItemNotFound;
use App\Modules\Shared\Application\Contracts\TransactionManager;
/**
* Sets or removes a stock item's image; the replaced files are deleted.
*/
final class ChangeStockItemImage
{
public function __construct(
private StockItemRepository $items,
private StockItemImages $images,
private TransactionManager $transactions,
) {}
/**
* @param string|null $uploadedFilePath Null removes the image.
*
* @throws StockItemNotFound
* @throws InvalidStockImage
*/
public function execute(int $itemId, ?string $uploadedFilePath): void
{
$this->items->findById($itemId) ?? throw new StockItemNotFound;
$stored = $uploadedFilePath === null ? null : $this->images->store($uploadedFilePath, $itemId);
/** @var list<string> $old */
$old = $this->transactions->run(function () use ($itemId, $stored): array {
$item = $this->items->findById($itemId) ?? throw new StockItemNotFound;
$old = array_values(array_filter([$item->imagePath(), $item->thumbnailPath()]));
if ($stored === null) {
$item->removeImage();
} else {
$item->setImage($stored['path'], $stored['thumbnailPath']);
}
$this->items->save($item);
return $old;
});
$this->images->delete($old);
}
}