Refactor attachment cropping functionality to support multiple variants

- Introduced AttachmentCrop model to manage crop variants for attachments.
- Updated Attachment model to remove direct crop fields and establish relationships with AttachmentCrop.
- Modified AttachmentService to handle storing and updating multiple crop variants (desktop and mobile).
- Adjusted validation rules to accommodate new crop structure.
- Updated database migration to create attachment_crops table and migrate existing crop data.
- Refactored tests to ensure compatibility with the new cropping structure and validate multiple crop variants.
- Enhanced documentation to reflect changes in attachment handling and cropping capabilities.
This commit is contained in:
2026-08-18 14:40:22 -03:00
parent c00b3d609c
commit e619c51ac9
14 changed files with 526 additions and 150 deletions

View File

@@ -6,7 +6,7 @@ use App\Domains\Attachable\Enums\AttachmentType;
use Illuminate\Database\Eloquent\Attributes\Fillable; use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo; use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\HasOne; use Illuminate\Database\Eloquent\Relations\HasOne;
use Illuminate\Support\Facades\Storage; use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str; use Illuminate\Support\Str;
@@ -19,9 +19,6 @@ use Illuminate\Support\Str;
'mime_type', 'mime_type',
'extension', 'extension',
'size', 'size',
'crop_horizontal',
'crop_vertical',
'cropped_attachment_id',
])] ])]
class Attachment extends Model class Attachment extends Model
{ {
@@ -43,20 +40,29 @@ class Attachment extends Model
return [ return [
'type' => AttachmentType::class, 'type' => AttachmentType::class,
'size' => 'integer', 'size' => 'integer',
'crop_horizontal' => 'array',
'crop_vertical' => 'array',
'cropped_attachment_id' => 'integer',
]; ];
} }
public function croppedAttachment(): BelongsTo public function cropVariants(): HasMany
{ {
return $this->belongsTo(self::class, 'cropped_attachment_id'); return $this->hasMany(AttachmentCrop::class);
} }
public function originalAttachment(): HasOne public function desktopCrop(): HasOne
{ {
return $this->hasOne(self::class, 'cropped_attachment_id'); return $this->hasOne(AttachmentCrop::class)
->where('variant', AttachmentCrop::DESKTOP);
}
public function mobileCrop(): HasOne
{
return $this->hasOne(AttachmentCrop::class)
->where('variant', AttachmentCrop::MOBILE);
}
public function cropSource(): HasOne
{
return $this->hasOne(AttachmentCrop::class, 'cropped_attachment_id');
} }
/** /**

View File

@@ -0,0 +1,43 @@
<?php
namespace App\Domains\Attachable\Models;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
#[Fillable([
'attachment_id',
'variant',
'crop_horizontal',
'crop_vertical',
'cropped_attachment_id',
])]
class AttachmentCrop extends Model
{
public const DESKTOP = 'desktop';
public const MOBILE = 'mobile';
public const VARIANTS = [self::DESKTOP, self::MOBILE];
protected function casts(): array
{
return [
'attachment_id' => 'integer',
'crop_horizontal' => 'array',
'crop_vertical' => 'array',
'cropped_attachment_id' => 'integer',
];
}
public function attachment(): BelongsTo
{
return $this->belongsTo(Attachment::class);
}
public function croppedAttachment(): BelongsTo
{
return $this->belongsTo(Attachment::class, 'cropped_attachment_id');
}
}

View File

@@ -5,6 +5,7 @@ namespace App\Domains\Attachable\Services;
use App\Domains\Attachable\Enums\AttachmentType; use App\Domains\Attachable\Enums\AttachmentType;
use App\Domains\Attachable\Exceptions\AttachmentStorageException; use App\Domains\Attachable\Exceptions\AttachmentStorageException;
use App\Domains\Attachable\Models\Attachment; use App\Domains\Attachable\Models\Attachment;
use App\Domains\Attachable\Models\AttachmentCrop;
use Illuminate\Http\UploadedFile; use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage; use Illuminate\Support\Facades\Storage;
@@ -14,46 +15,40 @@ use Throwable;
class AttachmentService class AttachmentService
{ {
public function storeCroppedImage( /**
* @param array<string, array{crop_horizontal: array<string, mixed>, crop_vertical: array<string, mixed>}> $crops
*/
public function storeCroppedImageVariants(
UploadedFile|string $image, UploadedFile|string $image,
string $path, string $path,
array $cropHorizontal, array $crops,
array $cropVertical,
): Attachment { ): Attachment {
$cropHorizontal = $this->validateCropRange($cropHorizontal, 'horizontal'); $crops = $this->validateCropVariants($crops);
$cropVertical = $this->validateCropRange($cropVertical, 'vertical');
$storedPaths = []; $storedPaths = [];
try { try {
return DB::transaction(function () use ( return DB::transaction(function () use (
$image, $image,
$path, $path,
$cropHorizontal, $crops,
$cropVertical,
&$storedPaths, &$storedPaths,
): Attachment { ): Attachment {
$original = $this->store($image, $path); $original = $this->store($image, $path);
$storedPaths[] = $original->path; $storedPaths[] = $original->path;
$contents = $this->imageContents($image);
$croppedContents = $this->cropImage( foreach ($crops as $variant => $crop) {
$this->imageContents($image), $cropped = $this->storeCropVariant($contents, $path, $crop);
$cropHorizontal, $storedPaths[] = $cropped->path;
$cropVertical, $original->cropVariants()->create([
); 'variant' => $variant,
$cropped = $this->store( 'crop_horizontal' => $crop['crop_horizontal'],
'data:'.$croppedContents['mime_type'].';base64,'.base64_encode($croppedContents['contents']), 'crop_vertical' => $crop['crop_vertical'],
$path, 'cropped_attachment_id' => $cropped->id,
); ]);
$storedPaths[] = $cropped->path; }
$original->update([ return $original->load('cropVariants.croppedAttachment');
'crop_horizontal' => $cropHorizontal,
'crop_vertical' => $cropVertical,
'cropped_attachment_id' => $cropped->id,
]);
return $original->load('croppedAttachment');
}); });
} catch (Throwable $throwable) { } catch (Throwable $throwable) {
if ($storedPaths !== []) { if ($storedPaths !== []) {
@@ -64,49 +59,61 @@ class AttachmentService
} }
} }
public function updateImageCrop( /**
* @param array<string, array{crop_horizontal: array<string, mixed>, crop_vertical: array<string, mixed>}> $crops
*/
public function updateImageCropVariants(
Attachment $original, Attachment $original,
array $cropHorizontal, array $crops,
array $cropVertical,
): Attachment { ): Attachment {
if ($original->type !== AttachmentType::Image) { if ($original->type !== AttachmentType::Image) {
throw new AttachmentStorageException('Only image attachments can be cropped.'); throw new AttachmentStorageException('Only image attachments can be cropped.');
} }
$cropHorizontal = $this->validateCropRange($cropHorizontal, 'horizontal'); $crops = $this->validateCropVariants($crops);
$cropVertical = $this->validateCropRange($cropVertical, 'vertical');
$contents = Storage::disk('s3')->get($original->path); $contents = Storage::disk('s3')->get($original->path);
if (! is_string($contents) || $contents === '') { if (! is_string($contents) || $contents === '') {
throw new AttachmentStorageException('The original image could not be read from the s3 disk.'); throw new AttachmentStorageException('The original image could not be read from the s3 disk.');
} }
$croppedContents = $this->cropImage($contents, $cropHorizontal, $cropVertical);
$directory = trim(str_replace('\\', '/', dirname($original->path)), './'); $directory = trim(str_replace('\\', '/', dirname($original->path)), './');
$directory = $directory !== '' ? $directory : 'attachments'; $directory = $directory !== '' ? $directory : 'attachments';
$previousCrop = $original->croppedAttachment; $previousCrops = $original->cropVariants()->with('croppedAttachment')->get();
$cropped = $this->store( $storedCrops = [];
'data:'.$croppedContents['mime_type'].';base64,'.base64_encode($croppedContents['contents']),
$directory,
);
try { try {
$original->update([ foreach ($crops as $variant => $crop) {
'crop_horizontal' => $cropHorizontal, $storedCrops[$variant] = $this->storeCropVariant($contents, $directory, $crop);
'crop_vertical' => $cropVertical, }
'cropped_attachment_id' => $cropped->id,
]); DB::transaction(function () use ($original, $crops, $storedCrops): void {
foreach ($crops as $variant => $crop) {
$original->cropVariants()->updateOrCreate(
['variant' => $variant],
[
'crop_horizontal' => $crop['crop_horizontal'],
'crop_vertical' => $crop['crop_vertical'],
'cropped_attachment_id' => $storedCrops[$variant]->id,
]
);
}
});
} catch (Throwable $throwable) { } catch (Throwable $throwable) {
$this->delete($cropped); foreach ($storedCrops as $storedCrop) {
$this->delete($storedCrop);
}
throw $throwable; throw $throwable;
} }
if ($previousCrop !== null && ! $previousCrop->is($cropped)) { foreach ($previousCrops as $previousCrop) {
$this->delete($previousCrop); if ($previousCrop->croppedAttachment !== null) {
$this->delete($previousCrop->croppedAttachment);
}
} }
return $original->refresh()->load('croppedAttachment'); return $original->refresh()->load('cropVariants.croppedAttachment');
} }
public function store( public function store(
@@ -153,11 +160,18 @@ class AttachmentService
public function delete(Attachment $attachment): void public function delete(Attachment $attachment): void
{ {
$croppedAttachment = $attachment->croppedAttachment; $croppedAttachments = $attachment->cropVariants()
$paths = array_values(array_filter([ ->with('croppedAttachment')
$attachment->path, ->get()
$croppedAttachment?->path, ->pluck('croppedAttachment')
])); ->filter();
$paths = $croppedAttachments
->pluck('path')
->prepend($attachment->path)
->filter()
->unique()
->values()
->all();
$deleted = Storage::disk('s3')->delete( $deleted = Storage::disk('s3')->delete(
count($paths) === 1 ? $paths[0] : $paths count($paths) === 1 ? $paths[0] : $paths
); );
@@ -166,9 +180,9 @@ class AttachmentService
throw new AttachmentStorageException('No se pudieron eliminar los archivos del disco s3.'); throw new AttachmentStorageException('No se pudieron eliminar los archivos del disco s3.');
} }
DB::transaction(function () use ($attachment, $croppedAttachment): void { DB::transaction(function () use ($attachment, $croppedAttachments): void {
$attachment->delete(); $attachment->delete();
$croppedAttachment?->delete(); Attachment::query()->whereKey($croppedAttachments->pluck('id'))->delete();
}); });
} }
@@ -213,6 +227,56 @@ class AttachmentService
return trim($path, '/'); return trim($path, '/');
} }
/**
* @param array<string, array{crop_horizontal?: mixed, crop_vertical?: mixed}> $crops
* @return array<string, array{crop_horizontal: array{start_percentage: float, end_percentage: float}, crop_vertical: array{start_percentage: float, end_percentage: float}}>
*/
protected function validateCropVariants(array $crops): array
{
$validated = [];
foreach (AttachmentCrop::VARIANTS as $variant) {
$crop = $crops[$variant] ?? null;
if (! is_array($crop)) {
throw new AttachmentStorageException("The {$variant} crop is required.");
}
$horizontal = $crop['crop_horizontal'] ?? null;
$vertical = $crop['crop_vertical'] ?? null;
if (! is_array($horizontal) || ! is_array($vertical)) {
throw new AttachmentStorageException(
"The {$variant} crop must contain crop_horizontal and crop_vertical ranges."
);
}
$validated[$variant] = [
'crop_horizontal' => $this->validateCropRange($horizontal, "{$variant} horizontal"),
'crop_vertical' => $this->validateCropRange($vertical, "{$variant} vertical"),
];
}
return $validated;
}
/**
* @param array{crop_horizontal: array<string, mixed>, crop_vertical: array<string, mixed>} $crop
*/
protected function storeCropVariant(string $contents, string $path, array $crop): Attachment
{
$croppedContents = $this->cropImage(
$contents,
$crop['crop_horizontal'],
$crop['crop_vertical'],
);
return $this->store(
'data:'.$croppedContents['mime_type'].';base64,'.base64_encode($croppedContents['contents']),
$path,
);
}
/** /**
* @param array{start_percentage?: mixed, end_percentage?: mixed} $range * @param array{start_percentage?: mixed, end_percentage?: mixed} $range
* @return array{start_percentage: float, end_percentage: float} * @return array{start_percentage: float, end_percentage: float}

View File

@@ -2,11 +2,12 @@
## Propósito ## Propósito
Centraliza el almacenamiento y la metadata de archivos adjuntos. Acepta archivos subidos o contenido Base64, los persiste en S3 y registra su tipo, MIME, extensión, tamaño, nombre original y clave única. Para imágenes también permite guardar un original junto con una versión recortada desde porcentajes horizontales y verticales. Centraliza el almacenamiento y la metadata de archivos adjuntos. Acepta archivos subidos o contenido Base64, los persiste en S3 y registra su tipo, MIME, extensión, tamaño, nombre original y clave única. Para imágenes también permite guardar un original junto con variantes recortadas para desktop y mobile.
## Componentes principales ## Componentes principales
- `Models/Attachment.php`: representa un adjunto y genera URL temporales de acceso. - `Models/Attachment.php`: representa un adjunto y genera URL temporales de acceso.
- `Models/AttachmentCrop.php`: relaciona un original con su crop desktop o mobile y la imagen generada.
- `Services/AttachmentService.php`: almacena, copia y elimina archivos, compensando en S3 si falla la escritura en base de datos. - `Services/AttachmentService.php`: almacena, copia y elimina archivos, compensando en S3 si falla la escritura en base de datos.
- `Enums/AttachmentType.php`: clasifica imágenes, videos, PDF, audio, documentos y otros archivos. - `Enums/AttachmentType.php`: clasifica imágenes, videos, PDF, audio, documentos y otros archivos.
- `Exceptions/AttachmentStorageException.php`: expresa fallos propios del almacenamiento. - `Exceptions/AttachmentStorageException.php`: expresa fallos propios del almacenamiento.
@@ -26,7 +27,7 @@ No expone rutas HTTP propias. Lo consumen otros dominios, especialmente `Catalog
- El directorio no puede quedar vacío después de normalizarlo. - El directorio no puede quedar vacío después de normalizarlo.
- Cada eje del crop guarda `start_percentage` y `end_percentage`, cumpliendo `0 <= start < end <= 100`. - Cada eje del crop guarda `start_percentage` y `end_percentage`, cumpliendo `0 <= start < end <= 100`.
- El attachment original guarda los rangos horizontal y vertical y la relación `croppedAttachment` con la versión procesada. - `attachment_crops` guarda una fila por variante con los rangos horizontal/vertical y el attachment procesado.
- Al eliminar el original mediante el servicio también se elimina su versión recortada. - Al eliminar el original mediante el servicio también se eliminan todas sus variantes recortadas.
- La eliminación se considera fallida si S3 no confirma el borrado. - La eliminación se considera fallida si S3 no confirma el borrado.
- Las URL generadas son temporales; el vencimiento predeterminado es de 10 minutos. - Las URL generadas son temporales; el vencimiento predeterminado es de 10 minutos.

View File

@@ -35,6 +35,24 @@ class CroppedImageOrBase64Rule implements ValidationRule
return; return;
} }
if (isset($value['crops']) && is_array($value['crops'])) {
foreach (['desktop', 'mobile'] as $variant) {
$crop = $value['crops'][$variant] ?? null;
if (! is_array($crop)) {
$fail("The :attribute.crops.{$variant} field must be an object.");
continue;
}
$this->validateRange("{$attribute}.crops.{$variant}", 'crop_horizontal', $crop, $fail);
$this->validateRange("{$attribute}.crops.{$variant}", 'crop_vertical', $crop, $fail);
}
return;
}
// Backwards compatibility with the original single-crop payload.
$this->validateRange($attribute, 'crop_horizontal', $value, $fail); $this->validateRange($attribute, 'crop_horizontal', $value, $fail);
$this->validateRange($attribute, 'crop_vertical', $value, $fail); $this->validateRange($attribute, 'crop_vertical', $value, $fail);
} }

View File

@@ -3,6 +3,7 @@
namespace App\Domains\Tenant\Resources\AdminApp; namespace App\Domains\Tenant\Resources\AdminApp;
use App\Domains\Attachable\Models\Attachment; use App\Domains\Attachable\Models\Attachment;
use App\Domains\Attachable\Models\AttachmentCrop;
use App\Domains\Tenant\Models\WebsiteExtra; use App\Domains\Tenant\Models\WebsiteExtra;
use Illuminate\Http\Request; use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource; use Illuminate\Http\Resources\Json\JsonResource;
@@ -49,10 +50,19 @@ class WebsiteExtraResource extends JsonResource
$attachment = $config['background_image_id']; $attachment = $config['background_image_id'];
$fullRange = ['start_percentage' => 0.0, 'end_percentage' => 100.0]; $fullRange = ['start_percentage' => 0.0, 'end_percentage' => 100.0];
$crops = $attachment->cropVariants->keyBy('variant');
$config['background_image_id'] = [ $config['background_image_id'] = [
'url' => $attachment->getTemporaryUrl(1440), 'url' => $attachment->getTemporaryUrl(1440),
'crop_horizontal' => $attachment->crop_horizontal ?? $fullRange, 'crops' => collect(AttachmentCrop::VARIANTS)->mapWithKeys(
'crop_vertical' => $attachment->crop_vertical ?? $fullRange, function (string $variant) use ($crops, $fullRange): array {
$crop = $crops->get($variant);
return [$variant => [
'crop_horizontal' => $crop?->crop_horizontal ?? $fullRange,
'crop_vertical' => $crop?->crop_vertical ?? $fullRange,
]];
}
)->all(),
]; ];
return $config; return $config;

View File

@@ -3,6 +3,7 @@
namespace App\Domains\Tenant\Resources\AdminApp; namespace App\Domains\Tenant\Resources\AdminApp;
use App\Domains\Attachable\Models\Attachment; use App\Domains\Attachable\Models\Attachment;
use App\Domains\Attachable\Models\AttachmentCrop;
use App\Domains\Tenant\Models\Tenant; use App\Domains\Tenant\Models\Tenant;
use Illuminate\Http\Request; use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource; use Illuminate\Http\Resources\Json\JsonResource;
@@ -70,16 +71,25 @@ class WebsiteExtrasResource extends JsonResource
} }
/** /**
* @return array{url: string, crop_horizontal: array<string, float>, crop_vertical: array<string, float>} * @return array{url: string, crops: array<string, array<string, array<string, float>>>}
*/ */
private function formatHeroAttachment(Attachment $attachment): array private function formatHeroAttachment(Attachment $attachment): array
{ {
$fullRange = ['start_percentage' => 0.0, 'end_percentage' => 100.0]; $fullRange = ['start_percentage' => 0.0, 'end_percentage' => 100.0];
$crops = $attachment->cropVariants->keyBy('variant');
return [ return [
'url' => $attachment->getTemporaryUrl(1440), 'url' => $attachment->getTemporaryUrl(1440),
'crop_horizontal' => $attachment->crop_horizontal ?? $fullRange, 'crops' => collect(AttachmentCrop::VARIANTS)->mapWithKeys(
'crop_vertical' => $attachment->crop_vertical ?? $fullRange, function (string $variant) use ($crops, $fullRange): array {
$crop = $crops->get($variant);
return [$variant => [
'crop_horizontal' => $crop?->crop_horizontal ?? $fullRange,
'crop_vertical' => $crop?->crop_vertical ?? $fullRange,
]];
}
)->all(),
]; ];
} }

