Skip to content

Instantly share code, notes, and snippets.

@pazteddy
Last active February 19, 2026 19:49
Show Gist options
  • Select an option

  • Save pazteddy/a3cfa6a6a4f7dbe76a90b00e782b8925 to your computer and use it in GitHub Desktop.

Select an option

Save pazteddy/a3cfa6a6a4f7dbe76a90b00e782b8925 to your computer and use it in GitHub Desktop.
Generación de identificador único y validación de campos
<?php
function nextId(array $products): int
{
$maxId = 0;
foreach ($products as $product) {
$maxId = max($maxId, (int)($product["id"] ?? 0));
}
return $maxId + 1;
}
function validateProductPayload(array $data, bool $isCreate, bool $requireAllFields = false): array
{
$errors = [];
$mustHaveAll = $isCreate || $requireAllFields;
$fields = [
"name" => [
"requiredMessage" => "El nombre es obligatorio",
"rules" => function ($value) use (&$errors) {
$value = trim((string)$value);
if ($value === "") {
$errors[] = "El nombre no puede estar vacío";
}
if (mb_strlen($value) < 2) {
$errors[] = "El nombre debe tener al menos 2 caracteres";
}
}
]
];
foreach ($fields as $field => $config) {
if ($mustHaveAll && !array_key_exists($field, $data)) {
$errors[] = $config["requiredMessage"];
continue;
}
if (array_key_exists($field, $data)) {
$config["rules"]($data[$field]);
}
}
return $errors;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment