feat(uploads): enforce MIME/extension validation and display upload rules on BO/FO forms

This commit is contained in:
Jérémy Munsch 2026-11-14 16:06:34 +01:00
parent 5d715094d1
commit 3af75ac974
No known key found for this signature in database
GPG key ID: 2AAECDA6B7330F91
23 changed files with 718 additions and 277 deletions

View file

@ -5,7 +5,7 @@ declare(strict_types=1);
namespace App\Http\Requests\Bo\Products;
use App\Cqs\Actions\Products\CreateProductInput;
use App\Traits\Requests\HasPicture;
use App\Rules\FileExtensionMatchesMimeType;
use Carbon\CarbonImmutable;
use Domain\Enums\ProductBrand;
use Domain\Enums\SellUnit;
@ -13,18 +13,35 @@ use Domain\Enums\TaxRate;
use Domain\Enums\Units\InvoicingUnit;
use Domain\Enums\Units\OrderUnit;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Date;
use Illuminate\Validation\Rule;
use Illuminate\Validation\Rules\Enum;
use Infrastructure\Adapters\Services\AppAdminAuthService;
use Money\Currency;
use Money\Money;
use Webmozart\Assert\Assert;
class StoreProductRequest extends FormRequest
{
use HasPicture;
public const int MAX_FILE_SIZE_KB = 5120;
public const int PICTURE_WIDTH = 200;
public const int PICTURE_HEIGHT = 200;
public const int PICTURE_LARGE_WIDTH = 500;
public const int PICTURE_LARGE_HEIGHT = 500;
/** @var list<string> */
public const array ALLOWED_EXTENSIONS = ['jpg', 'jpeg', 'png'];
/** @var list<string> */
public const array ALLOWED_MIME_TYPES = ['image/jpeg', 'image/png'];
public function __construct(
private readonly AppAdminAuthService $authService
private readonly AppAdminAuthService $authService,
) {
}
@ -56,9 +73,14 @@ class StoreProductRequest extends FormRequest
/** @return list<string> */
public function getAssociatedProductsIds(): array
{
$filtered = array_filter(
$this->array('associated_products'),
fn ($id) => is_string($id) || is_int($id)
);
return array_values(array_map(
fn ($id) => (string) $id,
$this->array('associated_products')
$filtered
));
}
@ -82,73 +104,100 @@ class StoreProductRequest extends FormRequest
orderableEnd: $this->filled('orderable_end') ? CarbonImmutable::parse($this->string('orderable_end')->value()) : null,
star: $this->boolean('star'),
status: $this->boolean('status'),
picture: $this->file('picture') ?? $this->input('picture'),
picture: $this->hasFile('picture') ? $this->file('picture') : null,
pictureAlt: $this->filled('picture_alt') ? $this->string('picture_alt')->value() : null,
pictureTitle: $this->filled('picture_title') ? $this->string('picture_title')->value() : null,
pictureLarge: $this->file('picture_large') ?? $this->input('picture_large'),
pictureLarge: $this->hasFile('picture_large') ? $this->file('picture_large') : null,
pictureLargeAlt: $this->filled('picture_large_alt') ? $this->string('picture_large_alt')->value() : null,
pictureLargeTitle: $this->filled('picture_large_title') ? $this->string('picture_large_title')->value() : null,
tags: $this->array('tags'),
tags: $this->getTags(),
associatedProductsIds: $this->getAssociatedProductsIds(),
);
}
/** @return array<string,mixed> */
/** @return array{ id: string, label: string }[] */
protected function getTags(): array
{
$tags = $this->array('tags');
Assert::allIsArray($tags);
return array_map(
static function (array $tag): array {
$id = Arr::get($tag, 'id');
Assert::scalar($id);
return [
'id' => (string) $id,
'label' => Arr::string($tag, 'label'),
];
},
$tags
);
}
/** @return array<string, \Illuminate\Validation\Rule|array<mixed>|string> */
public function rules(): array
{
$maxWidth = 200;
$maxHeight = 200;
$maxWidthLarge = 500;
$maxHeightLarge = 500;
return [
'name' => ['required', 'string', 'min:3', 'max:255'],
'brand' => ['sometimes', 'nullable', 'string', 'min:3', 'max:255'],
'short_description' => ['required', 'string', 'min:15', 'max:100'],
'description' => ['required', 'string', 'min:15'],
'price' => ['required', 'min:0', 'numeric'],
'invoicing_unit' => ['required', new Enum(InvoicingUnit::class)],
'stock' => ['required', 'integer', 'min:0'],
'weight' => ['sometimes', 'nullable', 'numeric'],
return array_merge(
[
'name' => ['required', 'string', 'min:3', 'max:255'],
'brand' => ['sometimes', 'nullable', 'string', 'min:3', 'max:255'],
'short_description' => ['required', 'string', 'min:15', 'max:100'],
'description' => ['required', 'string', 'min:15'],
'price' => ['required', 'min:0', 'numeric'],
'invoicing_unit' => ['required', new Enum(InvoicingUnit::class)],
'stock' => ['required', 'integer', 'min:0'],
'weight' => ['sometimes', 'nullable', 'numeric'],
'orderable_start' => ['nullable', 'date_format:Y-m-d\TH:i'],
'orderable_end' => ['nullable', 'date_format:Y-m-d\TH:i', 'after:orderable_start'],
'client_timezone' => ['required', 'timezone'],
'orderable_start' => ['nullable', 'date_format:Y-m-d\TH:i'],
'orderable_end' => ['nullable', 'date_format:Y-m-d\TH:i', 'after:orderable_start'],
'client_timezone' => ['required', 'timezone'],
'range_id' => ['required', 'integer', 'exists:ranges,id'],
'range_id' => ['required', 'integer', 'exists:ranges,id'],
'tags' => ['present', 'array', 'min:0'],
'tags.*.id' => ['required', 'exists:tags,id'],
'tags.*.label' => ['required', 'string', 'min:2', 'max:45'],
'star' => ['required', 'boolean'],
'status' => ['required', 'boolean'],
'weight_variable' => ['required', 'boolean'],
'tags' => ['present', 'array'],
'tags.*.id' => ['sometimes', 'exists:tags,id'],
'tags.*.label' => ['required', 'string', 'min:2', 'max:45'],
'star' => ['required', 'boolean'],
'status' => ['required', 'boolean'],
'weight_variable' => ['required', 'boolean'],
'sell_unit' => ['required', new Enum(SellUnit::class)],
'order_unit' => ['required', new Enum(OrderUnit::class)],
'tax_rate' => ['required', new Enum(TaxRate::class)],
'sell_unit' => ['required', new Enum(SellUnit::class)],
'order_unit' => ['required', new Enum(OrderUnit::class)],
'tax_rate' => ['required', new Enum(TaxRate::class)],
'associated_products' => ['present', 'array'],
'associated_products.*' => ['string', 'exists:products,id'],
'picture' => [
Rule::imageFile()
->extensions(self::ALLOWED_EXTENSIONS)
->rules([
'mimetypes:' . implode(',', self::ALLOWED_MIME_TYPES),
new FileExtensionMatchesMimeType(),
])
->max(self::MAX_FILE_SIZE_KB)
->dimensions(
Rule::dimensions()
->width(static::PICTURE_WIDTH)
->height(static::PICTURE_HEIGHT)
),
],
$this->pictureRules(
'picture',
$maxWidth,
$maxHeight,
$maxWidth,
$maxHeight,
true
),
$this->pictureRules(
'picture_large',
$maxWidthLarge,
$maxHeightLarge,
$maxWidthLarge,
$maxHeightLarge,
true
)
);
'picture_large' => [
Rule::imageFile()
->extensions(self::ALLOWED_EXTENSIONS)
->rules([
'mimetypes:' . implode(',', self::ALLOWED_MIME_TYPES),
new FileExtensionMatchesMimeType(),
])
->max(self::MAX_FILE_SIZE_KB)
->dimensions(
Rule::dimensions()
->width(static::PICTURE_LARGE_WIDTH)
->height(static::PICTURE_LARGE_HEIGHT)
),
],
'associated_products' => ['present', 'array'],
'associated_products.*' => ['string', 'exists:products,id'],
];
}
#[\Override]

View file

@ -5,20 +5,20 @@ declare(strict_types=1);
namespace App\Http\Requests\Bo\Products;
use App\Cqs\Actions\Products\UpdateProductInput;
use App\Models\Product;
use Carbon\CarbonImmutable;
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;
class UpdateProductRequest extends StoreProductRequest
{
public function toUpdateProductInput(Product $product): UpdateProductInput
public function toUpdateProductInput(ProductId $productId): UpdateProductInput
{
return new UpdateProductInput(
product: $product,
productId: $productId,
name: $this->string('name')->value(),
shortDescription: $this->string('short_description')->value(),
description: $this->string('description')->value(),
@ -36,13 +36,13 @@ class UpdateProductRequest extends StoreProductRequest
orderableEnd: $this->filled('orderable_end') ? CarbonImmutable::parse($this->string('orderable_end')->value()) : null,
star: $this->boolean('star'),
status: $this->boolean('status'),
picture: $this->file('picture') ?? $this->input('picture'),
picture: $this->hasFile('picture') ? $this->file('picture') : null,
pictureAlt: $this->filled('picture_alt') ? $this->string('picture_alt')->value() : null,
pictureTitle: $this->filled('picture_title') ? $this->string('picture_title')->value() : null,
pictureLarge: $this->file('picture_large') ?? $this->input('picture_large'),
pictureLarge: $this->hasFile('picture_large') ? $this->file('picture_large') : null,
pictureLargeAlt: $this->filled('picture_large_alt') ? $this->string('picture_large_alt')->value() : null,
pictureLargeTitle: $this->filled('picture_large_title') ? $this->string('picture_large_title')->value() : null,
tags: $this->array('tags'),
tags: $this->getTags(),
associatedProductsIds: $this->getAssociatedProductsIds(),
);
}

View file

@ -5,17 +5,28 @@ declare(strict_types=1);
namespace App\Http\Requests\Bo\Ranges;
use App\Cqs\Actions\Ranges\CreateRangeInput;
use App\Traits\Requests\HasPicture;
use App\Rules\FileExtensionMatchesMimeType;
use Domain\Models\ValueObjects\PictureMetadata;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;
use Infrastructure\Adapters\Services\AppAdminAuthService;
class StoreRangeRequest extends FormRequest
{
use HasPicture;
public const int MAX_FILE_SIZE_KB = 5120;
public const int PICTURE_WIDTH = 500;
public const int PICTURE_HEIGHT = 500;
/** @var list<string> */
public const array ALLOWED_EXTENSIONS = ['jpg', 'jpeg', 'png'];
/** @var list<string> */
public const array ALLOWED_MIME_TYPES = ['image/jpeg', 'image/png'];
public function __construct(
private readonly AppAdminAuthService $authService
private readonly AppAdminAuthService $authService,
) {
}
@ -32,29 +43,30 @@ class StoreRangeRequest extends FormRequest
]);
}
/** @return array<string,mixed> */
/** @return array<string, \Illuminate\Validation\Rule|array<mixed>|string> */
public function rules(): array
{
$maxWidth = 500;
$maxHeight = 500;
return array_merge(
[
'name' => ['required', 'string', 'min:2', 'max:45'],
'description' => ['nullable', 'string', 'min:2'],
'picture_alt' => ['required_with:picture', 'string', 'min:4', 'max:75'],
'picture_title' => ['required_with:picture', 'string', 'min:4', 'max:75'],
'status' => ['present', 'boolean:strict'],
return [
'name' => ['required', 'string', 'min:2', 'max:45'],
'description' => ['nullable', 'string', 'min:2'],
'picture_alt' => ['required_with:picture', 'string', 'min:4', 'max:75'],
'picture_title' => ['required_with:picture', 'string', 'min:4', 'max:75'],
'picture' => [
Rule::imageFile()
->extensions(self::ALLOWED_EXTENSIONS)
->rules([
'mimetypes:' . implode(',', self::ALLOWED_MIME_TYPES),
new FileExtensionMatchesMimeType(),
])
->max(self::MAX_FILE_SIZE_KB)
->dimensions(
Rule::dimensions()
->width(static::PICTURE_WIDTH)
->height(static::PICTURE_HEIGHT)
),
],
$this->pictureRules(
'picture',
$maxWidth,
$maxHeight,
$maxWidth,
$maxHeight,
true
)
);
'status' => ['present', 'boolean:strict'],
];
}
#[\Override]
@ -78,7 +90,7 @@ class StoreRangeRequest extends FormRequest
return new CreateRangeInput(
name: $this->string('name')->value(),
description: $this->filled('description') ? $this->string('description')->value() : null,
picture: $this->file('picture'),
picture: $this->hasFile('picture') ? $this->file('picture') : null,
pictureMetadata: new PictureMetadata(
alt: $pictureAlt,
title: $pictureTitle,

View file

@ -19,7 +19,7 @@ class UpdateRangeRequest extends StoreRangeRequest
range: $range,
name: $this->string('name')->value(),
description: $this->filled('description') ? $this->string('description')->value() : null,
picture: $this->file('picture'),
picture: $this->hasFile('picture') ? $this->file('picture') : null,
pictureMetadata: new PictureMetadata(
alt: $pictureAlt,
title: $pictureTitle,

View file

@ -5,19 +5,30 @@ declare(strict_types=1);
namespace App\Http\Requests\Bo\Slides;
use App\Cqs\Actions\Slides\CreateSlideInput;
use App\Traits\Requests\HasPicture;
use App\Rules\FileExtensionMatchesMimeType;
use Domain\Models\ValueObjects\DatePeriod;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Date;
use Illuminate\Support\Stringable;
use Illuminate\Validation\Rule;
use Infrastructure\Adapters\Services\AppAdminAuthService;
class StoreSlideRequest extends FormRequest
{
use HasPicture;
public const int MAX_FILE_SIZE_KB = 5120;
public const int PICTURE_WIDTH = 1440;
public const int PICTURE_HEIGHT = 960;
/** @var list<string> */
public const array ALLOWED_EXTENSIONS = ['jpg', 'jpeg', 'png'];
/** @var list<string> */
public const array ALLOWED_MIME_TYPES = ['image/jpeg', 'image/png'];
public function __construct(
private readonly AppAdminAuthService $authService
private readonly AppAdminAuthService $authService,
) {
}
@ -26,18 +37,6 @@ class StoreSlideRequest extends FormRequest
return $this->authService->check();
}
public function resolvePicture(): UploadedFile | string | null
{
$file = $this->file('picture');
if ($file instanceof UploadedFile) {
return $file;
}
return $this->has('picture') && is_string($this->input('picture'))
? $this->input('picture')
: null;
}
public function toDatePeriod(): DatePeriod
{
return new DatePeriod(
@ -51,7 +50,7 @@ class StoreSlideRequest extends FormRequest
return new CreateSlideInput(
title: $this->string('title')->value(),
text: $this->filled('text') ? $this->string('text')->value() : null,
picture: $this->resolvePicture(),
picture: $this->hasFile('picture') ? $this->file('picture') : null,
pictureAlt: $this->filled('picture_alt') ? $this->string('picture_alt')->value() : null,
pictureTitle: $this->filled('picture_title') ? $this->string('picture_title')->value() : null,
link: $this->filled('link') ? $this->string('link')->value() : null,
@ -65,8 +64,12 @@ class StoreSlideRequest extends FormRequest
#[\Override]
protected function prepareForValidation(): void
{
$text = $this->input('text');
if (is_string($text) && trim(html_entity_decode(strip_tags($text), ENT_QUOTES | ENT_HTML5, 'UTF-8')) === '') {
$text = $this->string('text')->value();
$trimmedText = $this->string('text')
->pipe(fn (Stringable $text) => html_entity_decode(strip_tags((string) $text), ENT_QUOTES | ENT_HTML5, 'UTF-8'))
->trim()
->toString();
if ($trimmedText === '') {
$text = null;
}
@ -77,39 +80,40 @@ class StoreSlideRequest extends FormRequest
]);
}
/** @return array<string,mixed> */
/** @return array<string, \Illuminate\Validation\Rule|array<mixed>|string> */
public function rules(): array
{
$maxWidth = 1440;
$maxHeight = 960;
return array_merge(
[
'title' => ['required', 'string', 'min:4', 'max:75'],
'picture_alt' => ['required_with:picture', 'string', 'min:4', 'max:75'],
'picture_title' => ['required_with:picture', 'string', 'min:4', 'max:75'],
'text' => ['nullable', 'required_without:picture', 'string', 'min:4'],
'link' => ['nullable', 'url:https', 'max:255'],
'link_label' => ['nullable', 'string', 'min:5', 'max:255'],
'link_new_tab' => ['present', 'boolean:strict'],
'connected' => ['present', 'boolean:strict'],
'date_start' => ['nullable', 'date_format:Y-m-d\TH:i'],
'date_end' => ['nullable', 'date_format:Y-m-d\TH:i', 'after:date_start'],
'client_timezone' => ['required', 'timezone'],
return [
'title' => ['required', 'string', 'min:4', 'max:75'],
'picture_alt' => ['required_with:picture', 'string', 'min:4', 'max:75'],
'picture_title' => ['required_with:picture', 'string', 'min:4', 'max:75'],
'picture' => [
Rule::imageFile()
->extensions(self::ALLOWED_EXTENSIONS)
->rules([
'mimetypes:' . implode(',', self::ALLOWED_MIME_TYPES),
new FileExtensionMatchesMimeType(),
])
->max(self::MAX_FILE_SIZE_KB)
->dimensions(
Rule::dimensions()
->width(static::PICTURE_WIDTH)
->height(static::PICTURE_HEIGHT)
),
],
$this->pictureRules(
'picture',
$maxWidth,
$maxHeight,
$maxWidth,
$maxHeight,
true
)
);
'text' => ['nullable', 'required_without:picture', 'string', 'min:4'],
'link' => ['nullable', 'url:https', 'max:255'],
'link_label' => ['nullable', 'string', 'min:5', 'max:255'],
'link_new_tab' => ['present', 'boolean:strict'],
'connected' => ['present', 'boolean:strict'],
'date_start' => ['nullable', 'date_format:Y-m-d\TH:i'],
'date_end' => ['nullable', 'date_format:Y-m-d\TH:i', 'after:date_start'],
'client_timezone' => ['required', 'timezone'],
];
}
#[\Override]
protected function passedValidation()
protected function passedValidation(): void
{
if ($this->filled('date_start')) {
$inputValue = Date::createFromFormat(

View file

@ -15,7 +15,7 @@ class UpdateSlideRequest extends StoreSlideRequest
slide: $slide,
title: $this->string('title')->value(),
text: $this->filled('text') ? $this->string('text')->value() : null,
picture: $this->resolvePicture(),
picture: $this->hasFile('picture') ? $this->file('picture') : null,
pictureAlt: $this->filled('picture_alt') ? $this->string('picture_alt')->value() : null,
pictureTitle: $this->filled('picture_title') ? $this->string('picture_title')->value() : null,
link: $this->filled('link') ? $this->string('link')->value() : null,

View file

@ -4,14 +4,22 @@ declare(strict_types=1);
namespace App\Http\Requests\Fo;
use Domain\Models\ValueObjects\AttachedFile;
use Domain\Models\ValueObjects\ContactFormData;
use App\Cqs\Actions\Contact\SubmitContactFormInput;
use App\Rules\FileExtensionMatchesMimeType;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Support\Facades\Storage;
use Illuminate\Http\UploadedFile;
use Illuminate\Validation\Rule;
class ContactFormRequest extends FormRequest
{
public const int MAX_FILE_SIZE_KB = 5120;
/** @var list<string> */
public const array ALLOWED_EXTENSIONS = ['jpg', 'jpeg', 'png', 'pdf'];
/** @var list<string> */
public const array ALLOWED_MIME_TYPES = ['image/jpeg', 'image/png', 'application/pdf'];
/** @return array<string,mixed> */
public function rules(): array
{
@ -31,8 +39,10 @@ class ContactFormRequest extends FormRequest
'file' => [
'nullable',
Rule::file()
->max(5120)
->types(['jpg', 'jpeg', 'png', 'pdf']),
->types([...self::ALLOWED_EXTENSIONS, ...self::ALLOWED_MIME_TYPES])
->extensions(self::ALLOWED_EXTENSIONS)
->rules([new FileExtensionMatchesMimeType()])
->max(self::MAX_FILE_SIZE_KB),
],
'ok_cgv' => ['accepted'],
];
@ -49,34 +59,20 @@ class ContactFormRequest extends FormRequest
];
}
public function toValueObject(): ContactFormData
public function toSubmitContactFormInput(): SubmitContactFormInput
{
$attachedFile = null;
$file = $this->file('file');
$uploadedFile = $file instanceof UploadedFile ? $file : null;
$orderRef = $this->input('order_ref');
if ($this->hasFile('file') && $this->file('file')->isValid()) {
$uploadedFile = $this->file('file');
$storedPath = $uploadedFile->store('contact-attachments', 'private');
if ($storedPath !== false) {
$fullPath = Storage::disk('private')->path($storedPath);
$attachedFile = new AttachedFile(
path: $fullPath,
originalName: $uploadedFile->getClientOriginalName(),
mimeType: $uploadedFile->getMimeType() ?? 'application/octet-stream',
);
}
}
return new ContactFormData(
return new SubmitContactFormInput(
lastName: $this->string('last_name')->value(),
firstName: $this->string('first_name')->value(),
email: $this->string('email')->value(),
subject: $this->string('subject')->value(),
message: $this->string('message')->value(),
orderRef: empty($this->input('order_ref')) ?
null : $this->string('order_ref')->value(),
file: $attachedFile,
orderRef: empty($orderRef) ? null : $this->string('order_ref')->value(),
file: $uploadedFile,
);
}

View file

@ -46,4 +46,53 @@ final class RequestHelper
{
return new Uri($request->fullUrl());
}
/**
* Build configuration array for the Back-Office image input Vue component.
*
* @param list<string> $allowedExtensions
* @return array{
* name: string,
* single: bool,
* width: int,
* height: int,
* preview: bool,
* accept: string,
* helper: string,
* value: string,
* }
*/
public static function imageInputConfig(
string $name,
int $width,
int $height,
int $maxSizeKb,
array $allowedExtensions,
string $value = '',
): array {
$maxSizeMb = round($maxSizeKb / 1024, 1);
$formattedSize = fmod($maxSizeMb, 1.0) === 0.0
? (string) (int) $maxSizeMb
: (string) $maxSizeMb;
$prefixedExtensions = array_map(
static fn (string $ext): string => '.' . ltrim($ext, '.'),
$allowedExtensions,
);
return [
'name' => $name,
'single' => true,
'width' => $width,
'height' => $height,
'preview' => false,
'accept' => implode(',', $prefixedExtensions),
'helper' => __('Allowed extensions: :extensions (:maxSize MB max). Required dimensions: :width px by :height px', [
'extensions' => implode(', ', $prefixedExtensions),
'maxSize' => $formattedSize,
'width' => $width,
'height' => $height,
]),
'value' => $value,
];
}
}

View file

@ -0,0 +1,42 @@
<?php
declare(strict_types=1);
namespace App\Rules;
use Illuminate\Contracts\Validation\ValidationRule;
use Illuminate\Http\UploadedFile;
use Symfony\Component\Mime\MimeTypes;
final readonly class FileExtensionMatchesMimeType implements ValidationRule
{
/**
* @param \Closure(string, ?string=):\Illuminate\Translation\PotentiallyTranslatedString $fail
*/
#[\Override]
public function validate(string $attribute, mixed $value, \Closure $fail): void
{
if (! $value instanceof UploadedFile || ! $value->isValid()) {
return;
}
$extension = strtolower($value->getClientOriginalExtension());
$detectedMime = strtolower((string) $value->getMimeType());
if ($extension === '' || $detectedMime === '') {
return;
}
$expectedMimes = array_map(
strtolower(...),
MimeTypes::getDefault()->getMimeTypes($extension),
);
if ($expectedMimes !== [] && ! in_array($detectedMime, $expectedMimes, true)) {
$fail(trans('validation.mimes', [
'attribute' => $attribute,
'values' => $extension,
]));
}
}
}

View file

@ -1,4 +1,5 @@
{
"(:extensions, :maxSize MB max)": "(:extensions, :maxSize MB max)",
"(and :count more error)": "(and :count more error)",
"(and :count more errors)": "(and :count more error)|(and :count more errors)|(and :count more errors)",
"- at least one lowercase letter": "- at least one lowercase letter",
@ -50,6 +51,7 @@
"All products have been selected.": "All products have been selected.",
"All rights reserved.": "All rights reserved.",
"Allergens": "Allergens",
"Allowed extensions: :extensions (:maxSize MB max). Required dimensions: :width px by :height px": "Allowed extensions: :extensions (:maxSize MB max). Required dimensions: :width px by :height px",
"Already registered?": "Already registered?",
"Already Reported": "Already Reported",
"An account is already associated with this email address": "An account is already associated with this email address",
@ -357,9 +359,6 @@
"Item removed from basket": "Item removed from basket",
"jj": "jj",
"joinedfile": "joinedfile",
"JPEG/PNG, 2MB max.": "JPEG/PNG, 2MB max.",
"JPEG/PNG, 2MB max. Recommended dimensions: :width px by :height px": "JPEG/PNG, 2MB max. Recommended dimensions: :width px by :height px",
"JPEG/PNG, 2Mo max.": "JPEG/PNG, 2Mo max.",
"Kcal": "Kcal",
"Keyword information": "Keyword information",
"Keywords associated with the product": "Keywords associated with the product",

View file

@ -1,4 +1,5 @@
{
"(:extensions, :maxSize MB max)": "(:extensions, :maxSize Mo max)",
"(and :count more error)": "(et :count erreur en plus)",
"(and :count more errors)": "(et :count erreur en plus)|(et :count erreurs en plus)|(et :count erreurs en plus)",
"- at least one lowercase letter": "- au moins une minuscule",
@ -49,6 +50,7 @@
"All products have been selected.": "Tous les produits ont été sélectionnés.",
"All rights reserved.": "Tous droits réservés.",
"Allergens": "Allergènes",
"Allowed extensions: :extensions (:maxSize MB max). Required dimensions: :width px by :height px": "Extensions autorisées : :extensions (:maxSize Mo max). Dimensions requises : :width px par :height px",
"Already registered?": "Déjà inscrit ?",
"Already Reported": "Déjà rapporté",
"An account is already associated with this email address": "Un compte est déjà associé à cette adresse e-mail",
@ -353,9 +355,6 @@
"Item removed from basket": "Article retiré du panier",
"jj": "jj",
"joinedfile": "Pièce jointe",
"JPEG/PNG, 2MB max.": "JPEG/PNG, 2Mo max.",
"JPEG/PNG, 2MB max. Recommended dimensions: :width px by :height px": "JPEG/PNG, 2Mo max. Dimensions conseillées : :width px par :height px",
"JPEG/PNG, 2Mo max.": "JPEG/PNG, 2Mo max.",
"Kcal": "Kcal",
"Keyword information": "Informations du mot clé",
"Keywords associated with the product": "Les mots clés associés au produit",

View file

@ -31,17 +31,10 @@
@change="pictureInputHasChanged"
type="file"
class="d-none"
:name="`${fileParamIsFile ? parameters.name : ''}`"
accept=".jpg,.jpeg,.gif,.png"
:name="fileParamIsFile ? parameters.name : undefined"
:accept="parameters.accept"
:aria-describedby="`Help${parameters.id}`"
>
<input
v-if="typeof fileOutput === 'string'"
class="d-none"
:name="parameters.name"
type="text"
:value="fileOutput"
>
<!-- END OUTPUT HTML INPUT -->
<!-- FILENAME DISPLAY -->
<input
@ -460,6 +453,25 @@ const UNITS = [
];
const BYTES_PER_KB = 1024;
const formatUrl = (val: string): string => {
if (!val) {
return "";
}
if (/^https?:\/\//i.test(val) || val.startsWith("data:")) {
return val;
}
return val.replace(/^\/|^/, "/");
};
const getFileName = (val: string): string => {
if (!val) {
return "";
}
const clean = val.split("?")[0].split("#")[0];
const lastSlash = clean.lastIndexOf("/");
return lastSlash !== -1 ? decodeURIComponent(clean.substring(lastSlash + 1)) : clean;
};
defineOptions({ name: "ImageInputComponent" });
// * EMITS
@ -496,6 +508,10 @@ const props = defineProps({
type: String,
default: ""
},
accept: {
type: String,
default: ".jpg,.jpeg,.png"
},
required: {
type: Boolean,
default: false
@ -537,6 +553,7 @@ const parameters = reactive<{
id: string,
name: string,
helper: string,
accept: string,
required: boolean,
showLabels: boolean,
preview: boolean,
@ -550,6 +567,7 @@ const parameters = reactive<{
id: props.id,
name: props.name,
helper: props.helper,
accept: props.accept,
required: props.required,
showLabels: props.showLabels,
preview: props.preview,
@ -574,7 +592,7 @@ const fileParameters = reactive<{
}>({
file: null,
filePath: "",
fileName: "",
fileName: __("vue.ImageInputComponent.choose_a_file"),
dimensions: {
height: 0,
width: 0,
@ -585,10 +603,10 @@ const fileParameters = reactive<{
const fileDataUrl = ref<string | null>(null);
/**
* The file we shall output :
* - String when having an already stored picture
* - File when we have a File fron the input or cropped component
* - null when noting
- The file we shall output :
- String when having an already stored picture
- File when we have a File fron the input or cropped component
- null when noting
*/
const fileOutput = ref<FileOutputValue>(null);
@ -637,14 +655,14 @@ onMounted(() => {
parameters.required = Boolean(data.required);
parameters.showLabels = Boolean(data.showLabels);
parameters.browseEvent = Boolean(data.browseEvent);
const value = data.value;
if (typeof value === "string" && value.length) {
fileParameters.filePath = value.replace(/^\/|^/, "");
fileParameters.fileName = value.replace(/^\/|^/, "");
fileOutput.value = fileParameters.filePath;
const value = String(data.value ?? "");
if (value.length) {
fileParameters.filePath = formatUrl(value);
fileParameters.fileName = getFileName(value);
fileDataUrl.value = fileParameters.filePath;
hasPicture.value = true;
}
}
fetchPictureFromPath(fileParameters.filePath);
initTooltips();
});
@ -659,14 +677,23 @@ watch(props, (newValue: typeof props) => {
assignFromProps();
previousPropValue.value = newValue.value;
}, { deep: true });
watch(previousPropValue, () => {
watch(previousPropValue, (newValue: string) => {
// * Ignore non prop usage.
if (!isUsedWithProps.value) {
return;
}
if (!newValue.length) {
resetComponent();
return;
}
cropperReset();
hasCroppedPicture.value = false;
fetchPictureFromPath(fileParameters.filePath)!.then((file) => useThis(file));
if (parameters.browseEvent) {
fetchPictureFromPath(fileParameters.filePath)?.then((file) => {
useThis(file);
fileOutput.value = file;
});
}
});
/** Crop parameters changes. */
watch(cropperParameters, (newValue: CropperParameters) => {
@ -708,14 +735,22 @@ watch(fileDataUrl, (newValue) => {
// * METHODS
function assignFromProps(): void {
fileParameters.filePath = props.value.replace(/^\/|^/, "");
fileParameters.fileName = props.value.replace(/^\/|^/, "");
fileOutput.value = fileParameters.filePath;
if (props.value.length) {
fileParameters.filePath = formatUrl(props.value);
fileParameters.fileName = getFileName(props.value);
fileDataUrl.value = fileParameters.filePath;
hasPicture.value = true;
} else if (!fileParamIsFile.value) {
fileParameters.filePath = "";
fileParameters.fileName = __("vue.ImageInputComponent.choose_a_file");
fileDataUrl.value = null;
hasPicture.value = false;
}
const mapParam = <T extends typeof parameters>(dest: T, prop: keyof T, value: ValueOf<T>) => {
dest[prop] = value;
};
for (const key of ["id", "name", "helper", "required", "showLabels", "preview", "browseEvent"]) {
for (const key of ["id", "name", "helper", "accept", "required", "showLabels", "preview", "browseEvent"]) {
const paramKey = key as keyof typeof parameters;
mapParam<typeof parameters>(parameters, paramKey, props[paramKey as never]);
}
@ -752,6 +787,28 @@ function cropperReset(): void {
lastAppliedRotation = 0;
}
/** Replace the filename extension so it matches the encoded MIME type. */
function replaceFileExtension(fileName: string, extension: string): string {
const cleanName = fileName.trim();
if (!cleanName || cleanName === __("vue.ImageInputComponent.choose_a_file")) {
return `image.${extension}`;
}
const dotIndex = cleanName.lastIndexOf(".");
if (dotIndex <= 0) {
return `${cleanName}.${extension}`;
}
return `${cleanName.slice(0, dotIndex)}.${extension}`;
}
function isJpegFile(file: File | null, fileName: string): boolean {
if (file?.type) {
return file.type === "image/jpeg";
}
return /\.(jpe?g)$/i.test(fileName);
}
/** Export cropped file from cropper. */
async function exportCropperFile(): Promise<void> {
const selection = cropperInstance.value?.getCropperSelection();
@ -760,12 +817,15 @@ async function exportCropperFile(): Promise<void> {
}
const outputWidth = Math.max(1, Math.trunc(parameters.dimensions.width));
const outputHeight = Math.max(1, Math.trunc(parameters.dimensions.height));
const useJpeg = isJpegFile(fileParameters.file, fileParameters.fileName);
const outputMime = useJpeg ? "image/jpeg" : "image/png";
const outputExtension = useJpeg ? "jpg" : "png";
hasCroppedPicture.value = true;
const canvas = await selection.$toCanvas({
width: outputWidth,
height: outputHeight,
beforeDraw: (context: CanvasRenderingContext2D) => {
context.fillStyle = "rgba(0, 0, 0, 0)";
context.fillStyle = useJpeg ? "#ffffff" : "rgba(0, 0, 0, 0)";
context.imageSmoothingEnabled = true;
context.imageSmoothingQuality = "high";
},
@ -780,15 +840,22 @@ async function exportCropperFile(): Promise<void> {
}
normalizedCtx.imageSmoothingEnabled = true;
normalizedCtx.imageSmoothingQuality = "high";
normalizedCtx.clearRect(0, 0, outputWidth, outputHeight);
if (useJpeg) {
normalizedCtx.fillStyle = "#ffffff";
normalizedCtx.fillRect(0, 0, outputWidth, outputHeight);
} else {
normalizedCtx.clearRect(0, 0, outputWidth, outputHeight);
}
normalizedCtx.drawImage(canvas, 0, 0, outputWidth, outputHeight);
fileDataUrl.value = normalizedCanvas.toDataURL("image/png");
fileDataUrl.value = useJpeg
? normalizedCanvas.toDataURL("image/jpeg")
: normalizedCanvas.toDataURL("image/png");
const file = new File(
[dataUrltoBlob(fileDataUrl.value)],
fileParameters.fileName,
replaceFileExtension(fileParameters.fileName, outputExtension),
{
type: "image/png",
type: outputMime,
lastModified: Date.now(),
}
);
@ -821,14 +888,14 @@ function fetchPictureFromPath(filePath: string): Promise<File> | void {
return;
}
return new Promise<File>((accept, deny) => nextTick(() => {
const prefixedFilePath: string = filePath.replace(/^\/|^/, "/"),
stringFileName: string = prefixedFilePath.substring(prefixedFilePath.lastIndexOf("/")).replace(/^\/|^/, "");
const prefixedFilePath: string = formatUrl(filePath),
stringFileName: string = getFileName(prefixedFilePath);
fetch(prefixedFilePath)
.then((response) => response.blob())
.then((blob: Blob) => {
const file = new File([blob], stringFileName, {
type: "image/png",
type: blob.type || "image/png",
lastModified: Date.now(),
});
setFileAsDataUrl(file);
@ -904,12 +971,7 @@ function prepareImageEditor(): void {
lastAppliedRotation = 0;
};
if (fileParameters.file === null) {
throw new Error("File nust not be null");
}
const editorImg = imgEditor.value!;
const blobUrl = URL.createObjectURL(fileParameters.file);
const initCropperAfterLoad = () => {
editorImg.removeEventListener("load", initCropperAfterLoad);
@ -922,8 +984,23 @@ function prepareImageEditor(): void {
});
};
editorImg.addEventListener("load", initCropperAfterLoad);
editorImg.src = blobUrl;
if (fileParameters.file !== null) {
editorImg.addEventListener("load", initCropperAfterLoad);
editorImg.src = URL.createObjectURL(fileParameters.file);
return;
}
if (fileDataUrl.value) {
fetch(formatUrl(fileDataUrl.value))
.then((response) => response.blob())
.then((blob: Blob) => {
editorImg.addEventListener("load", initCropperAfterLoad);
editorImg.src = URL.createObjectURL(blob);
});
return;
}
throw new Error("File must not be null");
}
/** Reset the entire component state. */
@ -992,8 +1069,8 @@ function setupCropperViewer(): boolean {
}
/**
* Cropper peut injecter sa sélection de manière asynchrone.
* On retente quelques frames pour éviter un preview blanc intermittent.
- Cropper peut injecter sa sélection de manière asynchrone.
- On retente quelques frames pour éviter un preview blanc intermittent.
*/
function setupCropperViewerWithRetry(maxAttempts = 10): void {
let attempts = 0;

View file

@ -130,15 +130,14 @@
<div class="row mb-4">
@include('bo.modules.input-error', ['inputName' => 'picture'])
@php
$jsonPic = [
'name' => 'picture',
'single' => true,
'width' => 200,
'height' => 200,
'preview' => false,
'helper' => __('JPEG/PNG, 2Mo max.'),
'value' => $product->picture ?? '',
];
$jsonPic = \App\Lib\Helpers\RequestHelper::imageInputConfig(
name: 'picture',
width: \App\Http\Requests\Bo\Products\StoreProductRequest::PICTURE_WIDTH,
height: \App\Http\Requests\Bo\Products\StoreProductRequest::PICTURE_HEIGHT,
maxSizeKb: \App\Http\Requests\Bo\Products\StoreProductRequest::MAX_FILE_SIZE_KB,
allowedExtensions: \App\Http\Requests\Bo\Products\StoreProductRequest::ALLOWED_EXTENSIONS,
value: $product->picture ?? '',
);
@endphp
<div class="image-input mb-2" data-json='@json($jsonPic)'></div>
@ -187,15 +186,14 @@
<div class="row">
@include('bo.modules.input-error', ['inputName' => 'picture_large'])
@php
$jsonPicLarge = [
'name' => 'picture_large',
'single' => true,
'width' => 500,
'height' => 500,
'preview' => false,
'helper' => __('JPEG/PNG, 2MB max.'),
'value' => $product->picture_large ?? '',
];
$jsonPicLarge = \App\Lib\Helpers\RequestHelper::imageInputConfig(
name: 'picture_large',
width: \App\Http\Requests\Bo\Products\StoreProductRequest::PICTURE_LARGE_WIDTH,
height: \App\Http\Requests\Bo\Products\StoreProductRequest::PICTURE_LARGE_HEIGHT,
maxSizeKb: \App\Http\Requests\Bo\Products\StoreProductRequest::MAX_FILE_SIZE_KB,
allowedExtensions: \App\Http\Requests\Bo\Products\StoreProductRequest::ALLOWED_EXTENSIONS,
value: $product->picture_large ?? '',
);
@endphp
<div class="image-input mb-2" data-json='@json($jsonPicLarge)'></div>

View file

@ -67,18 +67,14 @@
'inputName' => 'picture',
])
@php
$json = [
'name' => 'picture',
'single' => true,
'width' => 500,
'height' => 500,
'preview' => false,
'helper' => __('JPEG/PNG, 2MB max. Recommended dimensions: :width px by :height px', [
'width' => 500,
'height' => 500,
]),
'value' => $range->picture ?? '',
];
$json = \App\Lib\Helpers\RequestHelper::imageInputConfig(
name: 'picture',
width: \App\Http\Requests\Bo\Ranges\StoreRangeRequest::PICTURE_WIDTH,
height: \App\Http\Requests\Bo\Ranges\StoreRangeRequest::PICTURE_HEIGHT,
maxSizeKb: \App\Http\Requests\Bo\Ranges\StoreRangeRequest::MAX_FILE_SIZE_KB,
allowedExtensions: \App\Http\Requests\Bo\Ranges\StoreRangeRequest::ALLOWED_EXTENSIONS,
value: $range->picture ?? '',
);
@endphp
<div class="image-input" data-json='@json($json)'></div>
</div>

View file

@ -53,18 +53,14 @@
'inputName' => 'picture',
])
@php
$json = [
'name' => 'picture',
'single' => true,
'width' => 1440,
'height' => 960,
'preview' => false,
'helper' => __('JPEG/PNG, 2MB max. Recommended dimensions: :width px by :height px', [
'width' => 1440,
'height' => 960,
]),
'value' => $slide->picture ?? '',
];
$json = \App\Lib\Helpers\RequestHelper::imageInputConfig(
name: 'picture',
width: \App\Http\Requests\Bo\Slides\StoreSlideRequest::PICTURE_WIDTH,
height: \App\Http\Requests\Bo\Slides\StoreSlideRequest::PICTURE_HEIGHT,
maxSizeKb: \App\Http\Requests\Bo\Slides\StoreSlideRequest::MAX_FILE_SIZE_KB,
allowedExtensions: \App\Http\Requests\Bo\Slides\StoreSlideRequest::ALLOWED_EXTENSIONS,
value: $slide->picture ?? '',
);
@endphp
<div class="image-input" data-json='@json($json)'></div>
</div>

View file

@ -104,12 +104,19 @@
<div class="row mb-3">
<div class="col">
@php
$contactExtensions = array_map(
static fn (string $ext): string => '.' . ltrim($ext, '.'),
\App\Http\Requests\Fo\ContactFormRequest::ALLOWED_EXTENSIONS,
);
$contactMaxSizeMb = \App\Http\Requests\Fo\ContactFormRequest::MAX_FILE_SIZE_KB / 1024;
@endphp
<label class="form-label" for="file">
<span>{{ __('Attachment') }} </span>
<span class="fst-italic text-muted">(.pdf, .jpeg, .png, 5Mo max)</span>
<span class="fst-italic text-muted">{{ __('(:extensions, :maxSize MB max)', ['extensions' => implode(', ', $contactExtensions), 'maxSize' => $contactMaxSizeMb]) }}</span>
</label>
<input class="form-control @error('file') is-invalid @enderror" id="file" name="file" type="file"
accept=".jpg,.jpeg,.png,.pdf" />
accept="{{ implode(',', $contactExtensions) }}" />
@error('file')
<div class="invalid-feedback">{{ $message }}</div>
@enderror

View file

@ -2,6 +2,7 @@
declare(strict_types=1);
use App\Http\Requests\Bo\Products\StoreProductRequest;
use App\Models\Customer;
use App\Models\Discount;
use App\Models\Product;
@ -137,11 +138,31 @@ describe('ProductsController', function () {
});
it('can access create', function () {
/** @var \Tests\TestCase $this */
// WHEN
$response = $this->get('/bo/products/create');
// THEN
expect($response->status())->toBe(200);
$extensions = implode(', ', array_map(
static fn (string $ext): string => '.' . ltrim($ext, '.'),
StoreProductRequest::ALLOWED_EXTENSIONS,
));
$expectedPictureHelper = __('Allowed extensions: :extensions (:maxSize MB max). Required dimensions: :width px by :height px', [
'extensions' => $extensions,
'maxSize' => StoreProductRequest::MAX_FILE_SIZE_KB / 1024,
'width' => StoreProductRequest::PICTURE_WIDTH,
'height' => StoreProductRequest::PICTURE_HEIGHT,
]);
$expectedLargePictureHelper = __('Allowed extensions: :extensions (:maxSize MB max). Required dimensions: :width px by :height px', [
'extensions' => $extensions,
'maxSize' => StoreProductRequest::MAX_FILE_SIZE_KB / 1024,
'width' => StoreProductRequest::PICTURE_LARGE_WIDTH,
'height' => StoreProductRequest::PICTURE_LARGE_HEIGHT,
]);
$response->assertSee(json_encode($expectedPictureHelper), false);
$response->assertSee(json_encode($expectedLargePictureHelper), false);
});
it('renders empty string instead of null for ckeditor text when old input is null', function () {
@ -205,7 +226,7 @@ describe('ProductsController', function () {
// THEN
$response->assertSessionHasNoErrors();
expect($response->status())->toBe(302);
$product = Product::where('name', 'New Product')->first();
$product = Product::query()->where('name', 'New Product')->first();
expect($product)->not->toBeNull();
$response->assertRedirect("/bo/products/{$product->slug}/edit");
});
@ -350,7 +371,7 @@ describe('ProductsController', function () {
$response = $this->delete("/bo/products/{$product->slug}");
// THEN
expect(Product::find($product->id))->toBeNull();
expect(Product::query()->find($product->id))->toBeNull();
});
it('can toggle star', function (): void {

View file

@ -2,11 +2,14 @@
declare(strict_types=1);
use App\Http\Requests\Bo\Ranges\StoreRangeRequest;
use App\Models\Range;
use App\Models\User;
use Domain\Enums\UserRole;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Http\UploadedFile;
use Uwil\Storage\Contracts\StorageService;
use Uwil\Storage\Lib\ValueObjects\StorageFilePath;
uses(RefreshDatabase::class);
@ -16,6 +19,10 @@ describe('RangesController', function () {
// GIVEN
$this->user = User::factory()->create(['role' => UserRole::SuperAdmin]);
$this->actingAs($this->user, 'backend');
$storageMock = $this->mock(StorageService::class);
$storageMock->shouldIgnoreMissing();
$storageMock->shouldReceive('storeFileOntoDisk')
->andReturn(new StorageFilePath('ranges/picture.jpg'));
});
it('can access index', function () {
@ -34,6 +41,18 @@ describe('RangesController', function () {
// THEN
expect($response->status())->toBe(200);
$extensions = implode(', ', array_map(
static fn (string $ext): string => '.' . ltrim($ext, '.'),
StoreRangeRequest::ALLOWED_EXTENSIONS,
));
$expectedHelper = __('Allowed extensions: :extensions (:maxSize MB max). Required dimensions: :width px by :height px', [
'extensions' => $extensions,
'maxSize' => StoreRangeRequest::MAX_FILE_SIZE_KB / 1024,
'width' => StoreRangeRequest::PICTURE_WIDTH,
'height' => StoreRangeRequest::PICTURE_HEIGHT,
]);
$response->assertSee(json_encode($expectedHelper), false);
});
it('can store a range', function () {

View file

@ -3,6 +3,7 @@
declare(strict_types=1);
use App\Dto\SlideDto;
use App\Http\Requests\Bo\Slides\StoreSlideRequest;
use App\Models\Slide;
use App\Models\User;
use Domain\Enums\UserRole;
@ -38,6 +39,18 @@ describe('SlidesController', function (): void {
// THEN
expect($response->status())->toBe(200);
$response->assertViewIs('bo.slides.create');
$extensions = implode(', ', array_map(
static fn (string $ext): string => '.' . ltrim($ext, '.'),
StoreSlideRequest::ALLOWED_EXTENSIONS,
));
$expectedHelper = __('Allowed extensions: :extensions (:maxSize MB max). Required dimensions: :width px by :height px', [
'extensions' => $extensions,
'maxSize' => StoreSlideRequest::MAX_FILE_SIZE_KB / 1024,
'width' => StoreSlideRequest::PICTURE_WIDTH,
'height' => StoreSlideRequest::PICTURE_HEIGHT,
]);
$response->assertSee(json_encode($expectedHelper), false);
});
it('can store a slide', function (): void {

View file

@ -3,6 +3,7 @@
declare(strict_types=1);
use App\Http\Requests\Bo\Products\StoreProductRequest;
use Illuminate\Http\UploadedFile;
use Infrastructure\Adapters\Services\AppAdminAuthService;
use function Pest\Laravel\mock;
@ -74,4 +75,32 @@ describe('StoreProductRequest', function () {
// THEN
expect(true)->toBeTrue();
});
it('rejects product pictures when extension and mime type do not match or are disallowed', function () {
// GIVEN
$authService = mock(AppAdminAuthService::class);
$request = new StoreProductRequest($authService);
$rules = $request->rules();
$pngSmall = UploadedFile::fake()->image('small.png', StoreProductRequest::PICTURE_WIDTH, StoreProductRequest::PICTURE_HEIGHT);
$mismatchedSmall = new UploadedFile(
path: $pngSmall->getRealPath(),
originalName: 'product.jpeg',
mimeType: 'image/png',
error: UPLOAD_ERR_OK,
test: true,
);
$disallowedLarge = UploadedFile::fake()->image(
'large.webp',
StoreProductRequest::PICTURE_LARGE_WIDTH,
StoreProductRequest::PICTURE_LARGE_HEIGHT,
);
// WHEN
$smallValidator = validator(['picture' => $mismatchedSmall], ['picture' => $rules['picture']]);
$largeValidator = validator(['picture_large' => $disallowedLarge], ['picture_large' => $rules['picture_large']]);
// THEN
expect($smallValidator->errors()->has('picture'))->toBeTrue()
->and($largeValidator->errors()->has('picture_large'))->toBeTrue();
});
});

View file

@ -3,6 +3,7 @@
declare(strict_types=1);
use App\Http\Requests\Bo\Ranges\StoreRangeRequest;
use Illuminate\Http\UploadedFile;
use Infrastructure\Adapters\Services\AppAdminAuthService;
use function Pest\Laravel\mock;
@ -59,4 +60,28 @@ describe('StoreRangeRequest', function () {
// THEN
expect(true)->toBeTrue(); // just making sure it runs without exception
});
it('rejects a range image when extension and mime type do not match or are disallowed', function () {
// GIVEN
$authService = mock(AppAdminAuthService::class);
$request = new StoreRangeRequest($authService);
$rules = $request->rules();
$pngSource = UploadedFile::fake()->image('cropped.png', StoreRangeRequest::PICTURE_WIDTH, StoreRangeRequest::PICTURE_HEIGHT);
$mismatched = new UploadedFile(
path: $pngSource->getRealPath(),
originalName: 'range.jpeg',
mimeType: 'image/png',
error: UPLOAD_ERR_OK,
test: true,
);
$disallowedWebp = UploadedFile::fake()->image('range.webp', StoreRangeRequest::PICTURE_WIDTH, StoreRangeRequest::PICTURE_HEIGHT);
// WHEN
$mismatchValidator = validator(['picture' => $mismatched], ['picture' => $rules['picture']]);
$webpValidator = validator(['picture' => $disallowedWebp], ['picture' => $rules['picture']]);
// THEN
expect($mismatchValidator->errors()->has('picture'))->toBeTrue()
->and($webpValidator->errors()->has('picture'))->toBeTrue();
});
});

View file

@ -3,6 +3,7 @@
declare(strict_types=1);
use App\Http\Requests\Bo\Slides\StoreSlideRequest;
use Illuminate\Http\UploadedFile;
use Infrastructure\Adapters\Services\AppAdminAuthService;
use function Pest\Laravel\mock;
@ -114,4 +115,80 @@ describe('StoreSlideRequest', function () {
// THEN
expect($validator->errors()->has('text'))->toBeFalse();
});
it('accepts a 3MB slide image matching required dimensions', function () {
// GIVEN
$authService = mock(AppAdminAuthService::class);
$request = new StoreSlideRequest($authService);
$rules = $request->rules();
$picture = UploadedFile::fake()
->image('slide.jpg', StoreSlideRequest::PICTURE_WIDTH, StoreSlideRequest::PICTURE_HEIGHT)
->size(3072);
// WHEN
$validator = validator(
[
'title' => 'Slide Title',
'picture' => $picture,
'picture_alt' => 'Alt text',
'picture_title' => 'Title text',
'text' => null,
'link_new_tab' => false,
'connected' => false,
'client_timezone' => 'Europe/Paris',
],
$rules
);
// THEN
expect($validator->fails())->toBeFalse();
});
it('rejects a slide image when extension and mime type do not match or are disallowed', function () {
// GIVEN
$authService = mock(AppAdminAuthService::class);
$request = new StoreSlideRequest($authService);
$rules = $request->rules();
$pngSource = UploadedFile::fake()->image('cropped.png', StoreSlideRequest::PICTURE_WIDTH, StoreSlideRequest::PICTURE_HEIGHT);
$mismatched = new UploadedFile(
path: $pngSource->getRealPath(),
originalName: 'slide.jpeg',
mimeType: 'image/png',
error: UPLOAD_ERR_OK,
test: true,
);
$disallowedWebp = UploadedFile::fake()->image('slide.webp', StoreSlideRequest::PICTURE_WIDTH, StoreSlideRequest::PICTURE_HEIGHT);
// WHEN
$mismatchValidator = validator(
[
'title' => 'Slide Title',
'picture' => $mismatched,
'picture_alt' => 'Alt text',
'picture_title' => 'Title text',
'text' => null,
'link_new_tab' => false,
'connected' => false,
'client_timezone' => 'Europe/Paris',
],
$rules
);
$webpValidator = validator(
[
'title' => 'Slide Title',
'picture' => $disallowedWebp,
'picture_alt' => 'Alt text',
'picture_title' => 'Title text',
'text' => null,
'link_new_tab' => false,
'connected' => false,
'client_timezone' => 'Europe/Paris',
],
$rules
);
// THEN
expect($mismatchValidator->errors()->has('picture'))->toBeTrue()
->and($webpValidator->errors()->has('picture'))->toBeTrue();
});
});

View file

@ -2,9 +2,11 @@
declare(strict_types=1);
use App\Cqs\Actions\Contact\SubmitContactFormInput;
use App\Http\Requests\Fo\ContactFormRequest;
use Domain\Models\ValueObjects\ContactFormData;
use Illuminate\Filesystem\FilesystemAdapter;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Validator;
describe('ContactFormRequest', function () {
@ -17,7 +19,7 @@ describe('ContactFormRequest', function () {
$request->merge([
'last_name' => 'Doe',
'first_name' => 'John',
'email' => 'john.doe@example.com',
'email' => 'john.doe@gmail.com',
'subject' => 'Help with my order',
'order_ref' => '123456',
'message' => 'This is a message that is longer than 20 characters.',
@ -25,7 +27,8 @@ describe('ContactFormRequest', function () {
]);
// THEN
expect(true)->toBeTrue();
$validator = Validator::make($request->all(), $request->rules(), $request->messages());
expect($validator->passes())->toBeTrue();
});
it('fails validation on incorrect rules', function () {
@ -67,7 +70,7 @@ describe('ContactFormRequest', function () {
$request->merge([
'last_name' => 'Doe',
'first_name' => 'John',
'email' => 'john.doe@example.com',
'email' => 'john.doe@gmail.com',
'subject' => 'Help with my order',
'message' => 'This is a message that is longer than 20 characters.',
'ok_cgv' => true,
@ -77,37 +80,69 @@ describe('ContactFormRequest', function () {
$request->files->set('file', $file);
// THEN
expect(true)->toBeTrue();
$validator = Validator::make($request->all(), $request->rules(), $request->messages());
expect($validator->passes())->toBeTrue();
});
it('converts to value object without file', function () {
it('rejects contact attachment when extension and mime type do not match', function () {
// GIVEN
$pngSource = UploadedFile::fake()->image('cropped.png', 100, 100);
$mismatched = new UploadedFile(
path: $pngSource->getRealPath(),
originalName: 'attachment.pdf',
mimeType: 'image/png',
error: UPLOAD_ERR_OK,
test: true,
);
$request = new ContactFormRequest();
$request->initialize();
// WHEN
$validator = Validator::make(['file' => $mismatched], ['file' => $request->rules()['file']], $request->messages());
// THEN
expect($validator->errors()->has('file'))->toBeTrue();
});
it('converts to action input without file', function () {
// GIVEN
$request = new ContactFormRequest();
$request->initialize();
$request->merge([
'last_name' => 'Doe',
'first_name' => 'John',
'email' => 'john.doe@example.com',
'email' => 'john.doe@gmail.com',
'subject' => 'Help',
'order_ref' => '123',
'message' => 'This is a message that is longer than 20 characters.',
]);
// WHEN
$vo = $request->toValueObject();
$input = $request->toSubmitContactFormInput();
// THEN
expect($vo)->toBeInstanceOf(ContactFormData::class)
->and($vo->lastName)->toBe('Doe')
->and($vo->firstName)->toBe('John')
->and($vo->email)->toBe('john.doe@example.com')
->and($vo->subject)->toBe('Help')
->and($vo->orderRef)->toBe('123')
->and($vo->message)->toBe('This is a message that is longer than 20 characters.')
->and($vo->file)->toBeNull();
expect($input)->toBeInstanceOf(SubmitContactFormInput::class)
->and($input->lastName)->toBe('Doe')
->and($input->firstName)->toBe('John')
->and($input->email)->toBe('john.doe@gmail.com')
->and($input->subject)->toBe('Help')
->and($input->orderRef)->toBe('123')
->and($input->message)->toBe('This is a message that is longer than 20 characters.')
->and($input->file)->toBeNull();
});
it('converts to value object with file', function () {
it('keeps a configured s3 private disk for emailed attachments', function () {
// GIVEN
expect(config('filesystems.disks.s3-private'))->not->toBeNull();
// WHEN
$disk = Storage::disk('s3-private');
// THEN
expect($disk)->toBeInstanceOf(FilesystemAdapter::class);
});
it('converts to action input with file', function () {
// GIVEN
$file = UploadedFile::fake()->create('document.pdf', 100, 'application/pdf');
@ -116,20 +151,18 @@ describe('ContactFormRequest', function () {
$request->merge([
'last_name' => 'Doe',
'first_name' => 'John',
'email' => 'john.doe@example.com',
'email' => 'john.doe@gmail.com',
'subject' => 'Help',
'message' => 'This is a message that is longer than 20 characters.',
]);
$request->files->set('file', $file);
// WHEN
$vo = $request->toValueObject();
$input = $request->toSubmitContactFormInput();
// THEN
expect($vo)->toBeInstanceOf(ContactFormData::class)
->and($vo->file)->not->toBeNull()
->and($vo->file->originalName)->toBe('document.pdf')
->and($vo->file->mimeType)->toBe('application/pdf');
expect($input)->toBeInstanceOf(SubmitContactFormInput::class)
->and($input->file)->toBe($file);
});
it('returns custom messages', function () {