Refactor request validation to use model-specific prop synchronization and add migrations for categories and brands
This commit is contained in:
@@ -2,16 +2,59 @@
|
||||
|
||||
namespace App\Domains\Prop\Support;
|
||||
|
||||
use App\Domains\Prop\Models\Prop;
|
||||
use Closure;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
|
||||
class PropRules
|
||||
{
|
||||
/**
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public static function sync(): array
|
||||
public static function sync(string $modelClass): array
|
||||
{
|
||||
return [
|
||||
'props' => ['sometimes', 'array'],
|
||||
'props' => [
|
||||
'sometimes',
|
||||
'array',
|
||||
static function (string $attribute, mixed $value, Closure $fail) use ($modelClass): void {
|
||||
static::validatePropsForModel($attribute, $value, $fail, $modelClass);
|
||||
},
|
||||
],
|
||||
'props.*' => ['nullable'],
|
||||
];
|
||||
}
|
||||
|
||||
protected static function validatePropsForModel(string $attribute, mixed $value, Closure $fail, string $modelClass): void
|
||||
{
|
||||
if (! is_array($value) || $value === []) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (! is_subclass_of($modelClass, Model::class)) {
|
||||
$fail("The {$attribute} field references an invalid propable model.");
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$propCodes = array_map('strval', array_keys($value));
|
||||
$existingPropCodes = Prop::query()
|
||||
->forModel($modelClass)
|
||||
->whereIn('codigo', $propCodes)
|
||||
->pluck('codigo')
|
||||
->all();
|
||||
|
||||
$missingPropCodes = array_values(array_diff($propCodes, $existingPropCodes));
|
||||
|
||||
if ($missingPropCodes === []) {
|
||||
return;
|
||||
}
|
||||
|
||||
$fail(sprintf(
|
||||
'The selected %s are invalid for %s: %s.',
|
||||
$attribute,
|
||||
class_basename($modelClass),
|
||||
implode(', ', $missingPropCodes),
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user