feat(category): implement category configuration management with sorting and validation
This commit is contained in:
@@ -0,0 +1,69 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Commerce\Catalog\Requests\AdminApp;
|
||||
|
||||
use App\Shared\Rules\ImageOrBase64Rule;
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
use Illuminate\Support\Facades\Validator;
|
||||
use Illuminate\Validation\Validator as ValidationValidator;
|
||||
|
||||
class UpdateCategoryConfigurationRequest extends FormRequest
|
||||
{
|
||||
public function authorize(): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
public function rules(): array
|
||||
{
|
||||
return [
|
||||
'categories' => ['present', 'array', 'max:500'],
|
||||
'deleted_ids' => ['present', 'array', 'max:1000'],
|
||||
'deleted_ids.*' => ['required', 'integer', 'min:1', 'distinct'],
|
||||
];
|
||||
}
|
||||
|
||||
public function withValidator(ValidationValidator $validator): void
|
||||
{
|
||||
$validator->after(function (ValidationValidator $validator): void {
|
||||
if ($validator->errors()->isNotEmpty()) {
|
||||
return;
|
||||
}
|
||||
$this->validateNodes($validator, $this->input('categories'), 'categories', 0);
|
||||
});
|
||||
}
|
||||
|
||||
private function validateNodes(ValidationValidator $validator, array $nodes, string $path, int $depth): void
|
||||
{
|
||||
if ($depth > 10) {
|
||||
$validator->errors()->add($path, 'La jerarquía de categorías es demasiado profunda.');
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
foreach ($nodes as $index => $node) {
|
||||
$key = "{$path}.{$index}";
|
||||
if (! is_array($node)) {
|
||||
$validator->errors()->add($key, 'La categoría debe ser un objeto.');
|
||||
|
||||
continue;
|
||||
}
|
||||
$nested = Validator::make($node, [
|
||||
'id' => ['present', 'nullable', 'integer', 'min:1'],
|
||||
'nombre' => ['required', 'string', 'max:255'],
|
||||
'is_enabled' => ['required', 'boolean'],
|
||||
'banner_enabled' => ['required', 'boolean'],
|
||||
'banner' => ['present', 'nullable', new ImageOrBase64Rule],
|
||||
'subcategories' => ['present', 'array', 'max:500'],
|
||||
]);
|
||||
foreach ($nested->errors()->messages() as $field => $messages) {
|
||||
foreach ($messages as $message) {
|
||||
$validator->errors()->add("{$key}.{$field}", $message);
|
||||
}
|
||||
}
|
||||
if (! $nested->fails()) {
|
||||
$this->validateNodes($validator, $node['subcategories'], "{$key}.subcategories", $depth + 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user