View File

@@ -3,6 +3,7 @@
namespace App\Domains\Tenant\Resources; namespace App\Domains\Tenant\Resources;
use App\Domains\Attachable\Models\Attachment; use App\Domains\Attachable\Models\Attachment;
use App\Domains\Attachable\Models\AttachmentCrop;
use App\Domains\Catalog\Models\Category; use App\Domains\Catalog\Models\Category;
use App\Domains\Menu\Models\Menu; use App\Domains\Menu\Models\Menu;
use App\Domains\Tenant\Models\Tenant; use App\Domains\Tenant\Models\Tenant;
@@ -98,7 +99,18 @@ class TenantResource extends JsonResource
private function formatExtraConfig(mixed $value): mixed private function formatExtraConfig(mixed $value): mixed
{ {
if ($value instanceof Attachment) { if ($value instanceof Attachment) {
return ($value->croppedAttachment ?? $value)->getTemporaryUrl(1440); $crops = $value->cropVariants->keyBy('variant');
$desktop = $crops->get(AttachmentCrop::DESKTOP)?->croppedAttachment ?? $value;
$mobile = $crops->get(AttachmentCrop::MOBILE)?->croppedAttachment ?? $desktop;
if ($crops->isEmpty()) {
return $value->getTemporaryUrl(1440);
}
return [
'desktop' => $desktop->getTemporaryUrl(1440),
'mobile' => $mobile->getTemporaryUrl(1440),
];
} }
if (! is_array($value)) { if (! is_array($value)) {

View File

@@ -81,7 +81,7 @@ class TenantInformationService
$attachments = Attachment::query() $attachments = Attachment::query()
->whereIn('id', $attachmentIds) ->whereIn('id', $attachmentIds)
->with('croppedAttachment') ->with('cropVariants.croppedAttachment')
->get() ->get()
->keyBy('id'); ->keyBy('id');

View File

@@ -334,8 +334,7 @@ class WebsiteExtraService
); );
} }
$cropHorizontal = is_array($value) ? $value['crop_horizontal'] ?? null : null; $crops = $this->cropVariants($value);
$cropVertical = is_array($value) ? $value['crop_vertical'] ?? null : null;
$image = is_array($value) ? $value['image'] ?? null : $value; $image = is_array($value) ? $value['image'] ?? null : $value;
if (is_string($image) && Str::isUuid($image)) { if (is_string($image) && Str::isUuid($image)) {
@@ -349,19 +348,17 @@ class WebsiteExtraService
]); ]);
} }
if (is_array($cropHorizontal) && is_array($cropVertical)) { if ($crops !== null) {
$attachment = $this->attachmentService->updateImageCrop( $attachment = $this->attachmentService->updateImageCropVariants(
$attachment, $attachment,
$cropHorizontal, $crops,
$cropVertical,
); );
} }
} elseif (is_array($cropHorizontal) && is_array($cropVertical)) { } elseif ($crops !== null) {
$attachment = $this->attachmentService->storeCroppedImage( $attachment = $this->attachmentService->storeCroppedImageVariants(
$image, $image,
"tenants/{$tenant->codigo}/extras/{$definition->codigo}", "tenants/{$tenant->codigo}/extras/{$definition->codigo}",
$cropHorizontal, $crops,
$cropVertical,
); );
} else { } else {
$attachment = $this->attachmentService->store( $attachment = $this->attachmentService->store(
@@ -386,4 +383,37 @@ class WebsiteExtraService
return $attachment->id; return $attachment->id;
} }
/**
* Normalize the current variants payload and the original single-crop contract.
*
* @return array<string, array<string, mixed>>|null
*/
private function cropVariants(mixed $value): ?array
{
if (! is_array($value)) {
return null;
}
if (isset($value['crops']) && is_array($value['crops'])) {
return $value['crops'];
}
$horizontal = $value['crop_horizontal'] ?? null;
$vertical = $value['crop_vertical'] ?? null;
if (! is_array($horizontal) || ! is_array($vertical)) {
return null;
}
$crop = [
'crop_horizontal' => $horizontal,
'crop_vertical' => $vertical,
];
return [
'desktop' => $crop,
'mobile' => $crop,
];
}
} }

