0 && strlen($s) < $min) { json_error('INVALID_FIELD', "$fieldName must be at least $min characters", 400); } if ($max > 0 && strlen($s) > $max) { json_error('INVALID_FIELD', "$fieldName must be at most $max characters", 400); } return $s; } /** * Validate that a value is one of the allowed options. * Returns the value or calls json_error. */ function validate_enum(mixed $value, string $fieldName, array $allowed): string { $s = trim((string)$value); if (!in_array($s, $allowed, true)) { json_error('INVALID_FIELD', "$fieldName must be one of: " . implode(', ', $allowed), 400); } return $s; } /** * Validate and return an integer from body, with optional min/max bounds. */ function validate_int(mixed $value, string $fieldName, ?int $min = null, ?int $max = null): int { $i = (int)$value; if ($min !== null && $i < $min) { json_error('INVALID_FIELD', "$fieldName must be at least $min", 400); } if ($max !== null && $i > $max) { json_error('INVALID_FIELD', "$fieldName must be at most $max", 400); } return $i; } /** * Require the request method to match, or exit with 405. */ function require_method(string ...$allowed): void { $method = $_SERVER['REQUEST_METHOD']; if (!in_array($method, $allowed, true)) { json_error('METHOD_NOT_ALLOWED', 'Method not allowed', 405); } }