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

@@ -5,6 +5,7 @@ namespace App\Domains\Attachable\Services;
use App\Domains\Attachable\Enums\AttachmentType;
use App\Domains\Attachable\Exceptions\AttachmentStorageException;
use App\Domains\Attachable\Models\Attachment;
use App\Domains\Attachable\Models\AttachmentCrop;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
@@ -14,46 +15,40 @@ use Throwable;
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,
string $path,
array $cropHorizontal,
array $cropVertical,
array $crops,
): Attachment {
$cropHorizontal = $this->validateCropRange($cropHorizontal, 'horizontal');
$cropVertical = $this->validateCropRange($cropVertical, 'vertical');
$crops = $this->validateCropVariants($crops);
$storedPaths = [];
try {
return DB::transaction(function () use (
$image,
$path,
$cropHorizontal,
$cropVertical,
$crops,
&$storedPaths,
): Attachment {
$original = $this->store($image, $path);
$storedPaths[] = $original->path;
$contents = $this->imageContents($image);
$croppedContents = $this->cropImage(
$this->imageContents($image),
$cropHorizontal,
$cropVertical,
);
$cropped = $this->store(
'data:'.$croppedContents['mime_type'].';base64,'.base64_encode($croppedContents['contents']),
$path,
);
$storedPaths[] = $cropped->path;
foreach ($crops as $variant => $crop) {
$cropped = $this->storeCropVariant($contents, $path, $crop);
$storedPaths[] = $cropped->path;
$original->cropVariants()->create([
'variant' => $variant,
'crop_horizontal' => $crop['crop_horizontal'],
'crop_vertical' => $crop['crop_vertical'],
'cropped_attachment_id' => $cropped->id,
]);
}
$original->update([
'crop_horizontal' => $cropHorizontal,
'crop_vertical' => $cropVertical,
'cropped_attachment_id' => $cropped->id,
]);
return $original->load('croppedAttachment');
return $original->load('cropVariants.croppedAttachment');
});
} catch (Throwable $throwable) {
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,
array $cropHorizontal,
array $cropVertical,
array $crops,
): Attachment {
if ($original->type !== AttachmentType::Image) {
throw new AttachmentStorageException('Only image attachments can be cropped.');
}
$cropHorizontal = $this->validateCropRange($cropHorizontal, 'horizontal');
$cropVertical = $this->validateCropRange($cropVertical, 'vertical');
$crops = $this->validateCropVariants($crops);
$contents = Storage::disk('s3')->get($original->path);
if (! is_string($contents) || $contents === '') {
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 = $directory !== '' ? $directory : 'attachments';
$previousCrop = $original->croppedAttachment;
$cropped = $this->store(
'data:'.$croppedContents['mime_type'].';base64,'.base64_encode($croppedContents['contents']),
$directory,
);
$previousCrops = $original->cropVariants()->with('croppedAttachment')->get();
$storedCrops = [];
try {
$original->update([
'crop_horizontal' => $cropHorizontal,
'crop_vertical' => $cropVertical,
'cropped_attachment_id' => $cropped->id,
]);
foreach ($crops as $variant => $crop) {
$storedCrops[$variant] = $this->storeCropVariant($contents, $directory, $crop);
}
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) {
$this->delete($cropped);
foreach ($storedCrops as $storedCrop) {
$this->delete($storedCrop);
}
throw $throwable;
}
if ($previousCrop !== null && ! $previousCrop->is($cropped)) {
$this->delete($previousCrop);
foreach ($previousCrops as $previousCrop) {
if ($previousCrop->croppedAttachment !== null) {
$this->delete($previousCrop->croppedAttachment);
}
}
return $original->refresh()->load('croppedAttachment');
return $original->refresh()->load('cropVariants.croppedAttachment');
}
public function store(
@@ -153,11 +160,18 @@ class AttachmentService
public function delete(Attachment $attachment): void
{
$croppedAttachment = $attachment->croppedAttachment;
$paths = array_values(array_filter([
$attachment->path,
$croppedAttachment?->path,
]));
$croppedAttachments = $attachment->cropVariants()
->with('croppedAttachment')
->get()
->pluck('croppedAttachment')
->filter();
$paths = $croppedAttachments
->pluck('path')
->prepend($attachment->path)
->filter()
->unique()
->values()
->all();
$deleted = Storage::disk('s3')->delete(
count($paths) === 1 ? $paths[0] : $paths
);
@@ -166,9 +180,9 @@ class AttachmentService
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();
$croppedAttachment?->delete();
Attachment::query()->whereKey($croppedAttachments->pluck('id'))->delete();
});
}
@@ -213,6 +227,56 @@ class AttachmentService
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
* @return array{start_percentage: float, end_percentage: float}