diff --git a/app/Casts/OrderLineProductCast.php b/app/Casts/OrderLineProductCast.php index 916c5e2f..f1958d37 100644 --- a/app/Casts/OrderLineProductCast.php +++ b/app/Casts/OrderLineProductCast.php @@ -16,6 +16,7 @@ use Illuminate\Database\Eloquent\Model; use Illuminate\Support\Arr; use Ramsey\Uuid\Uuid; use Symfony\Component\Uid\Uuid as SymfonyUuid; +use Uwil\Storage\Lib\ValueObjects\StorageFilePath; /** * @implements CastsAttributes @@ -58,7 +59,7 @@ class OrderLineProductCast implements CastsAttributes discountedPrice: new MoneyCast()->get($model, 'discounted_price', Arr::get($data, 'discounted_price'), []), priceKgTtc: new MoneyCast()->get($model, 'price_kg_ttc', Arr::get($data, 'price_kg_ttc'), []), taxRate: TaxRate::fromPercent($taxRate), - picture: is_string($picture = Arr::get($data, 'picture')) ? $picture : null, + picture: is_string($picture = Arr::get($data, 'picture')) ? new StorageFilePath($picture) : null, ); } @@ -99,7 +100,7 @@ class OrderLineProductCast implements CastsAttributes [] ), 'tax_rate' => $value->taxRate->percent(), - 'picture' => $value->picture, + 'picture' => $value->picture?->value, ], \JSON_THROW_ON_ERROR | \JSON_UNESCAPED_SLASHES); } } diff --git a/app/Cqs/Actions/Contact/SubmitContactForm.php b/app/Cqs/Actions/Contact/SubmitContactForm.php new file mode 100644 index 00000000..3414fc79 --- /dev/null +++ b/app/Cqs/Actions/Contact/SubmitContactForm.php @@ -0,0 +1,59 @@ + + */ +final class SubmitContactForm implements Action +{ + public function __construct( + private readonly StorageService $storageService, + private readonly PrivateS3Disk $privateS3Disk, + ) { + } + + /** + * @param \App\Cqs\Actions\Contact\SubmitContactFormInput $input + */ + #[\Override] + public function __invoke(ActionInput $input): ContactFormData + { + Assert::isInstanceOf($input, SubmitContactFormInput::class); + + $attachedFile = null; + + if ($input->file instanceof UploadedFile && $input->file->isValid()) { + $storedPath = $this->storageService->storeUploadedOntoDisk($input->file, $this->privateS3Disk->disk); + $attachedFile = new AttachedFile( + path: $storedPath->value, + originalName: $input->file->getClientOriginalName(), + mimeType: $input->file->getMimeType() ?? 'application/octet-stream', + ); + } + + return new ContactFormData( + lastName: $input->lastName, + firstName: $input->firstName, + email: $input->email, + subject: $input->subject, + message: $input->message, + orderRef: $input->orderRef, + file: $attachedFile, + ); + } +} diff --git a/app/Cqs/Actions/Contact/SubmitContactFormInput.php b/app/Cqs/Actions/Contact/SubmitContactFormInput.php new file mode 100644 index 00000000..55aaad78 --- /dev/null +++ b/app/Cqs/Actions/Contact/SubmitContactFormInput.php @@ -0,0 +1,32 @@ +lastName)); + Assert::stringNotEmpty(trim($this->firstName)); + Assert::stringNotEmpty(trim($this->email)); + Assert::stringNotEmpty(trim($this->subject)); + Assert::stringNotEmpty(trim($this->message)); + + if ($this->orderRef !== null) { + Assert::stringNotEmpty(trim($this->orderRef)); + } + } +} diff --git a/app/Cqs/Actions/Products/CreateProduct.php b/app/Cqs/Actions/Products/CreateProduct.php index 8cdf4f30..5eaaeff4 100644 --- a/app/Cqs/Actions/Products/CreateProduct.php +++ b/app/Cqs/Actions/Products/CreateProduct.php @@ -6,10 +6,15 @@ namespace App\Cqs\Actions\Products; use App\Contracts\Action; use App\Contracts\ActionInput; +use App\Lib\PublicS3Disk; use App\Models\Product; use App\Models\Tag; +use App\Services\ImageOptimizerService; +use Illuminate\Http\UploadedFile; use Illuminate\Support\Facades\Date; use Illuminate\Support\Str; +use Uwil\Storage\Contracts\StorageService; +use Uwil\Storage\Lib\ValueObjects\StorageFilePath; use Webmozart\Assert\Assert; /** @@ -17,6 +22,13 @@ use Webmozart\Assert\Assert; */ final class CreateProduct implements Action { + public function __construct( + protected readonly StorageService $storageService, + protected readonly PublicS3Disk $s3Disk, + protected readonly ImageOptimizerService $imageOptimizerService, + ) { + } + /** * @param \App\Cqs\Actions\Products\CreateProductInput $input */ @@ -44,14 +56,14 @@ final class CreateProduct implements Action $product->star = $input->star; $product->status = $input->status; - if ($input->picture !== null) { - $product->setAttribute('picture', $input->picture); + if ($input->picture instanceof UploadedFile) { + $product->picture = $this->storeFile($input->picture); } $product->picture_alt = (string) $input->pictureAlt; $product->picture_title = (string) $input->pictureTitle; - if ($input->pictureLarge !== null) { - $product->setAttribute('picture_large', $input->pictureLarge); + if ($input->pictureLarge instanceof UploadedFile) { + $product->picture_large = $this->storeFile($input->pictureLarge); } $product->picture_large_alt = (string) $input->pictureLargeAlt; $product->picture_large_title = (string) $input->pictureLargeTitle; @@ -106,4 +118,11 @@ final class CreateProduct implements Action $product->products()->sync($syncData); } + + protected function storeFile(UploadedFile $file): StorageFilePath + { + $optimized = $this->imageOptimizerService->optimize($file); + + return $this->storageService->storeFileOntoDisk($optimized, $this->s3Disk->disk); + } } diff --git a/app/Cqs/Actions/Products/CreateProductInput.php b/app/Cqs/Actions/Products/CreateProductInput.php index f2d4748c..79109ae1 100644 --- a/app/Cqs/Actions/Products/CreateProductInput.php +++ b/app/Cqs/Actions/Products/CreateProductInput.php @@ -11,6 +11,7 @@ use Domain\Enums\SellUnit; use Domain\Enums\TaxRate; use Domain\Enums\Units\InvoicingUnit; use Domain\Enums\Units\OrderUnit; +use Illuminate\Http\UploadedFile; use Money\Money; use Webmozart\Assert\Assert; @@ -38,10 +39,10 @@ final readonly class CreateProductInput implements ActionInput public ?CarbonInterface $orderableEnd = null, public bool $star = false, public bool $status = false, - public mixed $picture = null, + public ?UploadedFile $picture = null, public ?string $pictureAlt = null, public ?string $pictureTitle = null, - public mixed $pictureLarge = null, + public ?UploadedFile $pictureLarge = null, public ?string $pictureLargeAlt = null, public ?string $pictureLargeTitle = null, public array $tags = [], diff --git a/app/Cqs/Actions/Products/DeleteProduct.php b/app/Cqs/Actions/Products/DeleteProduct.php index 8af950c1..290fc501 100644 --- a/app/Cqs/Actions/Products/DeleteProduct.php +++ b/app/Cqs/Actions/Products/DeleteProduct.php @@ -6,6 +6,9 @@ namespace App\Cqs\Actions\Products; use App\Contracts\Action; use App\Contracts\ActionInput; +use App\Lib\PublicS3Disk; +use App\Models\Product; +use Uwil\Storage\Contracts\StorageService; use Webmozart\Assert\Assert; /** @@ -13,6 +16,12 @@ use Webmozart\Assert\Assert; */ final class DeleteProduct implements Action { + public function __construct( + protected readonly StorageService $storageService, + protected readonly PublicS3Disk $s3Disk, + ) { + } + /** * @param \App\Cqs\Actions\Products\DeleteProductInput $input */ @@ -21,6 +30,28 @@ final class DeleteProduct implements Action { Assert::isInstanceOf($input, DeleteProductInput::class); - return (bool) $input->product->deleteOrFail(); + $product = Product::query() + ->where('id', $input->productId->value->toString()) + ->first(); + + if (! $product) { + return false; + } + + if ( + $product->picture && $this->storageService + ->fileExistsOnDisk($product->picture, $this->s3Disk->disk) + ) { + $this->storageService->removeFromDisk($product->picture, $this->s3Disk->disk); + } + + if ( + $product->picture_large && $this->storageService + ->fileExistsOnDisk($product->picture_large, $this->s3Disk->disk) + ) { + $this->storageService->removeFromDisk($product->picture_large, $this->s3Disk->disk); + } + + return (bool) $product->deleteOrFail(); } } diff --git a/app/Cqs/Actions/Products/DeleteProductInput.php b/app/Cqs/Actions/Products/DeleteProductInput.php index 43a1f2cf..bd878552 100644 --- a/app/Cqs/Actions/Products/DeleteProductInput.php +++ b/app/Cqs/Actions/Products/DeleteProductInput.php @@ -5,12 +5,12 @@ declare(strict_types=1); namespace App\Cqs\Actions\Products; use App\Contracts\ActionInput; -use App\Models\Product; +use Domain\Models\ValueObjects\Entities\ProductId; final readonly class DeleteProductInput implements ActionInput { public function __construct( - public Product $product, + public ProductId $productId, ) { } } diff --git a/app/Cqs/Actions/Products/UpdateProduct.php b/app/Cqs/Actions/Products/UpdateProduct.php index a4acab0b..dc6e5060 100644 --- a/app/Cqs/Actions/Products/UpdateProduct.php +++ b/app/Cqs/Actions/Products/UpdateProduct.php @@ -6,10 +6,15 @@ namespace App\Cqs\Actions\Products; use App\Contracts\Action; use App\Contracts\ActionInput; +use App\Lib\PublicS3Disk; use App\Models\Product; use App\Models\Tag; +use App\Services\ImageOptimizerService; +use Illuminate\Http\UploadedFile; use Illuminate\Support\Facades\Date; use Illuminate\Support\Str; +use Uwil\Storage\Contracts\StorageService; +use Uwil\Storage\Lib\ValueObjects\StorageFilePath; use Webmozart\Assert\Assert; /** @@ -17,6 +22,13 @@ use Webmozart\Assert\Assert; */ final class UpdateProduct implements Action { + public function __construct( + protected readonly StorageService $storageService, + protected readonly PublicS3Disk $s3Disk, + protected readonly ImageOptimizerService $imageOptimizerService, + ) { + } + /** * @param \App\Cqs\Actions\Products\UpdateProductInput $input */ @@ -25,7 +37,9 @@ final class UpdateProduct implements Action { Assert::isInstanceOf($input, UpdateProductInput::class); - $product = $input->product; + $product = Product::query() + ->where('id', $input->productId->value->toString()) + ->firstOrFail(); $product->name = $input->name; $product->short_description = $input->shortDescription; $product->description = $input->description; @@ -44,14 +58,14 @@ final class UpdateProduct implements Action $product->star = $input->star; $product->status = $input->status; - if ($input->picture !== null) { - $product->setAttribute('picture', $input->picture); + if ($input->picture instanceof UploadedFile) { + $product->setAttribute('picture', $this->storeFile($input->picture)); } $product->picture_alt = (string) $input->pictureAlt; $product->picture_title = (string) $input->pictureTitle; - if ($input->pictureLarge !== null) { - $product->setAttribute('picture_large', $input->pictureLarge); + if ($input->pictureLarge instanceof UploadedFile) { + $product->setAttribute('picture_large', $this->storeFile($input->pictureLarge)); } $product->picture_large_alt = (string) $input->pictureLargeAlt; $product->picture_large_title = (string) $input->pictureLargeTitle; @@ -106,4 +120,11 @@ final class UpdateProduct implements Action $product->products()->sync($syncData); } + + protected function storeFile(UploadedFile $file): StorageFilePath + { + $optimized = $this->imageOptimizerService->optimize($file); + + return $this->storageService->storeFileOntoDisk($optimized, $this->s3Disk->disk); + } } diff --git a/app/Cqs/Actions/Products/UpdateProductInput.php b/app/Cqs/Actions/Products/UpdateProductInput.php index b3f75990..79163d45 100644 --- a/app/Cqs/Actions/Products/UpdateProductInput.php +++ b/app/Cqs/Actions/Products/UpdateProductInput.php @@ -5,14 +5,16 @@ declare(strict_types=1); namespace App\Cqs\Actions\Products; use App\Contracts\ActionInput; -use App\Models\Product; use Carbon\CarbonInterface; use Domain\Enums\ProductBrand; use Domain\Enums\SellUnit; use Domain\Enums\TaxRate; use Domain\Enums\Units\InvoicingUnit; use Domain\Enums\Units\OrderUnit; +use Domain\Models\ValueObjects\Entities\ProductId; +use Illuminate\Http\UploadedFile; use Money\Money; +use Uwil\Storage\Lib\ValueObjects\StorageFilePath; use Webmozart\Assert\Assert; final readonly class UpdateProductInput implements ActionInput @@ -22,7 +24,7 @@ final readonly class UpdateProductInput implements ActionInput * @param list $associatedProductsIds */ public function __construct( - public Product $product, + public ProductId $productId, public string $name, public string $shortDescription, public string $description, @@ -40,10 +42,10 @@ final readonly class UpdateProductInput implements ActionInput public ?CarbonInterface $orderableEnd = null, public bool $star = false, public bool $status = false, - public mixed $picture = null, + public UploadedFile | StorageFilePath | null $picture = null, public ?string $pictureAlt = null, public ?string $pictureTitle = null, - public mixed $pictureLarge = null, + public UploadedFile | StorageFilePath | null $pictureLarge = null, public ?string $pictureLargeAlt = null, public ?string $pictureLargeTitle = null, public array $tags = [], diff --git a/app/Cqs/Actions/Ranges/CreateRange.php b/app/Cqs/Actions/Ranges/CreateRange.php index 634d6ad1..ddaeaf05 100644 --- a/app/Cqs/Actions/Ranges/CreateRange.php +++ b/app/Cqs/Actions/Ranges/CreateRange.php @@ -6,7 +6,12 @@ namespace App\Cqs\Actions\Ranges; use App\Contracts\Action; use App\Contracts\ActionInput; +use App\Lib\PublicS3Disk; use App\Models\Range; +use App\Services\ImageOptimizerService; +use Illuminate\Http\UploadedFile; +use Uwil\Storage\Contracts\StorageService; +use Uwil\Storage\Lib\ValueObjects\StorageFilePath; use Webmozart\Assert\Assert; /** @@ -14,6 +19,13 @@ use Webmozart\Assert\Assert; */ final class CreateRange implements Action { + public function __construct( + protected readonly StorageService $storageService, + protected readonly PublicS3Disk $s3Disk, + protected readonly ImageOptimizerService $imageOptimizerService, + ) { + } + /** * @param \App\Cqs\Actions\Ranges\CreateRangeInput $input */ @@ -30,8 +42,8 @@ final class CreateRange implements Action 'status' => $input->status, ]; - if ($input->picture !== null) { - $attributes['picture'] = $input->picture; + if ($input->picture instanceof UploadedFile) { + $attributes['picture'] = $this->storeFile($input->picture); } $range = new Range(); @@ -40,4 +52,11 @@ final class CreateRange implements Action return $range; } + + protected function storeFile(UploadedFile $file): StorageFilePath + { + $optimized = $this->imageOptimizerService->optimize($file); + + return $this->storageService->storeFileOntoDisk($optimized, $this->s3Disk->disk); + } } diff --git a/app/Cqs/Actions/Ranges/CreateRangeInput.php b/app/Cqs/Actions/Ranges/CreateRangeInput.php index 6031b01e..9e015949 100644 --- a/app/Cqs/Actions/Ranges/CreateRangeInput.php +++ b/app/Cqs/Actions/Ranges/CreateRangeInput.php @@ -14,7 +14,7 @@ final readonly class CreateRangeInput implements ActionInput public function __construct( public string $name, public ?string $description, - public UploadedFile | string | null $picture, + public ?UploadedFile $picture, public PictureMetadata $pictureMetadata, public bool $status, ) { diff --git a/app/Cqs/Actions/Ranges/DeleteRange.php b/app/Cqs/Actions/Ranges/DeleteRange.php index 228248fb..3c2a84f4 100644 --- a/app/Cqs/Actions/Ranges/DeleteRange.php +++ b/app/Cqs/Actions/Ranges/DeleteRange.php @@ -6,6 +6,8 @@ namespace App\Cqs\Actions\Ranges; use App\Contracts\Action; use App\Contracts\ActionInput; +use App\Lib\PublicS3Disk; +use Uwil\Storage\Contracts\StorageService; use Webmozart\Assert\Assert; /** @@ -13,6 +15,12 @@ use Webmozart\Assert\Assert; */ final class DeleteRange implements Action { + public function __construct( + protected readonly StorageService $storageService, + protected readonly PublicS3Disk $s3Disk, + ) { + } + /** * @param \App\Cqs\Actions\Ranges\DeleteRangeInput $input */ @@ -21,6 +29,15 @@ final class DeleteRange implements Action { Assert::isInstanceOf($input, DeleteRangeInput::class); - return (bool) $input->range->deleteOrFail(); + $deletion = (bool) $input->range->deleteOrFail(); + + if ( + $deletion && $input->range->picture && $this->storageService + ->fileExistsOnDisk($input->range->picture, $this->s3Disk->disk) + ) { + $this->storageService->removeFromDisk($input->range->picture, $this->s3Disk->disk); + } + + return $deletion; } } diff --git a/app/Cqs/Actions/Ranges/UpdateRange.php b/app/Cqs/Actions/Ranges/UpdateRange.php index 5e37f58a..ccb9574b 100644 --- a/app/Cqs/Actions/Ranges/UpdateRange.php +++ b/app/Cqs/Actions/Ranges/UpdateRange.php @@ -6,7 +6,12 @@ namespace App\Cqs\Actions\Ranges; use App\Contracts\Action; use App\Contracts\ActionInput; +use App\Lib\PublicS3Disk; use App\Models\Range; +use App\Services\ImageOptimizerService; +use Illuminate\Http\UploadedFile; +use Uwil\Storage\Contracts\StorageService; +use Uwil\Storage\Lib\ValueObjects\StorageFilePath; use Webmozart\Assert\Assert; /** @@ -14,6 +19,13 @@ use Webmozart\Assert\Assert; */ final class UpdateRange implements Action { + public function __construct( + protected readonly StorageService $storageService, + protected readonly PublicS3Disk $s3Disk, + protected readonly ImageOptimizerService $imageOptimizerService, + ) { + } + /** * @param \App\Cqs\Actions\Ranges\UpdateRangeInput $input */ @@ -30,8 +42,8 @@ final class UpdateRange implements Action 'status' => $input->status, ]; - if ($input->picture !== null) { - $attributes['picture'] = $input->picture; + if ($input->picture instanceof UploadedFile) { + $attributes['picture'] = $this->storeFile($input->picture); } $range = $input->range; @@ -40,4 +52,11 @@ final class UpdateRange implements Action return $range; } + + protected function storeFile(UploadedFile $file): StorageFilePath + { + $optimized = $this->imageOptimizerService->optimize($file); + + return $this->storageService->storeFileOntoDisk($optimized, $this->s3Disk->disk); + } } diff --git a/app/Cqs/Actions/Ranges/UpdateRangeInput.php b/app/Cqs/Actions/Ranges/UpdateRangeInput.php index 496dc782..0acbc1f4 100644 --- a/app/Cqs/Actions/Ranges/UpdateRangeInput.php +++ b/app/Cqs/Actions/Ranges/UpdateRangeInput.php @@ -8,6 +8,7 @@ use App\Contracts\ActionInput; use App\Models\Range; use Domain\Models\ValueObjects\PictureMetadata; use Illuminate\Http\UploadedFile; +use Uwil\Storage\Lib\ValueObjects\StorageFilePath; use Webmozart\Assert\Assert; final readonly class UpdateRangeInput implements ActionInput @@ -16,7 +17,7 @@ final readonly class UpdateRangeInput implements ActionInput public Range $range, public string $name, public ?string $description, - public UploadedFile | string | null $picture, + public UploadedFile | StorageFilePath | null $picture, public PictureMetadata $pictureMetadata, public bool $status, ) { diff --git a/app/Cqs/Actions/Slides/CreateSlide.php b/app/Cqs/Actions/Slides/CreateSlide.php index 92823dc1..850fd2a8 100644 --- a/app/Cqs/Actions/Slides/CreateSlide.php +++ b/app/Cqs/Actions/Slides/CreateSlide.php @@ -6,8 +6,13 @@ namespace App\Cqs\Actions\Slides; use App\Contracts\Action; use App\Contracts\ActionInput; +use App\Lib\PublicS3Disk; use App\Models\Slide; +use App\Services\ImageOptimizerService; +use Illuminate\Http\UploadedFile; use Illuminate\Support\Carbon; +use Uwil\Storage\Contracts\StorageService; +use Uwil\Storage\Lib\ValueObjects\StorageFilePath; use Webmozart\Assert\Assert; /** @@ -15,6 +20,13 @@ use Webmozart\Assert\Assert; */ final class CreateSlide implements Action { + public function __construct( + protected readonly StorageService $storageService, + protected readonly PublicS3Disk $s3Disk, + protected readonly ImageOptimizerService $imageOptimizerService, + ) { + } + /** * @param \App\Cqs\Actions\Slides\CreateSlideInput $input */ @@ -36,8 +48,8 @@ final class CreateSlide implements Action 'date_end' => $input->period->end !== null ? Carbon::instance($input->period->end) : null, ]; - if ($input->picture !== null) { - $attributes['picture'] = $input->picture; + if ($input->picture instanceof UploadedFile) { + $attributes['picture'] = $this->storeFile($input->picture); } $slide = new Slide(); @@ -46,4 +58,11 @@ final class CreateSlide implements Action return $slide; } + + protected function storeFile(UploadedFile $file): StorageFilePath + { + $optimized = $this->imageOptimizerService->optimize($file); + + return $this->storageService->storeFileOntoDisk($optimized, $this->s3Disk->disk); + } } diff --git a/app/Cqs/Actions/Slides/CreateSlideInput.php b/app/Cqs/Actions/Slides/CreateSlideInput.php index 9cf21571..17212755 100644 --- a/app/Cqs/Actions/Slides/CreateSlideInput.php +++ b/app/Cqs/Actions/Slides/CreateSlideInput.php @@ -14,7 +14,7 @@ final readonly class CreateSlideInput implements ActionInput public function __construct( public string $title, public ?string $text = null, - public UploadedFile | string | null $picture = null, + public ?UploadedFile $picture = null, public ?string $pictureAlt = null, public ?string $pictureTitle = null, public ?string $link = null, diff --git a/app/Cqs/Actions/Slides/DeleteSlide.php b/app/Cqs/Actions/Slides/DeleteSlide.php index dc9f8e96..03bbb39c 100644 --- a/app/Cqs/Actions/Slides/DeleteSlide.php +++ b/app/Cqs/Actions/Slides/DeleteSlide.php @@ -6,6 +6,8 @@ namespace App\Cqs\Actions\Slides; use App\Contracts\Action; use App\Contracts\ActionInput; +use App\Lib\PublicS3Disk; +use Uwil\Storage\Contracts\StorageService; use Webmozart\Assert\Assert; /** @@ -13,6 +15,12 @@ use Webmozart\Assert\Assert; */ final class DeleteSlide implements Action { + public function __construct( + private readonly StorageService $storageService, + private readonly PublicS3Disk $s3Disk, + ) { + } + /** * @param \App\Cqs\Actions\Slides\DeleteSlideInput $input */ @@ -21,6 +29,13 @@ final class DeleteSlide implements Action { Assert::isInstanceOf($input, DeleteSlideInput::class); + if ( + $input->slide->picture && $this->storageService + ->fileExistsOnDisk($input->slide->picture, $this->s3Disk->disk) + ) { + $this->storageService->removeFromDisk($input->slide->picture, $this->s3Disk->disk); + } + return (bool) $input->slide->deleteOrFail(); } } diff --git a/app/Cqs/Actions/Slides/UpdateSlide.php b/app/Cqs/Actions/Slides/UpdateSlide.php index 075af4e7..16f83cf3 100644 --- a/app/Cqs/Actions/Slides/UpdateSlide.php +++ b/app/Cqs/Actions/Slides/UpdateSlide.php @@ -6,8 +6,13 @@ namespace App\Cqs\Actions\Slides; use App\Contracts\Action; use App\Contracts\ActionInput; +use App\Lib\PublicS3Disk; use App\Models\Slide; +use App\Services\ImageOptimizerService; +use Illuminate\Http\UploadedFile; use Illuminate\Support\Carbon; +use Uwil\Storage\Contracts\StorageService; +use Uwil\Storage\Lib\ValueObjects\StorageFilePath; use Webmozart\Assert\Assert; /** @@ -15,6 +20,13 @@ use Webmozart\Assert\Assert; */ final class UpdateSlide implements Action { + public function __construct( + protected readonly StorageService $storageService, + protected readonly PublicS3Disk $s3Disk, + protected readonly ImageOptimizerService $imageOptimizerService, + ) { + } + /** * @param \App\Cqs\Actions\Slides\UpdateSlideInput $input */ @@ -36,8 +48,8 @@ final class UpdateSlide implements Action 'date_end' => $input->period->end !== null ? Carbon::instance($input->period->end) : null, ]; - if ($input->picture !== null) { - $attributes['picture'] = $input->picture; + if ($input->picture instanceof UploadedFile) { + $attributes['picture'] = $this->storeFile($input->picture); } $slide = $input->slide; @@ -46,4 +58,11 @@ final class UpdateSlide implements Action return $slide; } + + protected function storeFile(UploadedFile $file): StorageFilePath + { + $optimized = $this->imageOptimizerService->optimize($file); + + return $this->storageService->storeFileOntoDisk($optimized, $this->s3Disk->disk); + } } diff --git a/app/Cqs/Actions/Slides/UpdateSlideInput.php b/app/Cqs/Actions/Slides/UpdateSlideInput.php index d2c71a53..b0f879a4 100644 --- a/app/Cqs/Actions/Slides/UpdateSlideInput.php +++ b/app/Cqs/Actions/Slides/UpdateSlideInput.php @@ -8,6 +8,7 @@ use App\Contracts\ActionInput; use App\Models\Slide; use Domain\Models\ValueObjects\DatePeriod; use Illuminate\Http\UploadedFile; +use Uwil\Storage\Lib\ValueObjects\StorageFilePath; use Webmozart\Assert\Assert; final readonly class UpdateSlideInput implements ActionInput @@ -16,7 +17,7 @@ final readonly class UpdateSlideInput implements ActionInput public Slide $slide, public string $title, public ?string $text = null, - public UploadedFile | string | null $picture = null, + public UploadedFile | StorageFilePath | null $picture = null, public ?string $pictureAlt = null, public ?string $pictureTitle = null, public ?string $link = null, diff --git a/app/Dto/DiscountProductDto.php b/app/Dto/DiscountProductDto.php index 432866d7..54c80c98 100644 --- a/app/Dto/DiscountProductDto.php +++ b/app/Dto/DiscountProductDto.php @@ -24,12 +24,12 @@ final readonly class DiscountProductDto implements \JsonSerializable, Arrayable return new self( id: (string) $product->id, name: (string) $product->name, - picture: $product->picture, + picture: publicS3Asset($product->picture), ); } /** - * @return array{id: string, name: string} + * @return array{id: string, name: string, picture: ?string} */ #[\Override] public function toArray(): array @@ -42,7 +42,7 @@ final readonly class DiscountProductDto implements \JsonSerializable, Arrayable } /** - * @return array{id: string, name: string} + * @return array{id: string, name: string, picture: ?string} */ #[\Override] public function jsonSerialize(): array diff --git a/app/Dto/RangeDto.php b/app/Dto/RangeDto.php index 3254013c..a25f4125 100644 --- a/app/Dto/RangeDto.php +++ b/app/Dto/RangeDto.php @@ -33,7 +33,7 @@ final readonly class RangeDto implements Arrayable, UrlRoutable name: $range->name, slug: $range->slug, description: $range->description, - picture: is_string($range->picture) ? $range->picture : null, + picture: publicS3Asset($range->picture), picture_alt: $range->picture_alt, picture_title: $range->picture_title, order: $range->order, diff --git a/app/Dto/SlideDto.php b/app/Dto/SlideDto.php index 83827884..a4b781e6 100644 --- a/app/Dto/SlideDto.php +++ b/app/Dto/SlideDto.php @@ -39,7 +39,7 @@ final readonly class SlideDto implements Arrayable, UrlRoutable id: $slide->id, title: $slide->title, text: $slide->text, - picture: is_string($slide->picture) ? $slide->picture : null, + picture: publicS3Asset($slide->picture), picture_alt: $slide->picture_alt, picture_title: $slide->picture_title, link: $slide->link, diff --git a/app/Http/Controllers/Fo/Pages/ContactController.php b/app/Http/Controllers/Fo/Pages/ContactController.php index 28a4982b..7425cad2 100644 --- a/app/Http/Controllers/Fo/Pages/ContactController.php +++ b/app/Http/Controllers/Fo/Pages/ContactController.php @@ -5,6 +5,7 @@ declare(strict_types=1); namespace App\Http\Controllers\Fo\Pages; use App\Contracts\Executor; +use App\Cqs\Actions\Contact\SubmitContactForm; use App\Cqs\Queries\Pages\GetPageQuery; use App\Cqs\Queries\Pages\GetPageQueryInput; use App\Cqs\Queries\Shops\GetShopQuery; @@ -61,9 +62,12 @@ class ContactController extends Controller )); } - public function submitForm(ContactFormRequest $request): RedirectResponse + public function submitForm(ContactFormRequest $request, SubmitContactForm $action): RedirectResponse { - $contactData = $request->toValueObject(); + $contactData = $this->executor->execute( + $action, + $request->toSubmitContactFormInput(), + ); Mail::to($this->mailToContact) ->send(new SendContactMail($contactData)); diff --git a/app/Http/Resources/Fo/Ajax/BasketProductResource.php b/app/Http/Resources/Fo/Ajax/BasketProductResource.php index 21ae3f89..9212dc43 100644 --- a/app/Http/Resources/Fo/Ajax/BasketProductResource.php +++ b/app/Http/Resources/Fo/Ajax/BasketProductResource.php @@ -43,7 +43,7 @@ class BasketProductResource extends JsonResource 'slug' => $this->basketProduct->slug, 'picture' => $this->basketProduct->picture ? - url($this->basketProduct->picture) : null, + publicS3Asset($this->basketProduct->picture) : null, 'description' => $this->basketProduct->description, 'weight_variable' => $this->basketProduct->weightVariable, 'discountRate' => $this->basketProduct->discountRate->ratio(), diff --git a/app/Mail/SendContactMail.php b/app/Mail/SendContactMail.php index 3c992e0c..20fc6e6b 100644 --- a/app/Mail/SendContactMail.php +++ b/app/Mail/SendContactMail.php @@ -4,6 +4,7 @@ declare(strict_types=1); namespace App\Mail; +use App\Lib\PrivateS3Disk; use Domain\Models\ValueObjects\ContactFormData; use Illuminate\Bus\Queueable; use Illuminate\Contracts\Queue\ShouldQueue; @@ -88,8 +89,10 @@ class SendContactMail extends Mailable implements ShouldQueue $extension ); + $disk = app()->make(PrivateS3Disk::class)->disk->value; + return [ - Attachment::fromPath($this->data->file->path) + Attachment::fromStorageDisk($disk, $this->data->file->path) ->as($joinedFileName) ->withMime($this->data->file->mimeType), ]; diff --git a/app/Models/Product.php b/app/Models/Product.php index 1921efa3..a2b8a354 100644 --- a/app/Models/Product.php +++ b/app/Models/Product.php @@ -4,11 +4,11 @@ declare(strict_types=1); namespace App\Models; +use App\Casts\FilePathCast; use App\Casts\MoneyCast; use App\Interfaces\ModelWithOrder; use App\Interfaces\ModelWithStar; use App\Interfaces\ModelWithStatus; -use App\Lib\Helpers\FileStorageHelper; use App\Lib\Helpers\ToolboxHelper; use App\Traits\Models\HasOrder; use App\Traits\Models\HasStar; @@ -42,10 +42,10 @@ use Uwil\Laravel\Redirections\Traits\IsRedirectable; * @property ProductBrand $brand * @property string $description * @property string|null $short_description - * @property string|null $picture + * @property \Uwil\Storage\Lib\ValueObjects\StorageFilePath|null $picture * @property string $picture_alt * @property string $picture_title - * @property string|null $picture_large + * @property \Uwil\Storage\Lib\ValueObjects\StorageFilePath|null $picture_large * @property string $picture_large_alt * @property string $picture_large_title * @property \Money\Money $price @@ -133,20 +133,13 @@ class Product extends Model implements ModelWithOrder, ModelWithStar, ModelWithS self::makeStatusSense($model); self::makeStarSense($model); }); - - static::deleting(function (self $model): void { - FileStorageHelper::removeFile($model, 'picture'); - FileStorageHelper::removeFile($model, 'picture_large'); - }); } private static function manageFields(self $model): void { self::assertNameIsUnique($model->name, $model->id); - $model->slug = Str::slug($model->name); - $model->picture = FileStorageHelper::storeFile($model, $model->picture, true); - $model->picture_large = FileStorageHelper::storeFile($model, $model->picture_large, true); + $model->slug = Str::slug($model->name); if ($model->order === null) { $max = self::query()->max('order'); @@ -165,6 +158,8 @@ class Product extends Model implements ModelWithOrder, ModelWithStar, ModelWithS protected function casts(): array { return [ + 'picture' => FilePathCast::class, + 'picture_large' => FilePathCast::class, 'orderable_start' => 'datetime', 'orderable_end' => 'datetime', 'price' => MoneyCast::class, diff --git a/app/Models/Range.php b/app/Models/Range.php index ec72dd69..b586eae6 100644 --- a/app/Models/Range.php +++ b/app/Models/Range.php @@ -4,9 +4,9 @@ declare(strict_types=1); namespace App\Models; +use App\Casts\FilePathCast; use App\Interfaces\ModelWithOrder; use App\Interfaces\ModelWithStatus; -use App\Lib\Helpers\FileStorageHelper; use App\Lib\Helpers\ToolboxHelper; use App\Traits\Models\HasOrder; use App\Traits\Models\HasStatus; @@ -22,7 +22,7 @@ use Uwil\Laravel\Redirections\Traits\IsRedirectable; * @property string $name * @property string $slug * @property string|null $description - * @property string|null $picture + * @property \Uwil\Storage\Lib\ValueObjects\StorageFilePath|null $picture * @property string $picture_alt * @property string $picture_title * @property bool $status @@ -56,9 +56,6 @@ class Range extends Model implements ModelWithOrder, ModelWithStatus, Redirectab static::updating(function (self $model): void { self::manageFields($model); }); - static::deleting(function (self $model): void { - FileStorageHelper::removeFile($model, 'picture'); - }); } #[\Override] @@ -81,7 +78,6 @@ class Range extends Model implements ModelWithOrder, ModelWithStatus, Redirectab self::assertNameIsUnique($model->name, $model->id); $model->slug = Str::slug($model->name); - $model->picture = FileStorageHelper::storeFile($model, $model->picture, true); if (is_null($model->order)) { $maxOrder = self::query()->max('order'); $model->order = is_numeric($maxOrder) ? (int) $maxOrder + 1 : 0; @@ -105,7 +101,8 @@ class Range extends Model implements ModelWithOrder, ModelWithStatus, Redirectab protected function casts(): array { return [ - 'status' => 'bool', + 'picture' => FilePathCast::class, + 'status' => 'bool', ]; } } diff --git a/app/Models/Slide.php b/app/Models/Slide.php index bef0dd62..b2e7156d 100644 --- a/app/Models/Slide.php +++ b/app/Models/Slide.php @@ -4,9 +4,9 @@ declare(strict_types=1); namespace App\Models; +use App\Casts\FilePathCast; use App\Interfaces\ModelWithOrder; use App\Interfaces\ModelWithStatus; -use App\Lib\Helpers\FileStorageHelper; use App\Traits\Models\HasOrder; use App\Traits\Models\HasStatus; use Illuminate\Contracts\Session\Session; @@ -21,7 +21,7 @@ use Shared\Helpers\DatesHelper; * @property int $id * @property string $title * @property string|null $text - * @property string|null $picture + * @property \Uwil\Storage\Lib\ValueObjects\StorageFilePath|null $picture * @property string|null $picture_alt * @property string|null $picture_title * @property string|null $link_label @@ -77,9 +77,6 @@ class Slide extends Model implements ModelWithOrder, ModelWithStatus self::manageFields($model); self::makeStatusSense($model); }); - static::deleting(function (self $model): void { - FileStorageHelper::removeFile($model, 'picture'); - }); } public function isVisible(): bool @@ -95,8 +92,6 @@ class Slide extends Model implements ModelWithOrder, ModelWithStatus private static function manageFields(self $model): void { - $model->picture = FileStorageHelper::storeFile($model, $model->picture, true); - if ($model->order === null) { $max = self::query()->max('order'); $model->order = is_scalar($max) ? intval($max) + 1 : 1; @@ -120,6 +115,7 @@ class Slide extends Model implements ModelWithOrder, ModelWithStatus protected function casts(): array { return [ + 'picture' => FilePathCast::class, 'link_new_tab' => 'bool', 'connected' => 'bool', 'status' => 'bool', diff --git a/database/factories/SlideFactory.php b/database/factories/SlideFactory.php index a42b0cd6..5c1a68e5 100644 --- a/database/factories/SlideFactory.php +++ b/database/factories/SlideFactory.php @@ -37,7 +37,7 @@ class SlideFactory extends Factory 'link_label' => fake()->words(2, true), 'link_new_tab' => fake()->boolean(), 'connected' => fake()->boolean(20), - 'picture' => fake()->imageUrl(1920, 1080, 'nature'), + 'picture' => 'slides/' . fake()->slug() . '.jpg', 'picture_alt' => fake()->sentence(3), 'picture_title' => fake()->sentence(3), 'status' => true, diff --git a/domain/Models/ValueObjects/BasketProduct.php b/domain/Models/ValueObjects/BasketProduct.php index 390b6e6b..23f33999 100644 --- a/domain/Models/ValueObjects/BasketProduct.php +++ b/domain/Models/ValueObjects/BasketProduct.php @@ -10,6 +10,7 @@ use Domain\Enums\Units\OrderUnit; use Domain\Models\Entities\Product; use Domain\Models\ValueObjects\Entities\ProductId; use Money\Money; +use Uwil\Storage\Lib\ValueObjects\StorageFilePath; final readonly class BasketProduct { @@ -25,7 +26,7 @@ final readonly class BasketProduct public ?IncoId $incoId, public OrderUnit $orderUnit, public string $slug, - public ?string $picture, + public ?StorageFilePath $picture, public ?string $description, public bool $weightVariable, public DiscountRate $discountRate, diff --git a/domain/Models/ValueObjects/OrderLineProduct.php b/domain/Models/ValueObjects/OrderLineProduct.php index a8ab97fc..6abf59ea 100644 --- a/domain/Models/ValueObjects/OrderLineProduct.php +++ b/domain/Models/ValueObjects/OrderLineProduct.php @@ -9,6 +9,7 @@ use Domain\Enums\TaxRate; use Domain\Enums\Units\OrderUnit; use Domain\Models\ValueObjects\Entities\ProductId; use Money\Money; +use Uwil\Storage\Lib\ValueObjects\StorageFilePath; final readonly class OrderLineProduct { @@ -23,7 +24,7 @@ final readonly class OrderLineProduct public Money $discountedPrice, public Money $priceKgTtc, public TaxRate $taxRate, - public ?string $picture = null + public ?StorageFilePath $picture = null ) { if (trim($name) === '') { throw new \DomainException('Product name cannot be empty'); diff --git a/infra/Adapters/Serializers/BasketSerializer.php b/infra/Adapters/Serializers/BasketSerializer.php index 5d8f3fa4..cc7465c1 100644 --- a/infra/Adapters/Serializers/BasketSerializer.php +++ b/infra/Adapters/Serializers/BasketSerializer.php @@ -17,6 +17,8 @@ use Illuminate\Support\Arr; use Money\Currency; use Money\Money; use Ramsey\Uuid\Uuid; +use Uwil\Storage\Lib\ValueObjects\StorageFilePath; +use Webmozart\Assert\Assert; class BasketSerializer { @@ -81,6 +83,10 @@ class BasketSerializer $priceKgTtcCurrency = Arr::string($priceKgTtc, 'currency'); $options = Arr::array($itemData, 'options', []); + foreach ($options as $key => $option) { + Assert::string($key); + } + if (empty($unitPriceHtCurrency)) { throw new \DomainException("Currency is required for unitPriceHt of item with id $id"); } @@ -109,7 +115,7 @@ class BasketSerializer incoId: is_scalar($incoId) && $incoId !== 0 ? new IncoId((int) $incoId) : null, orderUnit: OrderUnit::from($orderUnit), slug: $slug, - picture: is_string($picture) && $picture !== '' ? $picture : null, + picture: is_string($picture) && $picture !== '' ? new StorageFilePath($picture) : null, description: is_string($description) && $description !== '' ? $description : null, weightVariable: $weightVariable, discountRate: $discountRate, diff --git a/resources/views/bo/products/index-list.blade.php b/resources/views/bo/products/index-list.blade.php index a486f1a4..8b1dad60 100644 --- a/resources/views/bo/products/index-list.blade.php +++ b/resources/views/bo/products/index-list.blade.php @@ -46,7 +46,7 @@ {{ Str::limit($product->name, 45) }} @if (!empty($product->picture)) - {{ $product->picture_alt }} @else {{ __('No Content') }} @@ -54,7 +54,7 @@ @if (!empty($product->picture_large)) - {{ $product->picture_large_alt }} @else {{ __('No Content') }} diff --git a/resources/views/bo/ranges/index-list.blade.php b/resources/views/bo/ranges/index-list.blade.php index 2b350213..34e25f5e 100644 --- a/resources/views/bo/ranges/index-list.blade.php +++ b/resources/views/bo/ranges/index-list.blade.php @@ -9,6 +9,7 @@ 'name' => Str::ucfirst(__('validation.attributes.title')), 'picture' => Str::ucfirst(__('validation.attributes.image')), 'order' => Str::ucfirst(__('validation.custom.attributes.order')), + 'status' => Str::ucfirst(__('validation.custom.attributes.status')) ]; @endphp @include('bo.modules.tableColSorter', ['cols' => $cols, 'mobileHide' => ['picture']]) @@ -18,7 +19,7 @@ {{ $range->name }} - {{ $range->picture_alt }} + {{ $range->picture_alt }} @include('bo.modules.change-order', [ 'route' => 'bo.ranges.change-order', diff --git a/resources/views/bo/slides/index-list.blade.php b/resources/views/bo/slides/index-list.blade.php index c82a07da..3cbdbe11 100644 --- a/resources/views/bo/slides/index-list.blade.php +++ b/resources/views/bo/slides/index-list.blade.php @@ -26,7 +26,7 @@ {{ $slide->title }} - {{ $slide->title }} + {{ $slide->title }} {{ $slide->link_label }} diff --git a/resources/views/bo/tags/index-list.blade.php b/resources/views/bo/tags/index-list.blade.php index 07f9eba6..c16a3659 100644 --- a/resources/views/bo/tags/index-list.blade.php +++ b/resources/views/bo/tags/index-list.blade.php @@ -8,6 +8,7 @@ $cols = [ 'label' => Str::ucfirst(__('validation.custom.attributes.label')), 'order' => Str::ucfirst(__('validation.custom.attributes.order')), + 'status' => Str::ucfirst(__('validation.custom.attributes.status')) ]; @endphp @include('bo.modules.tableColSorter', ['cols' => $cols, 'mobileHide' => ['description']]) diff --git a/resources/views/fo/home-parts/ranges.blade.php b/resources/views/fo/home-parts/ranges.blade.php index 5da9b252..246f8ee4 100644 --- a/resources/views/fo/home-parts/ranges.blade.php +++ b/resources/views/fo/home-parts/ranges.blade.php @@ -4,7 +4,7 @@
- {{ $range->picture_alt }}
diff --git a/resources/views/fo/home-parts/sliders/main.blade.php b/resources/views/fo/home-parts/sliders/main.blade.php index fc727aaa..2dd05557 100644 --- a/resources/views/fo/home-parts/sliders/main.blade.php +++ b/resources/views/fo/home-parts/sliders/main.blade.php @@ -26,7 +26,7 @@ @if (!empty($slide->picture))
- {{ $slide->picture_alt ?: $slide->title }}
@endif diff --git a/tests/Feature/App/Http/Controllers/Fo/Pages/ContactControllerTest.php b/tests/Feature/App/Http/Controllers/Fo/Pages/ContactControllerTest.php index dce49c08..5a80ab2d 100644 --- a/tests/Feature/App/Http/Controllers/Fo/Pages/ContactControllerTest.php +++ b/tests/Feature/App/Http/Controllers/Fo/Pages/ContactControllerTest.php @@ -5,14 +5,19 @@ declare(strict_types=1); namespace Tests\Feature\App\Http\Controllers\Fo\Pages; use App\Dto\ShopDto; +use App\Lib\PrivateS3Disk; use App\Mail\SendContactMail; use App\Models\Page; use App\Models\Shop; use Database\Seeders\ContentSeeder; +use Illuminate\Http\UploadedFile; use Illuminate\Support\Facades\Cache; use Illuminate\Support\Facades\Config; use Illuminate\Support\Facades\Mail; use Illuminate\Support\Facades\View; +use Uwil\Storage\Contracts\StorageService; +use Uwil\Storage\Lib\ValueObjects\DiskName; +use Uwil\Storage\Lib\ValueObjects\StorageFilePath; describe('ContactController', function (): void { beforeEach(function (): void { @@ -87,6 +92,43 @@ describe('ContactController', function (): void { Mail::assertQueued(SendContactMail::class); }); + it('submits contact form with an attachment uploaded via StorageService', function (): void { + /** @var \Tests\TestCase $this */ + // GIVEN + Mail::fake(); + $file = UploadedFile::fake()->create('piece.pdf', 100, 'application/pdf'); + $this->mock(StorageService::class, function ($mock): void { + $mock->shouldReceive('storeUploadedOntoDisk') + ->once() + ->with( + \Mockery::type(UploadedFile::class), + \Mockery::on(fn (DiskName $disk): bool => $disk->value === PrivateS3Disk::DISK_NAME), + ) + ->andReturn(new StorageFilePath('contact-attachments/piece.pdf')); + }); + + $data = [ + 'first_name' => 'Jean', + 'last_name' => 'Dupont', + 'email' => 'jean.dupont@gmail.com', + 'subject' => 'Question avec PJ', + 'message' => 'Bonjour, ceci est un message de test qui contient au moins vingt caractères.', + 'file' => $file, + 'ok_cgv' => '1', + ]; + + // WHEN + $response = $this->from('/contactez-nous')->post('/contactez-nous', $data); + + // THEN + $response->assertRedirect('/contactez-nous'); + $response->assertSessionHas('status', true); + Mail::assertQueued( + SendContactMail::class, + fn (SendContactMail $mail): bool => $mail->data->file?->path === 'contact-attachments/piece.pdf' + ); + }); + it('redirects with validation errors when form data is invalid', function (): void { /** @var \Tests\TestCase $this */ // GIVEN diff --git a/tests/Integration/WithApp/App/Actions/Contact/SubmitContactFormTest.php b/tests/Integration/WithApp/App/Actions/Contact/SubmitContactFormTest.php new file mode 100644 index 00000000..2753cd86 --- /dev/null +++ b/tests/Integration/WithApp/App/Actions/Contact/SubmitContactFormTest.php @@ -0,0 +1,94 @@ +shouldNotReceive('storeUploadedOntoDisk'); + $action = new SubmitContactForm($storage, new PrivateS3Disk()); + $input = new SubmitContactFormInput( + lastName: 'Doe', + firstName: 'John', + email: 'john.doe@example.com', + subject: 'Question', + message: 'Bonjour, ceci est un message de test valide.', + orderRef: '12345', + ); + + // WHEN + $result = $action($input); + + // THEN + expect($result)->toBeInstanceOf(ContactFormData::class) + ->and($result->lastName)->toBe('Doe') + ->and($result->firstName)->toBe('John') + ->and($result->email)->toBe('john.doe@example.com') + ->and($result->subject)->toBe('Question') + ->and($result->orderRef)->toBe('12345') + ->and($result->file)->toBeNull(); + }); + + it('uploads attachment to private S3 disk and attaches metadata', function (): void { + // GIVEN + $file = UploadedFile::fake()->create('document.pdf', 100, 'application/pdf'); + $storage = \Mockery::mock(StorageService::class); + $storage->shouldReceive('storeUploadedOntoDisk') + ->once() + ->with( + $file, + \Mockery::on(fn (DiskName $disk): bool => $disk->value === PrivateS3Disk::DISK_NAME), + ) + ->andReturn(new StorageFilePath('contact-attachments/document.pdf')); + + $action = new SubmitContactForm($storage, new PrivateS3Disk()); + $input = new SubmitContactFormInput( + lastName: 'Doe', + firstName: 'John', + email: 'john.doe@example.com', + subject: 'Question', + message: 'Bonjour, ceci est un message de test valide.', + file: $file, + ); + + // WHEN + $result = $action($input); + + // THEN + expect($result)->toBeInstanceOf(ContactFormData::class) + ->and($result->file)->toBeInstanceOf(AttachedFile::class) + ->and($result->file?->path)->toBe('contact-attachments/document.pdf') + ->and($result->file?->originalName)->toBe('document.pdf') + ->and($result->file?->mimeType)->toBe('application/pdf'); + }); + + it('throws when an invalid input is passed', function (): void { + // GIVEN + $storage = \Mockery::mock(StorageService::class); + $storage->shouldNotReceive('storeUploadedOntoDisk'); + $action = new SubmitContactForm($storage, new PrivateS3Disk()); + $invalidInput = new class () implements ActionInput + { + }; + + // WHEN + expect( + /** @phpstan-ignore argument.type */ + fn () => $action($invalidInput) + ) + // THEN + ->toThrow(\InvalidArgumentException::class); + }); +}); diff --git a/tests/Integration/WithApp/App/Actions/Ranges/CreateRangeTest.php b/tests/Integration/WithApp/App/Actions/Ranges/CreateRangeTest.php index 31aadc91..98a4adfd 100644 --- a/tests/Integration/WithApp/App/Actions/Ranges/CreateRangeTest.php +++ b/tests/Integration/WithApp/App/Actions/Ranges/CreateRangeTest.php @@ -5,11 +5,16 @@ declare(strict_types=1); use App\Contracts\ActionInput; use App\Cqs\Actions\Ranges\CreateRange; use App\Cqs\Actions\Ranges\CreateRangeInput; +use App\Lib\PublicS3Disk; use App\Models\Range; +use App\Services\ImageOptimizerService; use Domain\Models\ValueObjects\PictureMetadata; use Illuminate\Foundation\Testing\RefreshDatabase; use Illuminate\Http\UploadedFile; -use Illuminate\Support\Facades\Storage; +use Psr\Log\NullLogger; +use Shared\Filesystem\TemporaryFileFactory; +use Uwil\Storage\Contracts\StorageService; +use Uwil\Storage\Lib\ValueObjects\StorageFilePath; uses(RefreshDatabase::class); @@ -17,8 +22,14 @@ describe('CreateRange action', function () { test('it creates and persists a range in database', function () { /** @var \Tests\TestCase $this */ // GIVEN - Storage::fake('public'); - $action = new CreateRange(); + // Strict double: no S3 side effect, upload asserted. + $storage = \Mockery::mock(StorageService::class); + $storage->shouldReceive('storeFileOntoDisk')->once()->andReturn(new StorageFilePath('media/range.jpg')); + $action = new CreateRange( + $storage, + new PublicS3Disk('https://cdn.test'), + new ImageOptimizerService(new TemporaryFileFactory(), new NullLogger()), + ); $input = new CreateRangeInput( name: 'Gamme Décoration', description: '

Une superbe gamme

', @@ -49,7 +60,13 @@ describe('CreateRange action', function () { test('it throws when an invalid input is passed', function () { // GIVEN - $action = new CreateRange(); + $storage = \Mockery::mock(StorageService::class); + $storage->shouldNotReceive('storeFileOntoDisk'); + $action = new CreateRange( + $storage, + new PublicS3Disk('https://cdn.test'), + new ImageOptimizerService(new TemporaryFileFactory(), new NullLogger()), + ); $invalidInput = new class () implements ActionInput { }; diff --git a/tests/Integration/WithApp/App/Actions/Ranges/DeleteRangeTest.php b/tests/Integration/WithApp/App/Actions/Ranges/DeleteRangeTest.php index 19ae58dd..b8e391f9 100644 --- a/tests/Integration/WithApp/App/Actions/Ranges/DeleteRangeTest.php +++ b/tests/Integration/WithApp/App/Actions/Ranges/DeleteRangeTest.php @@ -5,8 +5,11 @@ declare(strict_types=1); use App\Contracts\ActionInput; use App\Cqs\Actions\Ranges\DeleteRange; use App\Cqs\Actions\Ranges\DeleteRangeInput; +use App\Lib\PublicS3Disk; use App\Models\Range; use Illuminate\Foundation\Testing\RefreshDatabase; +use Uwil\Storage\Contracts\StorageService; +use Uwil\Storage\Lib\ValueObjects\StorageFilePath; uses(RefreshDatabase::class); @@ -21,7 +24,11 @@ describe('DeleteRange action', function () { $range->status = true; $range->save(); - $action = new DeleteRange(); + // Range has no picture: storage must stay untouched. + $storage = \Mockery::mock(StorageService::class); + $storage->shouldNotReceive('fileExistsOnDisk'); + $storage->shouldNotReceive('removeFromDisk'); + $action = new DeleteRange($storage, new PublicS3Disk('https://cdn.test')); $input = new DeleteRangeInput(range: $range); // WHEN @@ -34,9 +41,34 @@ describe('DeleteRange action', function () { ]); }); + test('it removes the picture from storage when the range has one', function () { + /** @var \Tests\TestCase $this */ + // GIVEN + $range = new Range(); + $range->name = 'Gamme Avec Image'; + $range->picture_alt = 'Alt'; + $range->picture_title = 'Title'; + $range->status = true; + $range->picture = new StorageFilePath('media/range.jpg'); + $range->save(); + + $storage = \Mockery::mock(StorageService::class); + $storage->shouldReceive('fileExistsOnDisk')->once()->andReturnTrue(); + $storage->shouldReceive('removeFromDisk')->once()->andReturnTrue(); + $action = new DeleteRange($storage, new PublicS3Disk('https://cdn.test')); + + // WHEN + $result = $action(new DeleteRangeInput(range: $range)); + + // THEN + expect($result)->toBeTrue(); + $this->assertDatabaseMissing('ranges', ['id' => $range->id]); + }); + test('it throws when an invalid input is passed', function () { // GIVEN - $action = new DeleteRange(); + $storage = \Mockery::mock(StorageService::class); + $action = new DeleteRange($storage, new PublicS3Disk('https://cdn.test')); $invalidInput = new class () implements ActionInput { }; diff --git a/tests/Integration/WithApp/App/Actions/Ranges/UpdateRangeTest.php b/tests/Integration/WithApp/App/Actions/Ranges/UpdateRangeTest.php index 326ef02c..bbff5731 100644 --- a/tests/Integration/WithApp/App/Actions/Ranges/UpdateRangeTest.php +++ b/tests/Integration/WithApp/App/Actions/Ranges/UpdateRangeTest.php @@ -5,11 +5,16 @@ declare(strict_types=1); use App\Contracts\ActionInput; use App\Cqs\Actions\Ranges\UpdateRange; use App\Cqs\Actions\Ranges\UpdateRangeInput; +use App\Lib\PublicS3Disk; use App\Models\Range; +use App\Services\ImageOptimizerService; use Domain\Models\ValueObjects\PictureMetadata; use Illuminate\Foundation\Testing\RefreshDatabase; use Illuminate\Http\UploadedFile; -use Illuminate\Support\Facades\Storage; +use Psr\Log\NullLogger; +use Shared\Filesystem\TemporaryFileFactory; +use Uwil\Storage\Contracts\StorageService; +use Uwil\Storage\Lib\ValueObjects\StorageFilePath; uses(RefreshDatabase::class); @@ -17,7 +22,6 @@ describe('UpdateRange action', function () { test('it updates an existing range in database', function () { /** @var \Tests\TestCase $this */ // GIVEN - Storage::fake('public'); $range = new Range(); $range->name = 'Gamme Initiale'; $range->description = 'Ancien contenu'; @@ -26,7 +30,14 @@ describe('UpdateRange action', function () { $range->status = true; $range->save(); - $action = new UpdateRange(); + // Storage is a strict double: no network/S3 side effect, and the upload is asserted. + $storage = \Mockery::mock(StorageService::class); + $storage->shouldReceive('storeFileOntoDisk')->once()->andReturn(new StorageFilePath('media/range.jpg')); + $action = new UpdateRange( + $storage, + new PublicS3Disk('https://cdn.test'), + new ImageOptimizerService(new TemporaryFileFactory(), new NullLogger()), + ); $input = new UpdateRangeInput( range: $range, name: 'Gamme Renommée', @@ -57,7 +68,13 @@ describe('UpdateRange action', function () { test('it throws when an invalid input is passed', function () { // GIVEN - $action = new UpdateRange(); + $storage = \Mockery::mock(StorageService::class); + $storage->shouldNotReceive('storeFileOntoDisk'); + $action = new UpdateRange( + $storage, + new PublicS3Disk('https://cdn.test'), + new ImageOptimizerService(new TemporaryFileFactory(), new NullLogger()), + ); $invalidInput = new class () implements ActionInput { }; diff --git a/tests/Integration/WithApp/App/Actions/Slides/CreateSlideTest.php b/tests/Integration/WithApp/App/Actions/Slides/CreateSlideTest.php index 0ae8ff06..0c4d841b 100644 --- a/tests/Integration/WithApp/App/Actions/Slides/CreateSlideTest.php +++ b/tests/Integration/WithApp/App/Actions/Slides/CreateSlideTest.php @@ -5,13 +5,25 @@ declare(strict_types=1); use App\Contracts\ActionInput; use App\Cqs\Actions\Slides\CreateSlide; use App\Cqs\Actions\Slides\CreateSlideInput; +use App\Lib\PublicS3Disk; use App\Models\Slide; +use App\Services\ImageOptimizerService; use Domain\Models\ValueObjects\DatePeriod; +use Psr\Log\NullLogger; +use Shared\Filesystem\TemporaryFileFactory; +use Uwil\Storage\Contracts\StorageService; describe('CreateSlide action', function (): void { it('creates and persists a slide in database', function (): void { // GIVEN - $action = new CreateSlide(); + // Strict double: no picture in this input, so storage must never be touched. + $storage = \Mockery::mock(StorageService::class); + $storage->shouldNotReceive('storeFileOntoDisk'); + $action = new CreateSlide( + $storage, + new PublicS3Disk('https://cdn.test'), + new ImageOptimizerService(new TemporaryFileFactory(), new NullLogger()), + ); $start = new \DateTimeImmutable('2026-06-01 10:00:00'); $end = new \DateTimeImmutable('2026-06-30 20:00:00'); $period = new DatePeriod($start, $end); @@ -46,7 +58,13 @@ describe('CreateSlide action', function (): void { it('throws when an invalid input is passed', function (): void { // GIVEN - $action = new CreateSlide(); + $storage = \Mockery::mock(StorageService::class); + $storage->shouldNotReceive('storeFileOntoDisk'); + $action = new CreateSlide( + $storage, + new PublicS3Disk('https://cdn.test'), + new ImageOptimizerService(new TemporaryFileFactory(), new NullLogger()), + ); $invalidInput = new class () implements ActionInput { }; diff --git a/tests/Integration/WithApp/App/Actions/Slides/DeleteSlideTest.php b/tests/Integration/WithApp/App/Actions/Slides/DeleteSlideTest.php index a9e22ebc..cdc1ce7a 100644 --- a/tests/Integration/WithApp/App/Actions/Slides/DeleteSlideTest.php +++ b/tests/Integration/WithApp/App/Actions/Slides/DeleteSlideTest.php @@ -5,17 +5,25 @@ declare(strict_types=1); use App\Contracts\ActionInput; use App\Cqs\Actions\Slides\DeleteSlide; use App\Cqs\Actions\Slides\DeleteSlideInput; +use App\Lib\PublicS3Disk; use App\Models\Slide; +use Uwil\Storage\Contracts\StorageService; +use Uwil\Storage\Lib\ValueObjects\StorageFilePath; describe('DeleteSlide action', function (): void { - it('deletes an existing slide from database', function (): void { + it('deletes an existing slide from database without picture', function (): void { + /** @var \Tests\TestCase $this */ // GIVEN $slide = new Slide(); $slide->title = 'Slide à supprimer'; $slide->text = '

Contenu

'; $slide->saveOrFail(); - $action = new DeleteSlide(); + // Slide has no picture: storage must stay untouched. + $storage = \Mockery::mock(StorageService::class); + $storage->shouldNotReceive('fileExistsOnDisk'); + $storage->shouldNotReceive('removeFromDisk'); + $action = new DeleteSlide($storage, new PublicS3Disk('https://cdn.test')); $input = new DeleteSlideInput(slide: $slide); // WHEN @@ -23,22 +31,52 @@ describe('DeleteSlide action', function (): void { // THEN expect($result)->toBeTrue(); + $this->assertDatabaseMissing('slides', [ + 'id' => $slide->id, + ]); + expect(Slide::query()->find($slide->id))->toBeNull(); + }); + + it('removes the picture from storage when the slide has one', function (): void { + /** @var \Tests\TestCase $this */ + // GIVEN + $slide = new Slide(); + $slide->title = 'Slide avec image'; + $slide->text = '

Contenu

'; + $slide->picture = new StorageFilePath('slides/slide.jpg'); + $slide->saveOrFail(); + + $storage = \Mockery::mock(StorageService::class); + $storage->shouldReceive('fileExistsOnDisk')->once()->andReturnTrue(); + $storage->shouldReceive('removeFromDisk')->once()->andReturnTrue(); + $action = new DeleteSlide($storage, new PublicS3Disk('https://cdn.test')); + $input = new DeleteSlideInput(slide: $slide); + + // WHEN + $result = $action($input); + + // THEN + expect($result)->toBeTrue(); + $this->assertDatabaseMissing('slides', [ + 'id' => $slide->id, + ]); expect(Slide::query()->find($slide->id))->toBeNull(); }); it('throws when an invalid input is passed', function (): void { // GIVEN - $action = new DeleteSlide(); + $storage = \Mockery::mock(StorageService::class); + $storage->shouldNotReceive('fileExistsOnDisk'); + $storage->shouldNotReceive('removeFromDisk'); + $action = new DeleteSlide($storage, new PublicS3Disk('https://cdn.test')); $invalidInput = new class () implements ActionInput { }; - // WHEN + // WHEN & THEN expect( /** @phpstan-ignore argument.type */ fn () => $action($invalidInput) - ) - // THEN - ->toThrow(\InvalidArgumentException::class); + )->toThrow(\InvalidArgumentException::class); }); }); diff --git a/tests/Integration/WithApp/App/Actions/Slides/UpdateSlideTest.php b/tests/Integration/WithApp/App/Actions/Slides/UpdateSlideTest.php index cd8e3676..0588fa73 100644 --- a/tests/Integration/WithApp/App/Actions/Slides/UpdateSlideTest.php +++ b/tests/Integration/WithApp/App/Actions/Slides/UpdateSlideTest.php @@ -5,18 +5,33 @@ declare(strict_types=1); use App\Contracts\ActionInput; use App\Cqs\Actions\Slides\UpdateSlide; use App\Cqs\Actions\Slides\UpdateSlideInput; +use App\Lib\PublicS3Disk; use App\Models\Slide; +use App\Services\ImageOptimizerService; use Domain\Models\ValueObjects\DatePeriod; +use Illuminate\Http\UploadedFile; +use Psr\Log\NullLogger; +use Shared\Filesystem\TemporaryFileFactory; +use Uwil\Storage\Contracts\StorageService; +use Uwil\Storage\Lib\ValueObjects\StorageFilePath; describe('UpdateSlide action', function (): void { - it('updates an existing slide in database', function (): void { + it('updates an existing slide without new picture', function (): void { + /** @var \Tests\TestCase $this */ // GIVEN $slide = new Slide(); $slide->title = 'Ancien Titre'; $slide->text = '

Ancien texte

'; $slide->saveOrFail(); - $action = new UpdateSlide(); + // Strict double: no picture in this input, so storeFileOntoDisk must never be touched. + $storage = \Mockery::mock(StorageService::class); + $storage->shouldNotReceive('storeFileOntoDisk'); + $action = new UpdateSlide( + $storage, + new PublicS3Disk('https://cdn.test'), + new ImageOptimizerService(new TemporaryFileFactory(), new NullLogger()), + ); $start = new \DateTimeImmutable('2026-07-01 10:00:00'); $end = new \DateTimeImmutable('2026-07-31 20:00:00'); $period = new DatePeriod($start, $end); @@ -48,11 +63,71 @@ describe('UpdateSlide action', function (): void { expect($fresh)->not->toBeNull() ->and($fresh?->title)->toBe('Titre Mis à Jour') ->and($fresh?->text)->toBe('

Texte mis à jour

'); + + $this->assertDatabaseHas('slides', [ + 'id' => $slide->id, + 'title' => 'Titre Mis à Jour', + ]); + }); + + it('updates an existing slide with a new uploaded picture', function (): void { + /** @var \Tests\TestCase $this */ + // GIVEN + $slide = new Slide(); + $slide->title = 'Ancien Titre'; + $slide->text = '

Ancien texte

'; + $slide->saveOrFail(); + + $storage = \Mockery::mock(StorageService::class); + $storage->shouldReceive('storeFileOntoDisk')->once()->andReturn(new StorageFilePath('slides/new-slide.jpg')); + $action = new UpdateSlide( + $storage, + new PublicS3Disk('https://cdn.test'), + new ImageOptimizerService(new TemporaryFileFactory(), new NullLogger()), + ); + + $input = new UpdateSlideInput( + slide: $slide, + title: 'Titre Avec Image', + text: '

Texte avec image

', + picture: UploadedFile::fake()->image('new-slide.jpg', 600, 400), + pictureAlt: 'Nouvel alt', + pictureTitle: 'Nouveau titre', + ); + + // WHEN + $updatedSlide = $action($input); + + // THEN + expect($updatedSlide->id)->toBe($slide->id) + ->and($updatedSlide->title)->toBe('Titre Avec Image') + ->and($updatedSlide->picture_alt)->toBe('Nouvel alt') + ->and($updatedSlide->picture_title)->toBe('Nouveau titre') + ->and($updatedSlide->picture)->toBeInstanceOf(StorageFilePath::class) + ->and($updatedSlide->picture?->value)->toBe('slides/new-slide.jpg'); + + $fresh = Slide::query()->find($slide->id); + expect($fresh)->not->toBeNull() + ->and($fresh?->title)->toBe('Titre Avec Image') + ->and($fresh?->picture?->value)->toBe('slides/new-slide.jpg'); + + $this->assertDatabaseHas('slides', [ + 'id' => $slide->id, + 'title' => 'Titre Avec Image', + 'picture_alt' => 'Nouvel alt', + 'picture_title' => 'Nouveau titre', + ]); }); it('throws when an invalid input is passed', function (): void { // GIVEN - $action = new UpdateSlide(); + $storage = \Mockery::mock(StorageService::class); + $storage->shouldNotReceive('storeFileOntoDisk'); + $action = new UpdateSlide( + $storage, + new PublicS3Disk('https://cdn.test'), + new ImageOptimizerService(new TemporaryFileFactory(), new NullLogger()), + ); $invalidInput = new class () implements ActionInput { }; diff --git a/tests/Integration/WithApp/App/Dto/SlideDtoTest.php b/tests/Integration/WithApp/App/Dto/SlideDtoTest.php index ef6291ef..6f6a7eb5 100644 --- a/tests/Integration/WithApp/App/Dto/SlideDtoTest.php +++ b/tests/Integration/WithApp/App/Dto/SlideDtoTest.php @@ -3,11 +3,19 @@ declare(strict_types=1); use App\Dto\SlideDto; +use App\Lib\PublicS3Disk; use App\Models\Slide; use Illuminate\Support\Carbon; +use Illuminate\Support\Facades\Storage; describe('SlideDto integration', function (): void { - it('creates a DTO from Slide model with booted application', function (): void { + beforeEach(function (): void { + config(['filesystems.disks.s3.url' => 'https://cdn.test']); + Storage::forgetDisk(['s3', 's3-public']); + app()->forgetInstance(PublicS3Disk::class); + }); + + it('creates a DTO from Slide model with booted application and resolves public S3 URL', function (): void { // GIVEN $dateStart = Carbon::parse('2026-06-01 10:00:00'); $dateEnd = Carbon::parse('2026-06-30 20:00:00'); @@ -35,7 +43,7 @@ describe('SlideDto integration', function (): void { expect($dto->id)->toBe(42) ->and($dto->title)->toBe('Bannière Été') ->and($dto->text)->toBe('

Découvrez notre nouvelle collection

') - ->and($dto->picture)->toBe('storage/modelfiles/slides/26/06/01/ab/summer.jpg') + ->and($dto->picture)->toBe('https://cdn.test/public/storage/modelfiles/slides/26/06/01/ab/summer.jpg') ->and($dto->picture_alt)->toBe('Collection Été') ->and($dto->picture_title)->toBe('Bannière promotionnelle été') ->and($dto->link)->toBe('https://example.com/ete') @@ -48,4 +56,24 @@ describe('SlideDto integration', function (): void { ->and($dto->status)->toBeTrue() ->and($dto->isVisible())->toBeFalse(); }); + + it('creates a DTO from Slide model when picture is null', function (): void { + // GIVEN + $slide = new Slide(); + $slide->id = 43; + $slide->title = 'Slide sans image'; + $slide->text = '

Texte uniquement

'; + $slide->picture = null; + $slide->link_new_tab = false; + $slide->connected = false; + $slide->order = 1; + $slide->status = true; + + // WHEN + $dto = SlideDto::fromModel($slide); + + // THEN + expect($dto->picture)->toBeNull() + ->and($dto->title)->toBe('Slide sans image'); + }); }); diff --git a/tests/Integration/WithApp/Casts/OrderLineProductCastTest.php b/tests/Integration/WithApp/Casts/OrderLineProductCastTest.php index baafe54e..1a5a3eb1 100644 --- a/tests/Integration/WithApp/Casts/OrderLineProductCastTest.php +++ b/tests/Integration/WithApp/Casts/OrderLineProductCastTest.php @@ -16,6 +16,7 @@ use Illuminate\Database\Eloquent\Model; use Money\Currency; use Money\Money; use Ramsey\Uuid\Uuid; +use Uwil\Storage\Lib\ValueObjects\StorageFilePath; describe('OrderLineProductCast', function () { @@ -53,7 +54,8 @@ describe('OrderLineProductCast', function () { ->and($vo->brand)->toBe(ProductBrand::loue) ->and($vo->orderUnit)->toBe(OrderUnit::PCE) ->and($vo->taxRate)->toBe(TaxRate::TVA_5_5) - ->and($vo->picture)->toBe('poulet.jpg'); + ->and($vo->picture)->toBeInstanceOf(StorageFilePath::class) + ->and($vo->picture->value)->toBe('poulet.jpg'); }); it('can cast JSON to OrderLineProduct with TVA 20% and null picture correctly', function () { @@ -105,7 +107,7 @@ describe('OrderLineProductCast', function () { discountedPrice: new Money(950, new Currency('EUR')), priceKgTtc: new Money(700, new Currency('EUR')), taxRate: TaxRate::TVA_5_5, - picture: 'poulet.jpg' + picture: new StorageFilePath('poulet.jpg') ); // WHEN diff --git a/tests/Integration/WithApp/Infra/Repositories/SessionBasketRepositoryTest.php b/tests/Integration/WithApp/Infra/Repositories/SessionBasketRepositoryTest.php index 93e3914b..b012fe71 100644 --- a/tests/Integration/WithApp/Infra/Repositories/SessionBasketRepositoryTest.php +++ b/tests/Integration/WithApp/Infra/Repositories/SessionBasketRepositoryTest.php @@ -17,6 +17,9 @@ use Domain\Ports\Repositories\BasketRepository; use Money\Currency; use Money\Money; use Ramsey\Uuid\Uuid; +use Uwil\Storage\Lib\ValueObjects\StorageFilePath; + +covers(BasketRepository::class); describe('SessionBasketRepository', function () { @@ -64,7 +67,7 @@ describe('SessionBasketRepository', function () { ->and($retrievedProduct->incoId?->value)->toBe($product->incoId?->value) ->and($retrievedProduct->orderUnit->value)->toBe($product->orderUnit->value) ->and($retrievedProduct->slug)->toBe($product->slug) - ->and($retrievedProduct->picture)->toBe($product->picture) + ->and($retrievedProduct->picture?->value)->toBe($product->picture?->value) ->and($retrievedProduct->description)->toBe($product->description) ->and($retrievedProduct->weightVariable)->toBe($product->weightVariable) ->and($retrievedProduct->discountRate->basisPoints())->toBe($product->discountRate->basisPoints()) @@ -83,7 +86,7 @@ describe('SessionBasketRepository', function () { incoId: new IncoId(456789), orderUnit: OrderUnit::from('KGM'), slug: 'poulet-roti', - picture: 'poulet.jpg', + picture: new StorageFilePath('poulet.jpg'), description: 'Un bon poulet', weightVariable: true, discountRate: DiscountRate::fromRatio(0.05), diff --git a/tests/Unit/App/Actions/Slides/CreateSlideInputTest.php b/tests/Unit/App/Actions/Slides/CreateSlideInputTest.php index b52ad42d..67694eb0 100644 --- a/tests/Unit/App/Actions/Slides/CreateSlideInputTest.php +++ b/tests/Unit/App/Actions/Slides/CreateSlideInputTest.php @@ -4,6 +4,7 @@ declare(strict_types=1); use App\Cqs\Actions\Slides\CreateSlideInput; use Domain\Models\ValueObjects\DatePeriod; +use Illuminate\Http\UploadedFile; describe('CreateSlideInput', function (): void { it('creates a valid CreateSlideInput instance with text', function (): void { @@ -29,7 +30,7 @@ describe('CreateSlideInput', function (): void { it('creates a valid CreateSlideInput instance with picture', function (): void { // GIVEN $title = 'Nouveau Slide Photo'; - $picture = 'storage/modelfiles/slides/picture.jpg'; + $picture = \Mockery::mock(UploadedFile::class); // WHEN $input = new CreateSlideInput( @@ -81,7 +82,11 @@ describe('CreateSlideInput', function (): void { $tooLongAlt = str_repeat('a', 76); // WHEN - expect(fn () => new CreateSlideInput(title: 'Slide', picture: 'pic.jpg', pictureAlt: $tooLongAlt)) + expect(fn () => new CreateSlideInput( + title: 'Slide', + picture: \Mockery::mock(UploadedFile::class), + pictureAlt: $tooLongAlt + )) // THEN ->toThrow(\InvalidArgumentException::class); }); diff --git a/tests/Unit/App/Casts/OrderLineProductCastTest.php b/tests/Unit/App/Casts/OrderLineProductCastTest.php index 104d71a7..2f4eece1 100644 --- a/tests/Unit/App/Casts/OrderLineProductCastTest.php +++ b/tests/Unit/App/Casts/OrderLineProductCastTest.php @@ -14,131 +14,140 @@ use Illuminate\Database\Eloquent\Model; use Money\Currency; use Money\Money; use Ramsey\Uuid\Uuid; +use Uwil\Storage\Lib\ValueObjects\StorageFilePath; -it('throws exception when getting null', function () { - // GIVEN - $cast = new OrderLineProductCast(); - $model = \Mockery::mock(Model::class); +covers(OrderLineProductCast::class); - // WHEN - $cast->get($model, 'product', null, []); +describe('OrderLineProductCast', function () { - // THEN -})->throws(\InvalidArgumentException::class, 'The value cannot be null.'); + it('throws exception when getting null', function () { + // GIVEN + $cast = new OrderLineProductCast(); + $model = \Mockery::mock(Model::class); -it('throws exception when getting non-string', function () { - // GIVEN - $cast = new OrderLineProductCast(); - $model = \Mockery::mock(Model::class); + // WHEN + $cast->get($model, 'product', null, []); - // WHEN - $cast->get($model, 'product', 123, []); + // THEN + })->throws(\InvalidArgumentException::class, 'The value cannot be null.'); - // THEN -})->throws(\InvalidArgumentException::class, 'The value must be a string.'); + it('throws exception when getting non-string', function () { + // GIVEN + $cast = new OrderLineProductCast(); + $model = \Mockery::mock(Model::class); -it('gets an order line product', function () { - // GIVEN - $cast = new OrderLineProductCast(); - $model = \Mockery::mock(Model::class); - $uuid = Uuid::uuid7()->toString(); + // WHEN + $cast->get($model, 'product', 123, []); - $json = json_encode([ - 'inco_id' => 123, - 'original_id' => $uuid, - 'name' => 'Product Name', - 'weight' => 1000, - 'weight_variable' => false, - 'brand' => ProductBrand::loue->value, - 'order_unit' => OrderUnit::PCE->value, - 'price' => '1000', - 'discounted_price' => '800', - 'price_kg_ttc' => '1000', - 'tax_rate' => TaxRate::TVA_5_5->percent(), - 'picture' => 'pic.jpg', - ]); + // THEN + })->throws(\InvalidArgumentException::class, 'The value must be a string.'); - // WHEN - $product = $cast->get($model, 'product', $json, []); + it('gets an order line product', function () { + // GIVEN + $cast = new OrderLineProductCast(); + $model = \Mockery::mock(Model::class); + $uuid = Uuid::uuid7()->toString(); - // THEN - expect($product)->toBeInstanceOf(OrderLineProduct::class) - ->and($product->incoId->value)->toBe(123) - ->and($product->originalId->value->toString())->toBe($uuid) - ->and($product->name)->toBe('Product Name') - ->and($product->weight->value)->toBe(1000) - ->and($product->weight->isVariable)->toBeFalse() - ->and($product->taxRate)->toBe(TaxRate::TVA_5_5) - ->and($product->picture)->toBe('pic.jpg'); -}); + $json = json_encode([ + 'inco_id' => 123, + 'original_id' => $uuid, + 'name' => 'Product Name', + 'weight' => 1000, + 'weight_variable' => false, + 'brand' => ProductBrand::loue->value, + 'order_unit' => OrderUnit::PCE->value, + 'price' => '1000', + 'discounted_price' => '800', + 'price_kg_ttc' => '1000', + 'tax_rate' => TaxRate::TVA_5_5->percent(), + 'picture' => 'pic.jpg', + ]); -it('gets an order line product with integer tax rate and null picture', function () { - // GIVEN - $cast = new OrderLineProductCast(); - $model = \Mockery::mock(Model::class); - $uuid = Uuid::uuid7()->toString(); + // WHEN + $product = $cast->get($model, 'product', $json, []); - $json = json_encode([ - 'inco_id' => 123, - 'original_id' => $uuid, - 'name' => 'Product Name', - 'weight' => 1000, - 'weight_variable' => false, - 'brand' => ProductBrand::loue->value, - 'order_unit' => OrderUnit::PCE->value, - 'price' => '1000', - 'discounted_price' => '800', - 'price_kg_ttc' => '1000', - 'tax_rate' => 20, // integer from json_decode for 20% - 'picture' => null, - ]); + // THEN + expect($product)->toBeInstanceOf(OrderLineProduct::class) + ->and($product->incoId->value)->toBe(123) + ->and($product->originalId->value->toString())->toBe($uuid) + ->and($product->name)->toBe('Product Name') + ->and($product->weight->value)->toBe(1000) + ->and($product->weight->isVariable)->toBeFalse() + ->and($product->taxRate)->toBe(TaxRate::TVA_5_5) + ->and($product->picture)->toBeInstanceOf(StorageFilePath::class) + ->and($product->picture->value)->toBe('pic.jpg'); + }); - // WHEN - $product = $cast->get($model, 'product', $json, []); + it('gets an order line product with integer tax rate and null picture', function () { + // GIVEN + $cast = new OrderLineProductCast(); + $model = \Mockery::mock(Model::class); + $uuid = Uuid::uuid7()->toString(); - // THEN - expect($product)->toBeInstanceOf(OrderLineProduct::class) - ->and($product->taxRate)->toBe(TaxRate::TVA_20) - ->and($product->picture)->toBeNull(); -}); + $json = json_encode([ + 'inco_id' => 123, + 'original_id' => $uuid, + 'name' => 'Product Name', + 'weight' => 1000, + 'weight_variable' => false, + 'brand' => ProductBrand::loue->value, + 'order_unit' => OrderUnit::PCE->value, + 'price' => '1000', + 'discounted_price' => '800', + 'price_kg_ttc' => '1000', + 'tax_rate' => 20, // integer from json_decode for 20% + 'picture' => null, + ]); -it('throws exception when setting invalid type', function () { - // GIVEN - $cast = new OrderLineProductCast(); - $model = \Mockery::mock(Model::class); + // WHEN + $product = $cast->get($model, 'product', $json, []); - // WHEN - $cast->set($model, 'product', 'invalid', []); + // THEN + expect($product)->toBeInstanceOf(OrderLineProduct::class) + ->and($product->taxRate)->toBe(TaxRate::TVA_20) + ->and($product->picture)->toBeNull(); + }); - // THEN -})->throws( - \InvalidArgumentException::class, - 'The given value is not an instance of OrderLineProduct.' -); + it('throws exception when setting invalid type', function () { + // GIVEN + $cast = new OrderLineProductCast(); + $model = \Mockery::mock(Model::class); -it('sets an order line product', function () { - // GIVEN - $cast = new OrderLineProductCast(); - $model = \Mockery::mock(Model::class); - $currency = resolve(Currency::class); + // WHEN + $cast->set($model, 'product', 'invalid', []); - $product = new OrderLineProduct( - incoId: new IncoId(123), - originalId: new ProductId(Uuid::uuid7()), - name: 'Product Name', - weight: new ProductWeight(1000, false), - brand: ProductBrand::cases()[0], // Pick first enum case - orderUnit: OrderUnit::cases()[0], // Pick first enum case - price: new Money(1000, $currency), - discountedPrice: new Money(800, $currency), - priceKgTtc: new Money(1000, $currency), - taxRate: TaxRate::TVA_20, - picture: 'pic.jpg' + // THEN + })->throws( + \InvalidArgumentException::class, + 'The given value is not an instance of OrderLineProduct.' ); - // WHEN - $value = $cast->set($model, 'product', $product, []); + it('sets an order line product', function () { + // GIVEN + $cast = new OrderLineProductCast(); + $model = \Mockery::mock(Model::class); + $currency = new Currency('EUR'); - // THEN - expect($value)->toBeJson(); + $product = new OrderLineProduct( + incoId: new IncoId(123), + originalId: new ProductId(Uuid::uuid7()), + name: 'Product Name', + weight: new ProductWeight(1000, false), + brand: ProductBrand::cases()[0], // Pick first enum case + orderUnit: OrderUnit::cases()[0], // Pick first enum case + price: new Money(1000, $currency), + discountedPrice: new Money(800, $currency), + priceKgTtc: new Money(1000, $currency), + taxRate: TaxRate::TVA_20, + picture: new StorageFilePath('pic.jpg') + ); + + // WHEN + $value = $cast->set($model, 'product', $product, []); + $data = json_decode($value, true); + + // THEN + expect($value)->toBeJson() + ->and($data['picture'])->toBe('pic.jpg'); + }); }); diff --git a/tests/Unit/Domain/Models/Entities/BasketTest.php b/tests/Unit/Domain/Models/Entities/BasketTest.php index 2535812b..94f6f135 100644 --- a/tests/Unit/Domain/Models/Entities/BasketTest.php +++ b/tests/Unit/Domain/Models/Entities/BasketTest.php @@ -15,6 +15,7 @@ use Domain\Models\ValueObjects\Entities\ProductId; use Domain\Models\ValueObjects\IncoId; use Money\Money; use Ramsey\Uuid\Uuid; +use Uwil\Storage\Lib\ValueObjects\StorageFilePath; describe('Basket and BasketProduct', function (): void { @@ -32,7 +33,7 @@ describe('Basket and BasketProduct', function (): void { 'incoId' => new IncoId(45), 'orderUnit' => OrderUnit::PCE, 'slug' => 'poulet-roti', - 'picture' => 'images/poulet.jpg', + 'picture' => new StorageFilePath('images/poulet.jpg'), 'description' => 'Un bon poulet rôti', 'weightVariable' => true, 'discountRate' => DiscountRate::fromRatio(0.2), @@ -65,7 +66,7 @@ describe('Basket and BasketProduct', function (): void { incoId: new IncoId(45), orderUnit: $orderUnit, slug: 'poulet-roti', - picture: 'images/poulet.jpg', + picture: new StorageFilePath('images/poulet.jpg'), description: 'Un bon poulet rôti', weightVariable: true, discountRate: DiscountRate::fromRatio(0.2), @@ -85,7 +86,7 @@ describe('Basket and BasketProduct', function (): void { expect($item->incoId->value)->toBe(45); expect($item->orderUnit)->toBe(OrderUnit::PCE); expect($item->slug)->toBe('poulet-roti'); - expect($item->picture)->toBe('images/poulet.jpg'); + expect((string) $item->picture)->toBe('images/poulet.jpg'); expect($item->description)->toBe('Un bon poulet rôti'); expect($item->weightVariable)->toBeTrue(); expect($item->discountRate->basisPoints())->toBe(2000); @@ -116,7 +117,7 @@ describe('Basket and BasketProduct', function (): void { expect($updatedItem->incoId->value)->toBe(45); expect($updatedItem->orderUnit)->toBe(OrderUnit::PCE); expect($updatedItem->slug)->toBe('poulet-roti'); - expect($updatedItem->picture)->toBe('images/poulet.jpg'); + expect((string) $updatedItem->picture)->toBe('images/poulet.jpg'); expect($updatedItem->description)->toBe('Un bon poulet rôti'); expect($updatedItem->weightVariable)->toBeTrue(); expect($updatedItem->discountRate->basisPoints())->toBe(2000); diff --git a/tests/Unit/Domain/Models/Entities/OrderTest.php b/tests/Unit/Domain/Models/Entities/OrderTest.php index c258cc93..9e63be35 100644 --- a/tests/Unit/Domain/Models/Entities/OrderTest.php +++ b/tests/Unit/Domain/Models/Entities/OrderTest.php @@ -36,6 +36,7 @@ use Domain\Models\ValueObjects\ShopperServiceCode; use Domain\Models\ValueObjects\ShopperSiteCode; use Money\Money; use Ramsey\Uuid\Uuid; +use Uwil\Storage\Lib\ValueObjects\StorageFilePath; function makeOrderLine(array $overrides = []): OrderLine { @@ -228,7 +229,7 @@ describe('Order - fromBasket factory', function (): void { incoId: new IncoId(45), orderUnit: OrderUnit::PCE, slug: 'poulet-roti', - picture: 'images/poulet.jpg', + picture: new StorageFilePath('images/poulet.jpg'), description: 'Un bon poulet', weightVariable: false, discountRate: DiscountRate::fromRatio(0.1), diff --git a/tests/Unit/Domain/Models/ValueObjects/OrderLineProductTest.php b/tests/Unit/Domain/Models/ValueObjects/OrderLineProductTest.php index 97800f57..35cc5a57 100644 --- a/tests/Unit/Domain/Models/ValueObjects/OrderLineProductTest.php +++ b/tests/Unit/Domain/Models/ValueObjects/OrderLineProductTest.php @@ -13,6 +13,7 @@ use Domain\Models\ValueObjects\OrderLineProduct; use Domain\Models\ValueObjects\ProductWeight; use Money\Money; use Ramsey\Uuid\Uuid; +use Uwil\Storage\Lib\ValueObjects\StorageFilePath; describe('OrderLineProduct', function (): void { it('can instantiate correctly', function (): void { @@ -32,7 +33,7 @@ describe('OrderLineProduct', function (): void { Money::EUR(900), Money::EUR(2000), TaxRate::TVA_5_5, - 'pic.jpg' + new StorageFilePath('pic.jpg') // WHEN ); // THEN @@ -47,7 +48,7 @@ describe('OrderLineProduct', function (): void { ->and($product->discountedPrice->getAmount())->toBe('900') ->and($product->priceKgTtc->getAmount())->toBe('2000') ->and($product->taxRate)->toBe(TaxRate::TVA_5_5) - ->and($product->picture)->toBe('pic.jpg'); + ->and($product->picture)->toEqual(new StorageFilePath('pic.jpg')); }); it('throws exception if name is empty', function (): void { diff --git a/tests/Unit/Domain/Services/BasketServiceTest.php b/tests/Unit/Domain/Services/BasketServiceTest.php index dbaa524a..a55f7659 100644 --- a/tests/Unit/Domain/Services/BasketServiceTest.php +++ b/tests/Unit/Domain/Services/BasketServiceTest.php @@ -21,6 +21,7 @@ use Domain\Services\BasketService; use Mockery; use Money\Money; use Ramsey\Uuid\Uuid; +use Uwil\Storage\Lib\ValueObjects\StorageFilePath; function makeBasketProduct(array $overrides = []): BasketProduct { @@ -36,7 +37,7 @@ function makeBasketProduct(array $overrides = []): BasketProduct 'incoId' => new IncoId(45), 'orderUnit' => OrderUnit::PCE, 'slug' => 'poulet-roti', - 'picture' => 'images/poulet.jpg', + 'picture' => new StorageFilePath('images/poulet.jpg'), 'description' => 'Un bon poulet', 'weightVariable' => false, 'discountRate' => DiscountRate::fromRatio(0.0), diff --git a/tests/Unit/Domain/Services/OrderServiceTest.php b/tests/Unit/Domain/Services/OrderServiceTest.php index d9e63424..6d211e60 100644 --- a/tests/Unit/Domain/Services/OrderServiceTest.php +++ b/tests/Unit/Domain/Services/OrderServiceTest.php @@ -39,6 +39,7 @@ use Mockery; use Money\Money; use Ramsey\Uuid\Uuid; use Shared\Helpers\UuidHelper; +use Uwil\Storage\Lib\ValueObjects\StorageFilePath; describe('Order Cancellation', function () { it('cancels a validated order successfully', function () { @@ -146,7 +147,7 @@ describe('Order Creation', function () { incoId: new IncoId(45), orderUnit: OrderUnit::PCE, slug: 'poulet-roti', - picture: 'images/poulet.jpg', + picture: new StorageFilePath('images/poulet.jpg'), description: 'Un bon poulet', weightVariable: false, discountRate: DiscountRate::fromRatio(0.1), @@ -234,7 +235,8 @@ describe('Order Creation', function () { expect($product->brand)->toBe(ProductBrand::marie); expect($product->incoId->value)->toBe(45); expect($product->orderUnit)->toBe(OrderUnit::PCE); - expect($product->picture)->toBe('images/poulet.jpg'); + expect($product->picture)->toBeInstanceOf(StorageFilePath::class); + expect($product->picture->value)->toBe('images/poulet.jpg'); }); it('throws exception if basket product has no incoId', function () { diff --git a/tests/Unit/Infra/Adapters/Repositories/SessionBasketRepositoryTest.php b/tests/Unit/Infra/Adapters/Repositories/SessionBasketRepositoryTest.php index 6710ce64..538d8640 100644 --- a/tests/Unit/Infra/Adapters/Repositories/SessionBasketRepositoryTest.php +++ b/tests/Unit/Infra/Adapters/Repositories/SessionBasketRepositoryTest.php @@ -9,114 +9,119 @@ use Infrastructure\Adapters\Repositories\SessionBasketRepository; use Infrastructure\Adapters\Serializers\BasketSerializer; use Ramsey\Uuid\Uuid; -it('returns null if session is empty', function () { - // GIVEN - $basketId = new BasketId(Uuid::uuid7()); - $session = \Mockery::mock(Session::class); - $session->shouldReceive('has')->with('basket_key' . $basketId->value->toString())->andReturn(false); +covers(SessionBasketRepository::class); - $serializer = \Mockery::mock(BasketSerializer::class); +describe('SessionBasketRepository', function () { - $repo = new SessionBasketRepository($session, 'basket_key', $serializer); + it('returns null if session is empty', function () { + // GIVEN + $basketId = new BasketId(Uuid::uuid7()); + $session = \Mockery::mock(Session::class); + $session->shouldReceive('has')->with('basket_key' . $basketId->value->toString())->andReturn(false); - // WHEN - $basket = $repo->find($basketId); + $serializer = \Mockery::mock(BasketSerializer::class); - // THEN - expect($basket)->toBeNull(); -}); - -it('returns deserialized basket if session has data', function () { - // GIVEN - $basketId = new BasketId(Uuid::uuid7()); - $session = \Mockery::mock(Session::class); - $session->shouldReceive('has')->with('basket_key' . $basketId->value->toString())->andReturn(true); - $session->shouldReceive('get')->with('basket_key' . $basketId->value->toString())->andReturn('{"id":"123"}'); - - $serializer = \Mockery::mock(BasketSerializer::class); - $basket = new Basket($basketId, []); - $serializer->shouldReceive('fromArray')->with(['id' => '123'])->andReturn($basket); - - $repo = new SessionBasketRepository($session, 'basket_key', $serializer); - - // WHEN - $result = $repo->find($basketId); - - // THEN - expect($result)->toBe($basket); -}); - -it('returns null if session data is invalid json', function () { - // GIVEN - $basketId = new BasketId(Uuid::uuid7()); - $session = \Mockery::mock(Session::class); - $session->shouldReceive('has')->with('basket_key' . $basketId->value->toString())->andReturn(true); - $session->shouldReceive('get')->with('basket_key' . $basketId->value->toString())->andReturn('invalid-json'); - - $serializer = \Mockery::mock(BasketSerializer::class); - - $repo = new SessionBasketRepository($session, 'basket_key', $serializer); - - // WHEN - $basket = $repo->find($basketId); - - // THEN - expect($basket)->toBeNull(); -}); - -it('returns null if deserialization throws exception', function () { - // GIVEN - $basketId = new BasketId(Uuid::uuid7()); - $session = \Mockery::mock(Session::class); - $session->shouldReceive('has')->with('basket_key' . $basketId->value->toString())->andReturn(true); - $session->shouldReceive('get')->with('basket_key' . $basketId->value->toString())->andReturn('{"id":"123"}'); - - $serializer = \Mockery::mock(BasketSerializer::class); - $serializer->shouldReceive('fromArray')->andThrow(new \Exception('error')); - - $repo = new SessionBasketRepository($session, 'basket_key', $serializer); - - // WHEN - $basket = $repo->find($basketId); - - // THEN - expect($basket)->toBeNull(); -}); - -it('persists basket to session', function () { - // GIVEN - $basketId = new BasketId(Uuid::uuid7()); - $session = \Mockery::mock(Session::class); - - $serializer = \Mockery::mock(BasketSerializer::class); - $basket = new Basket($basketId, []); - $serializer->shouldReceive('toArray')->with($basket)->andReturn(['id' => '123']); - - $session->shouldReceive('put')->with('basket_key' . $basketId->value->toString(), '{"id":"123"}')->once(); - - $repo = new SessionBasketRepository($session, 'basket_key', $serializer); - - // WHEN - $repo->persist($basket); - - // THEN - // Expectations handled by Mockery counts automatically (the `once()` call above) -}); - -it('deletes basket from session', function () { - // GIVEN - $basketId = new BasketId(Uuid::uuid7()); - $session = \Mockery::mock(Session::class); - $session->shouldReceive('forget')->with('basket_key' . $basketId->value->toString())->once(); - - $serializer = \Mockery::mock(BasketSerializer::class); - - $repo = new SessionBasketRepository($session, 'basket_key', $serializer); - $basket = new Basket($basketId, []); - - // WHEN - $repo->delete($basket); - - // THEN - // Expectations handled by Mockery automatically + $repo = new SessionBasketRepository($session, 'basket_key', $serializer); + + // WHEN + $basket = $repo->find($basketId); + + // THEN + expect($basket)->toBeNull(); + }); + + it('returns deserialized basket if session has data', function () { + // GIVEN + $basketId = new BasketId(Uuid::uuid7()); + $session = \Mockery::mock(Session::class); + $session->shouldReceive('has')->with('basket_key' . $basketId->value->toString())->andReturn(true); + $session->shouldReceive('get')->with('basket_key' . $basketId->value->toString())->andReturn('{"id":"123"}'); + + $serializer = \Mockery::mock(BasketSerializer::class); + $basket = new Basket($basketId, []); + $serializer->shouldReceive('fromArray')->with(['id' => '123'])->andReturn($basket); + + $repo = new SessionBasketRepository($session, 'basket_key', $serializer); + + // WHEN + $result = $repo->find($basketId); + + // THEN + expect($result)->toBe($basket); + }); + + it('returns null if session data is invalid json', function () { + // GIVEN + $basketId = new BasketId(Uuid::uuid7()); + $session = \Mockery::mock(Session::class); + $session->shouldReceive('has')->with('basket_key' . $basketId->value->toString())->andReturn(true); + $session->shouldReceive('get')->with('basket_key' . $basketId->value->toString())->andReturn('invalid-json'); + + $serializer = \Mockery::mock(BasketSerializer::class); + + $repo = new SessionBasketRepository($session, 'basket_key', $serializer); + + // WHEN + $basket = $repo->find($basketId); + + // THEN + expect($basket)->toBeNull(); + }); + + it('returns null if deserialization throws exception', function () { + // GIVEN + $basketId = new BasketId(Uuid::uuid7()); + $session = \Mockery::mock(Session::class); + $session->shouldReceive('has')->with('basket_key' . $basketId->value->toString())->andReturn(true); + $session->shouldReceive('get')->with('basket_key' . $basketId->value->toString())->andReturn('{"id":"123"}'); + + $serializer = \Mockery::mock(BasketSerializer::class); + $serializer->shouldReceive('fromArray')->andThrow(new \Exception('error')); + + $repo = new SessionBasketRepository($session, 'basket_key', $serializer); + + // WHEN + $basket = $repo->find($basketId); + + // THEN + expect($basket)->toBeNull(); + }); + + it('persists basket to session', function () { + // GIVEN + $basketId = new BasketId(Uuid::uuid7()); + $session = \Mockery::mock(Session::class); + + $serializer = \Mockery::mock(BasketSerializer::class); + $basket = new Basket($basketId, []); + $serializer->shouldReceive('toArray')->with($basket)->andReturn(['id' => '123']); + + $session->shouldReceive('put')->with('basket_key' . $basketId->value->toString(), '{"id":"123"}')->once(); + + $repo = new SessionBasketRepository($session, 'basket_key', $serializer); + + // WHEN + $repo->persist($basket); + + // THEN + // Expectations handled by Mockery counts automatically (the `once()` call above) + }); + + it('deletes basket from session', function () { + // GIVEN + $basketId = new BasketId(Uuid::uuid7()); + $session = \Mockery::mock(Session::class); + $session->shouldReceive('forget')->with('basket_key' . $basketId->value->toString())->once(); + + $serializer = \Mockery::mock(BasketSerializer::class); + + $repo = new SessionBasketRepository($session, 'basket_key', $serializer); + $basket = new Basket($basketId, []); + + // WHEN + $repo->delete($basket); + + // THEN + // Expectations handled by Mockery automatically + }); }); diff --git a/tests/Unit/Infra/Adapters/Serializers/BasketSerializerTest.php b/tests/Unit/Infra/Adapters/Serializers/BasketSerializerTest.php index ca9eb2b2..65aadb0d 100644 --- a/tests/Unit/Infra/Adapters/Serializers/BasketSerializerTest.php +++ b/tests/Unit/Infra/Adapters/Serializers/BasketSerializerTest.php @@ -15,6 +15,7 @@ use Infrastructure\Adapters\Serializers\BasketSerializer; use Money\Currency; use Money\Money; use Ramsey\Uuid\Uuid; +use Uwil\Storage\Lib\ValueObjects\StorageFilePath; it('serializes and deserializes basket correctly', function () { describe('BasketSerializer', function () { @@ -36,7 +37,7 @@ it('serializes and deserializes basket correctly', function () { incoId: new IncoId(12345), orderUnit: OrderUnit::PCE, slug: 'product-1', - picture: 'pic.png', + picture: new StorageFilePath('pic.png'), description: 'desc', weightVariable: true, discountRate: DiscountRate::fromRatio(0.1),