View File

@@ -0,0 +1,91 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
if (! Schema::hasTable('attachment_crops')) {
Schema::create('attachment_crops', function (Blueprint $table): void {
$table->id();
$table->foreignId('attachment_id')->constrained('attachments')->cascadeOnDelete();
$table->string('variant', 20);
$table->json('crop_horizontal');
$table->json('crop_vertical');
$table->foreignId('cropped_attachment_id')
->unique()
->constrained('attachments')
->cascadeOnDelete();
$table->timestamps();
$table->unique(['attachment_id', 'variant']);
});
}
if (Schema::hasColumn('attachments', 'cropped_attachment_id')) {
DB::table('attachments')
->whereNotNull('cropped_attachment_id')
->orderBy('id')
->chunkById(100, function ($attachments): void {
foreach ($attachments as $attachment) {
DB::table('attachment_crops')->updateOrInsert(
['attachment_id' => $attachment->id, 'variant' => 'desktop'],
[
'crop_horizontal' => $attachment->crop_horizontal
?? json_encode(['start_percentage' => 0, 'end_percentage' => 100]),
'crop_vertical' => $attachment->crop_vertical
?? json_encode(['start_percentage' => 0, 'end_percentage' => 100]),
'cropped_attachment_id' => $attachment->cropped_attachment_id,
'created_at' => now(),
'updated_at' => now(),
]
);
}
});
Schema::table('attachments', function (Blueprint $table): void {
$table->dropForeign(['cropped_attachment_id']);
$table->dropColumn([
'crop_horizontal',
'crop_vertical',
'cropped_attachment_id',
]);
});
}
}
public function down(): void
{
Schema::table('attachments', function (Blueprint $table): void {
$table->json('crop_horizontal')->nullable()->after('size');
$table->json('crop_vertical')->nullable()->after('crop_horizontal');
$table->foreignId('cropped_attachment_id')
->nullable()
->unique()
->after('crop_vertical')
->constrained('attachments')
->nullOnDelete();
});
DB::table('attachment_crops')
->where('variant', 'desktop')
->orderBy('id')
->chunkById(100, function ($crops): void {
foreach ($crops as $crop) {
DB::table('attachments')
->where('id', $crop->attachment_id)
->update([
'crop_horizontal' => $crop->crop_horizontal,
'crop_vertical' => $crop->crop_vertical,
'cropped_attachment_id' => $crop->cropped_attachment_id,
]);
}
});
Schema::dropIfExists('attachment_crops');
}
};

