Last active
February 19, 2026 19:49
-
-
Save pazteddy/a3cfa6a6a4f7dbe76a90b00e782b8925 to your computer and use it in GitHub Desktop.
Generación de identificador único y validación de campos
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?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