feat(attachment): refactor image cropping functionality to use range objects and update related tests

This commit is contained in:
2026-08-18 12:54:47 -03:00
parent 58cc35fd61
commit 9cfd49f233
16 changed files with 496 additions and 54 deletions

View File

@@ -19,8 +19,8 @@ use Illuminate\Support\Str;
'mime_type',
'extension',
'size',
'crop_horizontal_start_percent',
'crop_vertical_start_percent',
'crop_horizontal',
'crop_vertical',
'cropped_attachment_id',
])]
class Attachment extends Model
@@ -43,8 +43,8 @@ class Attachment extends Model
return [
'type' => AttachmentType::class,
'size' => 'integer',
'crop_horizontal_start_percent' => 'float',
'crop_vertical_start_percent' => 'float',
'crop_horizontal' => 'array',
'crop_vertical' => 'array',
'cropped_attachment_id' => 'integer',
];
}

View File

@@ -17,11 +17,11 @@ class AttachmentService
public function storeCroppedImage(
UploadedFile|string $image,
string $path,
float $horizontalCropPercentage,
float $verticalCropPercentage,
array $cropHorizontal,
array $cropVertical,
): Attachment {
$this->validateCropPercentage($horizontalCropPercentage, 'horizontal');
$this->validateCropPercentage($verticalCropPercentage, 'vertical');
$cropHorizontal = $this->validateCropRange($cropHorizontal, 'horizontal');
$cropVertical = $this->validateCropRange($cropVertical, 'vertical');
$storedPaths = [];
@@ -29,8 +29,8 @@ class AttachmentService
return DB::transaction(function () use (
$image,
$path,
$horizontalCropPercentage,
$verticalCropPercentage,
$cropHorizontal,
$cropVertical,
&$storedPaths,
): Attachment {
$original = $this->store($image, $path);
@@ -38,8 +38,8 @@ class AttachmentService
$croppedContents = $this->cropImage(
$this->imageContents($image),
$horizontalCropPercentage,
$verticalCropPercentage,
$cropHorizontal,
$cropVertical,
);
$cropped = $this->store(
'data:'.$croppedContents['mime_type'].';base64,'.base64_encode($croppedContents['contents']),
@@ -48,8 +48,8 @@ class AttachmentService
$storedPaths[] = $cropped->path;
$original->update([
'crop_horizontal_start_percent' => $horizontalCropPercentage,
'crop_vertical_start_percent' => $verticalCropPercentage,
'crop_horizontal' => $cropHorizontal,
'crop_vertical' => $cropVertical,
'cropped_attachment_id' => $cropped->id,
]);
@@ -64,6 +64,51 @@ class AttachmentService
}
}
public function updateImageCrop(
Attachment $original,
array $cropHorizontal,
array $cropVertical,
): 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');
$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,
);
try {
$original->update([
'crop_horizontal' => $cropHorizontal,
'crop_vertical' => $cropVertical,
'cropped_attachment_id' => $cropped->id,
]);
} catch (Throwable $throwable) {
$this->delete($cropped);
throw $throwable;
}
if ($previousCrop !== null && ! $previousCrop->is($cropped)) {
$this->delete($previousCrop);
}
return $original->refresh()->load('croppedAttachment');
}
public function store(
UploadedFile|string $file,
string $path,
@@ -168,13 +213,34 @@ class AttachmentService
return trim($path, '/');
}
protected function validateCropPercentage(float $percentage, string $axis): void
/**
* @param array{start_percentage?: mixed, end_percentage?: mixed} $range
* @return array{start_percentage: float, end_percentage: float}
*/
protected function validateCropRange(array $range, string $axis): array
{
if (! is_finite($percentage) || $percentage < 0 || $percentage >= 100) {
$start = $range['start_percentage'] ?? null;
$end = $range['end_percentage'] ?? null;
if (! is_numeric($start) || ! is_numeric($end)) {
throw new AttachmentStorageException(
"The {$axis} crop percentage must be greater than or equal to 0 and less than 100."
"The {$axis} crop range must contain numeric start_percentage and end_percentage values."
);
}
$start = (float) $start;
$end = (float) $end;
if (! is_finite($start) || ! is_finite($end) || $start < 0 || $end > 100 || $start >= $end) {
throw new AttachmentStorageException(
"The {$axis} crop range must satisfy 0 <= start_percentage < end_percentage <= 100."
);
}
return [
'start_percentage' => $start,
'end_percentage' => $end,
];
}
protected function imageContents(UploadedFile|string $image): string
@@ -197,8 +263,8 @@ class AttachmentService
*/
protected function cropImage(
string $contents,
float $horizontalCropPercentage,
float $verticalCropPercentage,
array $cropHorizontal,
array $cropVertical,
): array {
$source = @imagecreatefromstring($contents);
@@ -208,13 +274,15 @@ class AttachmentService
$width = imagesx($source);
$height = imagesy($source);
$x = min($width - 1, (int) floor($width * $horizontalCropPercentage / 100));
$y = min($height - 1, (int) floor($height * $verticalCropPercentage / 100));
$x = min($width - 1, (int) floor($width * $cropHorizontal['start_percentage'] / 100));
$right = min($width, (int) ceil($width * $cropHorizontal['end_percentage'] / 100));
$y = min($height - 1, (int) floor($height * $cropVertical['start_percentage'] / 100));
$bottom = min($height, (int) ceil($height * $cropVertical['end_percentage'] / 100));
$cropped = imagecrop($source, [
'x' => $x,
'y' => $y,
'width' => $width - $x,
'height' => $height - $y,
'width' => $right - $x,
'height' => $bottom - $y,
]);
if ($cropped === false) {

View File

@@ -25,8 +25,8 @@ No expone rutas HTTP propias. Lo consumen otros dominios, especialmente `Catalog
## Consideraciones
- El directorio no puede quedar vacío después de normalizarlo.
- Los porcentajes de inicio del crop deben estar en el rango `[0, 100)`; el recorte se extiende desde ese punto hasta los bordes derecho e inferior.
- El attachment original guarda los porcentajes y la relación `croppedAttachment` con la versión procesada.
- 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.
- Al eliminar el original mediante el servicio también se elimina su versión recortada.
- La eliminación se considera fallida si S3 no confirma el borrado.
- Las URL generadas son temporales; el vencimiento predeterminado es de 10 minutos.

View File

@@ -0,0 +1,68 @@
<?php
namespace App\Domains\Shared\Rules;
use Closure;
use Illuminate\Contracts\Validation\ValidationRule;
class CroppedImageOrBase64Rule implements ValidationRule
{
public function validate(string $attribute, mixed $value, Closure $fail): void
{
if (! is_array($value)) {
(new ImageOrBase64Rule)->validate($attribute, $value, $fail);
return;
}
if (! array_key_exists('image', $value)) {
$fail('The :attribute.image field is required.');
return;
}
$valid = true;
(new ImageOrBase64Rule)->validate(
"{$attribute}.image",
$value['image'],
function (string $message) use ($fail, &$valid): void {
$valid = false;
$fail($message);
}
);
if (! $valid) {
return;
}
$this->validateRange($attribute, 'crop_horizontal', $value, $fail);
$this->validateRange($attribute, 'crop_vertical', $value, $fail);
}
private function validateRange(string $attribute, string $axis, array $value, Closure $fail): void
{
$range = $value[$axis] ?? null;
if (! is_array($range)) {
$fail("The :attribute.{$axis} field must be an object.");
return;
}
$start = $range['start_percentage'] ?? null;
$end = $range['end_percentage'] ?? null;
if (
! is_numeric($start)
|| ! is_numeric($end)
|| (float) $start < 0
|| (float) $end > 100
|| (float) $start >= (float) $end
) {
$fail(
"The :attribute.{$axis} field must satisfy "
.'0 <= start_percentage < end_percentage <= 100.'
);
}
}
}

View File

@@ -29,12 +29,35 @@ class WebsiteExtraResource extends JsonResource
fn (Attachment $attachment): string => $attachment->key
),
'resolved_config' => $this->formatConfig(
$this->resolvedConfig(),
$this->resolvedAdminConfig(),
fn (Attachment $attachment): string => $attachment->getTemporaryUrl(1440)
),
];
}
private function resolvedAdminConfig(): mixed
{
$config = $this->resolvedConfig();
if (
$this->websiteTypeExtra->codigo !== 'heroConfig'
|| ! is_array($config)
|| ! ($config['background_image_id'] ?? null) instanceof Attachment
) {
return $config;
}
$attachment = $config['background_image_id'];
$fullRange = ['start_percentage' => 0.0, 'end_percentage' => 100.0];
$config['background_image_id'] = [
'url' => $attachment->getTemporaryUrl(1440),
'crop_horizontal' => $attachment->crop_horizontal ?? $fullRange,
'crop_vertical' => $attachment->crop_vertical ?? $fullRange,
];
return $config;
}
private function formatConfig(mixed $value, callable $formatAttachment): mixed
{
if ($value instanceof Attachment) {

View File

@@ -45,14 +45,44 @@ class WebsiteExtrasResource extends JsonResource
),
]),
'resolved_extras' => $websiteExtras->mapWithKeys(fn ($extra) => [
$extra->websiteTypeExtra->codigo => $this->formatConfig(
$extra->resolvedConfig(),
fn (Attachment $attachment): string => $attachment->getTemporaryUrl(1440)
),
$extra->websiteTypeExtra->codigo => $this->formatResolvedConfig($extra),
]),
];
}
private function formatResolvedConfig(mixed $extra): mixed
{
$config = $extra->resolvedConfig();
if (
$extra->websiteTypeExtra->codigo === 'heroConfig'
&& is_array($config)
&& ($config['background_image_id'] ?? null) instanceof Attachment
) {
$attachment = $config['background_image_id'];
$config['background_image_id'] = $this->formatHeroAttachment($attachment);
}
return $this->formatConfig(
$config,
fn (Attachment $attachment): string => $attachment->getTemporaryUrl(1440)
);
}
/**
* @return array{url: string, crop_horizontal: array<string, float>, crop_vertical: array<string, float>}
*/
private function formatHeroAttachment(Attachment $attachment): array
{
$fullRange = ['start_percentage' => 0.0, 'end_percentage' => 100.0];
return [
'url' => $attachment->getTemporaryUrl(1440),
'crop_horizontal' => $attachment->crop_horizontal ?? $fullRange,
'crop_vertical' => $attachment->crop_vertical ?? $fullRange,
];
}
private function formatConfig(mixed $value, callable $formatAttachment): mixed
{
if ($value instanceof Attachment) {

View File

@@ -98,7 +98,7 @@ class TenantResource extends JsonResource
private function formatExtraConfig(mixed $value): mixed
{
if ($value instanceof Attachment) {
return $value->getTemporaryUrl(1440);
return ($value->croppedAttachment ?? $value)->getTemporaryUrl(1440);
}
if (! is_array($value)) {

View File

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

View File

@@ -5,6 +5,7 @@ namespace App\Domains\Tenant\Services;
use App\Domains\Attachable\Enums\AttachmentType;
use App\Domains\Attachable\Models\Attachment;
use App\Domains\Attachable\Services\AttachmentService;
use App\Domains\Shared\Rules\CroppedImageOrBase64Rule;
use App\Domains\Shared\Rules\ImageOrBase64Rule;
use App\Domains\Tenant\Models\Tenant;
use App\Domains\Tenant\Models\WebsiteExtra;
@@ -222,9 +223,11 @@ class WebsiteExtraService
$compiled = is_string($rules) ? explode('|', $rules) : $rules;
return array_map(
fn (mixed $rule): mixed => $rule === 'image_or_base64'
? new ImageOrBase64Rule
: $rule,
fn (mixed $rule): mixed => match ($rule) {
'image_or_base64' => new ImageOrBase64Rule,
'cropped_image_or_base64' => new CroppedImageOrBase64Rule,
default => $rule,
},
$compiled
);
}
@@ -331,8 +334,12 @@ class WebsiteExtraService
);
}
if (is_string($value) && Str::isUuid($value)) {
$attachment = Attachment::query()->where('key', $value)->first();
$cropHorizontal = is_array($value) ? $value['crop_horizontal'] ?? null : null;
$cropVertical = is_array($value) ? $value['crop_vertical'] ?? null : null;
$image = is_array($value) ? $value['image'] ?? null : $value;
if (is_string($image) && Str::isUuid($image)) {
$attachment = Attachment::query()->where('key', $image)->first();
if (! $attachment) {
throw ValidationException::withMessages([
@@ -341,9 +348,24 @@ class WebsiteExtraService
],
]);
}
if (is_array($cropHorizontal) && is_array($cropVertical)) {
$attachment = $this->attachmentService->updateImageCrop(
$attachment,
$cropHorizontal,
$cropVertical,
);
}
} elseif (is_array($cropHorizontal) && is_array($cropVertical)) {
$attachment = $this->attachmentService->storeCroppedImage(
$image,
"tenants/{$tenant->codigo}/extras/{$definition->codigo}",
$cropHorizontal,
$cropVertical,
);
} else {
$attachment = $this->attachmentService->store(
$value,
$image,
"tenants/{$tenant->codigo}/extras/{$definition->codigo}"
);
}