View File

@@ -5,6 +5,7 @@ namespace Tests\Feature\Attachable;
use App\Domains\Attachable\Enums\AttachmentType; use App\Domains\Attachable\Enums\AttachmentType;
use App\Domains\Attachable\Exceptions\AttachmentStorageException; use App\Domains\Attachable\Exceptions\AttachmentStorageException;
use App\Domains\Attachable\Models\Attachment; use App\Domains\Attachable\Models\Attachment;
use App\Domains\Attachable\Models\AttachmentCrop;
use App\Domains\Attachable\Services\AttachmentService; use App\Domains\Attachable\Services\AttachmentService;
use Illuminate\Foundation\Testing\RefreshDatabase; use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Http\UploadedFile; use Illuminate\Http\UploadedFile;
@@ -74,32 +75,45 @@ class AttachmentTest extends TestCase
{ {
Storage::fake('s3'); Storage::fake('s3');
$original = app(AttachmentService::class)->storeCroppedImage( $original = app(AttachmentService::class)->storeCroppedImageVariants(
UploadedFile::fake()->image('product.jpg', 200, 100), UploadedFile::fake()->image('product.jpg', 200, 100),
'attachments/acme', 'attachments/acme',
['start_percentage' => 25, 'end_percentage' => 75], [
['start_percentage' => 10, 'end_percentage' => 85], 'desktop' => [
'crop_horizontal' => ['start_percentage' => 25, 'end_percentage' => 75],
'crop_vertical' => ['start_percentage' => 10, 'end_percentage' => 85],
],
'mobile' => [
'crop_horizontal' => ['start_percentage' => 20, 'end_percentage' => 80],
'crop_vertical' => ['start_percentage' => 0, 'end_percentage' => 100],
],
],
); );
$cropped = $original->croppedAttachment; $desktopCrop = $original->cropVariants->firstWhere('variant', AttachmentCrop::DESKTOP);
$mobileCrop = $original->cropVariants->firstWhere('variant', AttachmentCrop::MOBILE);
$cropped = $desktopCrop->croppedAttachment;
$this->assertNotNull($cropped); $this->assertNotNull($cropped);
$this->assertEquals( $this->assertEquals(
['start_percentage' => 25.0, 'end_percentage' => 75.0], ['start_percentage' => 25.0, 'end_percentage' => 75.0],
$original->crop_horizontal, $desktopCrop->crop_horizontal,
); );
$this->assertEquals( $this->assertEquals(
['start_percentage' => 10.0, 'end_percentage' => 85.0], ['start_percentage' => 10.0, 'end_percentage' => 85.0],
$original->crop_vertical, $desktopCrop->crop_vertical,
); );
$this->assertTrue($cropped->originalAttachment->is($original)); $this->assertTrue($cropped->cropSource->attachment->is($original));
$this->assertDatabaseCount('attachments', 2); $this->assertDatabaseCount('attachments', 3);
$this->assertDatabaseHas('attachments', [ $this->assertDatabaseCount('attachment_crops', 2);
'id' => $original->id, $this->assertDatabaseHas('attachment_crops', [
'attachment_id' => $original->id,
'variant' => AttachmentCrop::DESKTOP,
'cropped_attachment_id' => $cropped->id, 'cropped_attachment_id' => $cropped->id,
]); ]);
Storage::disk('s3')->assertExists($original->path); Storage::disk('s3')->assertExists($original->path);
Storage::disk('s3')->assertExists($cropped->path); Storage::disk('s3')->assertExists($cropped->path);
Storage::disk('s3')->assertExists($mobileCrop->croppedAttachment->path);
$croppedSize = getimagesizefromstring(Storage::disk('s3')->get($cropped->path)); $croppedSize = getimagesizefromstring(Storage::disk('s3')->get($cropped->path));
@@ -113,11 +127,19 @@ class AttachmentTest extends TestCase
Storage::fake('s3'); Storage::fake('s3');
try { try {
app(AttachmentService::class)->storeCroppedImage( app(AttachmentService::class)->storeCroppedImageVariants(
UploadedFile::fake()->image('product.png'), UploadedFile::fake()->image('product.png'),
'attachments/acme', 'attachments/acme',
['start_percentage' => 75, 'end_percentage' => 25], [
['start_percentage' => 0, 'end_percentage' => 100], 'desktop' => [
'crop_horizontal' => ['start_percentage' => 75, 'end_percentage' => 25],
'crop_vertical' => ['start_percentage' => 0, 'end_percentage' => 100],
],
'mobile' => [
'crop_horizontal' => ['start_percentage' => 0, 'end_percentage' => 100],
'crop_vertical' => ['start_percentage' => 0, 'end_percentage' => 100],
],
],
); );
$this->fail('Expected an AttachmentStorageException to be thrown.'); $this->fail('Expected an AttachmentStorageException to be thrown.');
@@ -132,11 +154,10 @@ class AttachmentTest extends TestCase
Storage::fake('s3'); Storage::fake('s3');
try { try {
app(AttachmentService::class)->storeCroppedImage( app(AttachmentService::class)->storeCroppedImageVariants(
UploadedFile::fake()->createWithContent('invalid.png', 'not-an-image'), UploadedFile::fake()->createWithContent('invalid.png', 'not-an-image'),
'attachments/acme', 'attachments/acme',
['start_percentage' => 10, 'end_percentage' => 90], $this->fullCropVariants(),
['start_percentage' => 10, 'end_percentage' => 90],
); );
$this->fail('Expected an AttachmentStorageException to be thrown.'); $this->fail('Expected an AttachmentStorageException to be thrown.');
@@ -150,45 +171,56 @@ class AttachmentTest extends TestCase
{ {
Storage::fake('s3'); Storage::fake('s3');
$original = app(AttachmentService::class)->storeCroppedImage( $original = app(AttachmentService::class)->storeCroppedImageVariants(
UploadedFile::fake()->image('product.png'), UploadedFile::fake()->image('product.png'),
'attachments/acme', 'attachments/acme',
['start_percentage' => 10, 'end_percentage' => 90], $this->fullCropVariants(),
['start_percentage' => 10, 'end_percentage' => 90],
); );
$cropped = $original->croppedAttachment; $cropped = $original->cropVariants->pluck('croppedAttachment');
app(AttachmentService::class)->delete($original); app(AttachmentService::class)->delete($original);
$this->assertDatabaseCount('attachments', 0); $this->assertDatabaseCount('attachments', 0);
Storage::disk('s3')->assertMissing($original->path); Storage::disk('s3')->assertMissing($original->path);
Storage::disk('s3')->assertMissing($cropped->path); foreach ($cropped as $variant) {
Storage::disk('s3')->assertMissing($variant->path);
}
} }
public function test_it_replaces_the_crop_of_an_existing_image(): void public function test_it_replaces_the_crop_of_an_existing_image(): void
{ {
Storage::fake('s3'); Storage::fake('s3');
$original = app(AttachmentService::class)->storeCroppedImage( $original = app(AttachmentService::class)->storeCroppedImageVariants(
UploadedFile::fake()->image('product.jpg', 200, 100), UploadedFile::fake()->image('product.jpg', 200, 100),
'attachments/acme', 'attachments/acme',
['start_percentage' => 0, 'end_percentage' => 100], $this->fullCropVariants(),
['start_percentage' => 0, 'end_percentage' => 100],
); );
$previousCrop = $original->croppedAttachment; $previousCrops = $original->cropVariants->pluck('croppedAttachment');
$updated = app(AttachmentService::class)->updateImageCrop( $updated = app(AttachmentService::class)->updateImageCropVariants(
$original, $original,
['start_percentage' => 25, 'end_percentage' => 75], [
['start_percentage' => 10, 'end_percentage' => 85], 'desktop' => [
'crop_horizontal' => ['start_percentage' => 25, 'end_percentage' => 75],
'crop_vertical' => ['start_percentage' => 10, 'end_percentage' => 85],
],
'mobile' => [
'crop_horizontal' => ['start_percentage' => 30, 'end_percentage' => 70],
'crop_vertical' => ['start_percentage' => 0, 'end_percentage' => 100],
],
],
); );
$this->assertFalse($updated->croppedAttachment->is($previousCrop)); foreach ($previousCrops as $previousCrop) {
$this->assertDatabaseMissing('attachments', ['id' => $previousCrop->id]); $this->assertDatabaseMissing('attachments', ['id' => $previousCrop->id]);
Storage::disk('s3')->assertMissing($previousCrop->path); Storage::disk('s3')->assertMissing($previousCrop->path);
}
$desktop = $updated->cropVariants->firstWhere('variant', AttachmentCrop::DESKTOP);
$croppedSize = getimagesizefromstring( $croppedSize = getimagesizefromstring(
Storage::disk('s3')->get($updated->croppedAttachment->path) Storage::disk('s3')->get($desktop->croppedAttachment->path)
); );
$this->assertIsArray($croppedSize); $this->assertIsArray($croppedSize);
@@ -252,4 +284,14 @@ class AttachmentTest extends TestCase
]); ]);
} }
} }
private function fullCropVariants(): array
{
$crop = [
'crop_horizontal' => ['start_percentage' => 0, 'end_percentage' => 100],
'crop_vertical' => ['start_percentage' => 0, 'end_percentage' => 100],
];
return ['desktop' => $crop, 'mobile' => $crop];
}
} }

