refactor(storage): migrate media models, basket value objects and CQS actions to S3

This commit is contained in:
Jérémy Munsch 2026-11-14 16:06:12 +01:00
parent 0684215511
commit cfba7f4756
No known key found for this signature in database
GPG key ID: 2AAECDA6B7330F91
58 changed files with 1002 additions and 329 deletions

View file

@ -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<OrderLineProduct,OrderLineProduct>
@ -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);
}
}

View file

@ -0,0 +1,59 @@
<?php
declare(strict_types=1);
namespace App\Cqs\Actions\Contact;
use App\Contracts\Action;
use App\Contracts\ActionInput;
use App\Lib\PrivateS3Disk;
use Domain\Models\ValueObjects\AttachedFile;
use Domain\Models\ValueObjects\ContactFormData;
use Illuminate\Http\UploadedFile;
use Uwil\Storage\Contracts\StorageService;
use Webmozart\Assert\Assert;
/**
* @implements \App\Contracts\Action<
* \App\Cqs\Actions\Contact\SubmitContactFormInput,
* \Domain\Models\ValueObjects\ContactFormData
* >
*/
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,
);
}
}

View file

@ -0,0 +1,32 @@
<?php
declare(strict_types=1);
namespace App\Cqs\Actions\Contact;
use App\Contracts\ActionInput;
use Illuminate\Http\UploadedFile;
use Webmozart\Assert\Assert;
final readonly class SubmitContactFormInput implements ActionInput
{
public function __construct(
public string $lastName,
public string $firstName,
public string $email,
public string $subject,
public string $message,
public ?string $orderRef = null,
public ?UploadedFile $file = null,
) {
Assert::stringNotEmpty(trim($this->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));
}
}
}

View file

@ -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);
}
}

View file

@ -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 = [],

View file

@ -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();
}
}

View file

@ -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,
) {
}
}

View file

@ -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);
}
}

View file

@ -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<string> $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 = [],

View file

@ -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);
}
}

View file

@ -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,
) {

View file

@ -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;
}
}

View file

@ -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);
}
}

View file

@ -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,
) {

View file

@ -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);
}
}

View file

@ -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,

View file

@ -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();
}
}

View file

@ -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);
}
}

View file

@ -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,

View file

@ -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

View file

@ -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,

View file

@ -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,

View file

@ -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));

View file

@ -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(),

View file

@ -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),
];

View file

@ -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,

View file

@ -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',
];
}
}

View file

@ -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',

View file

@ -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,

View file

@ -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,

View file

@ -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');

View file

@ -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,

View file

@ -46,7 +46,7 @@
<td>{{ Str::limit($product->name, 45) }}</td>
<td class="d-none d-md-table-cell">
@if (!empty($product->picture))
<img class="img-fluid mw-5" src="{{ asset($product->picture) }}" title="{{ $product->picture_title }}"
<img class="img-fluid mw-5" src="{{ $product->picture }}" title="{{ $product->picture_title }}"
alt="{{ $product->picture_alt }}">
@else
<span>{{ __('No Content') }}</span>
@ -54,7 +54,7 @@
</td>
<td class="d-none d-md-table-cell">
@if (!empty($product->picture_large))
<img class="img-fluid mw-5" src="{{ asset($product->picture_large) }}" title="{{ $product->picture_large_title }}"
<img class="img-fluid mw-5" src="{{ $product->picture_large }}" title="{{ $product->picture_large_title }}"
alt="{{ $product->picture_large_alt }}">
@else
<span>{{ __('No Content') }}</span>

View file

@ -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 @@
<tr>
<td>{{ $range->name }}</td>
<td class="d-none d-md-table-cell">
<img class="img-fluid mw-5" src="{{ asset($range->picture) }}" title="{{ $range->picture_title }}" alt="{{ $range->picture_alt }}">
<img class="img-fluid mw-5" src="{{ $range->picture }}" title="{{ $range->picture_title }}" alt="{{ $range->picture_alt }}">
</td>
@include('bo.modules.change-order', [
'route' => 'bo.ranges.change-order',

View file

@ -26,7 +26,7 @@
<tr>
<td>{{ $slide->title }}</td>
<td>
<img src="{{ asset($slide->picture) }}" alt="{{ $slide->title }}" height="50px">
<img src="{{ $slide->picture }}" alt="{{ $slide->title }}" height="50px">
</td>
<td><a href="{{ $slide->link }}" target="_slide">{{ $slide->link_label }}</a></td>
<td class="text-center align-middle">

View file

@ -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']])

View file

@ -4,7 +4,7 @@
<div class="card mb-3">
<div class="row g-0">
<div class="col-md-4 d-flex align-items-center justify-center">
<img class="img-fluid rounded-start" data-bs-toggle="tooltip" src="{{ asset($range->picture) }}" title="{{ $range->picture_title }}"
<img class="img-fluid rounded-start" data-bs-toggle="tooltip" src="{{ $range->picture }}" title="{{ $range->picture_title }}"
alt="{{ $range->picture_alt }}">
</div>
<div class="col-md-8 d-flex align-items-center">

View file

@ -26,7 +26,7 @@
@if (!empty($slide->picture))
<div
class="col-12 col-xl-8 order-xl-2 d-flex justify-content-center justify-content-xl-start align-items-center pb-xl-0 px-xl-4 order-1 px-0 pb-3">
<img class="img-fluid object-fit-contain w-100" data-bs-toggle="tooltip" src="{{ asset($slide->picture) }}"
<img class="img-fluid object-fit-contain w-100" data-bs-toggle="tooltip" src="{{ $slide->picture }}"
title="{{ $slide->picture_title }}" alt="{{ $slide->picture_alt ?: $slide->title }}">
</div>
@endif

View file

@ -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

View file

@ -0,0 +1,94 @@
<?php
declare(strict_types=1);
use App\Contracts\ActionInput;
use App\Cqs\Actions\Contact\SubmitContactForm;
use App\Cqs\Actions\Contact\SubmitContactFormInput;
use App\Lib\PrivateS3Disk;
use Domain\Models\ValueObjects\AttachedFile;
use Domain\Models\ValueObjects\ContactFormData;
use Illuminate\Http\UploadedFile;
use Uwil\Storage\Contracts\StorageService;
use Uwil\Storage\Lib\ValueObjects\DiskName;
use Uwil\Storage\Lib\ValueObjects\StorageFilePath;
describe('SubmitContactForm action', function (): void {
it('builds ContactFormData without touching storage when no file is provided', function (): void {
// GIVEN
$storage = \Mockery::mock(StorageService::class);
$storage->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);
});
});

View file

@ -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: '<p>Une superbe gamme</p>',
@ -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
{
};

View file

@ -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
{
};

View file

@ -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
{
};

View file

@ -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
{
};

View file

@ -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 = '<p>Contenu</p>';
$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 = '<p>Contenu</p>';
$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);
});
});

View file

@ -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 = '<p>Ancien texte</p>';
$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('<p>Texte mis à jour</p>');
$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 = '<p>Ancien texte</p>';
$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: '<p>Texte avec image</p>',
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
{
};

View file

@ -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('<p>Découvrez notre nouvelle collection</p>')
->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 = '<p>Texte uniquement</p>';
$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');
});
});

View file

@ -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

View file

@ -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),

View file

@ -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);
});

View file

@ -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');
});
});

View file

@ -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);

View file

@ -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),

View file

@ -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 {

View file

@ -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),

View file

@ -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 () {

View file

@ -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
});
});

View file

@ -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),