View File

@@ -3,6 +3,7 @@
namespace Tests\Feature\Tenant; namespace Tests\Feature\Tenant;
use App\Domains\Attachable\Models\Attachment; use App\Domains\Attachable\Models\Attachment;
use App\Domains\Attachable\Models\AttachmentCrop;
use App\Domains\Auth\Models\User; use App\Domains\Auth\Models\User;
use App\Domains\Authorization\Enums\RoleCode; use App\Domains\Authorization\Enums\RoleCode;
use App\Domains\Tenant\Models\Tenant; use App\Domains\Tenant\Models\Tenant;
@@ -251,62 +252,98 @@ class AdminAppWebsiteExtraControllerTest extends TestCase
'config' => [ 'config' => [
'background_image_id' => [ 'background_image_id' => [
'image' => $image, 'image' => $image,
'crop_horizontal' => [ 'crops' => [
'start_percentage' => 25, 'desktop' => [
'end_percentage' => 75, 'crop_horizontal' => [
], 'start_percentage' => 25,
'crop_vertical' => [ 'end_percentage' => 75,
'start_percentage' => 10, ],
'end_percentage' => 85, 'crop_vertical' => [
'start_percentage' => 10,
'end_percentage' => 85,
],
],
'mobile' => [
'crop_horizontal' => [
'start_percentage' => 30,
'end_percentage' => 70,
],
'crop_vertical' => [
'start_percentage' => 0,
'end_percentage' => 100,
],
],
], ],
], ],
], ],
])->assertOk(); ])->assertOk();
$original = Attachment::query()->whereNotNull('cropped_attachment_id')->sole(); $original = Attachment::query()->whereHas('cropVariants')->sole();
$response $response
->assertJsonPath('data.extras.heroConfig.background_image_id', $original->key) ->assertJsonPath('data.extras.heroConfig.background_image_id', $original->key)
->assertJsonPath( ->assertJsonPath(
'data.resolved_extras.heroConfig.background_image_id.crop_horizontal.start_percentage', 'data.resolved_extras.heroConfig.background_image_id.crops.desktop.crop_horizontal.start_percentage',
25 25
) )
->assertJsonPath( ->assertJsonPath(
'data.resolved_extras.heroConfig.background_image_id.crop_vertical.end_percentage', 'data.resolved_extras.heroConfig.background_image_id.crops.mobile.crop_vertical.end_percentage',
85 100
); );
$this->assertStringContainsString( $this->assertStringContainsString(
$original->key, $original->key,
$response->json('data.resolved_extras.heroConfig.background_image_id.url') $response->json('data.resolved_extras.heroConfig.background_image_id.url')
); );
$this->assertDatabaseCount('attachments', 2); $this->assertDatabaseCount('attachments', 3);
$this->assertDatabaseCount('attachment_crops', 2);
$previousCropId = $original->cropped_attachment_id; $previousCropIds = $original->cropVariants()->pluck('cropped_attachment_id');
$this->putJson('/api/v1/adminapp/tenant/website-extras/heroConfig', [ $this->putJson('/api/v1/adminapp/tenant/website-extras/heroConfig', [
'config' => [ 'config' => [
'background_image_id' => [ 'background_image_id' => [
'image' => $original->key, 'image' => $original->key,
'crop_horizontal' => [ 'crops' => [
'start_percentage' => 10, 'desktop' => [
'end_percentage' => 90, 'crop_horizontal' => [
], 'start_percentage' => 10,
'crop_vertical' => [ 'end_percentage' => 90,
'start_percentage' => 20, ],
'end_percentage' => 80, 'crop_vertical' => [
'start_percentage' => 20,
'end_percentage' => 80,
],
],
'mobile' => [
'crop_horizontal' => [
'start_percentage' => 35,
'end_percentage' => 65,
],
'crop_vertical' => [
'start_percentage' => 0,
'end_percentage' => 100,
],
],
], ],
], ],
], ],
]) ])
->assertOk() ->assertOk()
->assertJsonPath( ->assertJsonPath(
'data.resolved_extras.heroConfig.background_image_id.crop_horizontal.start_percentage', 'data.resolved_extras.heroConfig.background_image_id.crops.desktop.crop_horizontal.start_percentage',
10 10
); );
$this->assertNotSame($previousCropId, $original->refresh()->cropped_attachment_id); $newCropIds = $original->cropVariants()->pluck('cropped_attachment_id');
$this->assertDatabaseMissing('attachments', ['id' => $previousCropId]); $this->assertEmpty($previousCropIds->intersect($newCropIds));
$this->assertDatabaseCount('attachments', 2); foreach ($previousCropIds as $previousCropId) {
$this->assertDatabaseMissing('attachments', ['id' => $previousCropId]);
}
$this->assertDatabaseCount('attachments', 3);
$this->assertDatabaseHas('attachment_crops', [
'attachment_id' => $original->id,
'variant' => AttachmentCrop::MOBILE,
]);
} }
public function test_update_returns_not_found_for_an_unsupported_extra_code(): void public function test_update_returns_not_found_for_an_unsupported_extra_code(): void

View File

@@ -4,6 +4,7 @@ namespace Tests\Feature\Tenant;
use App\Domains\Attachable\Enums\AttachmentType; use App\Domains\Attachable\Enums\AttachmentType;
use App\Domains\Attachable\Models\Attachment; use App\Domains\Attachable\Models\Attachment;
use App\Domains\Attachable\Models\AttachmentCrop;
use App\Domains\Authorization\Enums\RoleCode; use App\Domains\Authorization\Enums\RoleCode;
use App\Domains\Authorization\Models\Role; use App\Domains\Authorization\Models\Role;
use App\Domains\Catalog\Models\Category; use App\Domains\Catalog\Models\Category;
@@ -338,10 +339,18 @@ class BootstrapTenantControllerTest extends TestCase
], ],
], ],
]); ]);
$cropped = Attachment::query()->create([ $desktop = Attachment::query()->create([
'key' => (string) Str::uuid(), 'key' => (string) Str::uuid(),
'path' => 'tenants/acme/cropped.jpg', 'path' => 'tenants/acme/desktop.jpg',
'filename' => 'cropped.jpg', 'filename' => 'desktop.jpg',
'type' => AttachmentType::Image,
'mime_type' => 'image/jpeg',
'extension' => 'jpg',
]);
$mobile = Attachment::query()->create([
'key' => (string) Str::uuid(),
'path' => 'tenants/acme/mobile.jpg',
'filename' => 'mobile.jpg',
'type' => AttachmentType::Image, 'type' => AttachmentType::Image,
'mime_type' => 'image/jpeg', 'mime_type' => 'image/jpeg',
'extension' => 'jpg', 'extension' => 'jpg',
@@ -353,10 +362,15 @@ class BootstrapTenantControllerTest extends TestCase
'type' => AttachmentType::Image, 'type' => AttachmentType::Image,
'mime_type' => 'image/jpeg', 'mime_type' => 'image/jpeg',
'extension' => 'jpg', 'extension' => 'jpg',
'crop_horizontal' => ['start_percentage' => 10, 'end_percentage' => 90],
'crop_vertical' => ['start_percentage' => 20, 'end_percentage' => 80],
'cropped_attachment_id' => $cropped->id,
]); ]);
foreach ([AttachmentCrop::DESKTOP => $desktop, AttachmentCrop::MOBILE => $mobile] as $variant => $crop) {
$original->cropVariants()->create([
'variant' => $variant,
'crop_horizontal' => ['start_percentage' => 10, 'end_percentage' => 90],
'crop_vertical' => ['start_percentage' => 20, 'end_percentage' => 80],
'cropped_attachment_id' => $crop->id,
]);
}
$tenant->websiteExtras()->create([ $tenant->websiteExtras()->create([
'website_type_extra_id' => $heroDefinition->id, 'website_type_extra_id' => $heroDefinition->id,
'config' => ['background_image_id' => $original->id], 'config' => ['background_image_id' => $original->id],
@@ -368,11 +382,9 @@ class BootstrapTenantControllerTest extends TestCase
->assertJsonMissingPath('data.extras.heroConfig.crop_horizontal') ->assertJsonMissingPath('data.extras.heroConfig.crop_horizontal')
->assertJsonMissingPath('data.extras.heroConfig.crop_vertical'); ->assertJsonMissingPath('data.extras.heroConfig.crop_vertical');
$backgroundImage = $response->json('data.extras.heroConfig.background_image_id'); $response
->assertJsonPath('data.extras.heroConfig.background_image_id.desktop', fn (string $url): bool => str_contains($url, 'desktop.jpg'))
$this->assertIsString($backgroundImage); ->assertJsonPath('data.extras.heroConfig.background_image_id.mobile', fn (string $url): bool => str_contains($url, 'mobile.jpg'));
$this->assertStringContainsString('cropped.jpg', $backgroundImage);
$this->assertStringNotContainsString('original.jpg', $backgroundImage);
} }
public function test_it_returns_not_found_when_the_domain_does_not_exist(): void public function test_it_returns_not_found_when_the_domain_does_not_exist(): void