I'm developing some API methods, it's required to take seriously validation of the input data and performance (because there will be hundreds of API clients with thousands of records being queried and updated)
As a sample here is some code to see how I use array_diff and array_key functions to validate the decoded object from the JSON (that the API client sends in the HTTP request body) has valid fields:
// Obtener campos
$humano = file_get_contents('php://input');
$campos = json_decode($humano, true);
if (!is_array($campos))
{
throw new ExcepcionApi(400, 'ERR_C_HUM_CREAR_001',
'Petición inválida al tratar de crear un nuevo cliente ',
'El campo POST "cliente" no contiene JSON válido, para '
. 'que pueda ser registrado el cliente se necesita '
. 'que el objeto esté en la raíz del documento JSON.');
}
// Definir campos permitidos y requeridos
$campos_permitidos = [
'id', 'cuenta_id', 'nombre', 'apellidos', 'sexo',
'codigo_postal', 'email', 'telefono', 'celular',
'direccion', 'ciudad', 'empresa', 'fecha_creacion', 'fecha_modificacion',
];
$campos_requeridos = [
'nombre', 'apellidos', 'email',
];
$campos_recibidos = array_keys($campos);
// Verificar que sólo se definan campos permitidos
$campos_ilegales = array_diff($campos_recibidos, $campos_permitidos);
if (!empty($campos_ilegales))
{
throw new ExcepcionApi(400, 'ERR_C_HUM_CREAR_002',
'Petición inválida al tratar de crear un nuevo cliente ',
'El campo POST "cliente" contiene JSON válido, pero '
. 'los siguientes campos no pueden ser parte del objeto: '
. implode(', ', $campos_ilegales) . '.');
}
// Verificar que cada campo requerido exista en $campos
$campos_faltantes = array_diff($campos_requeridos, $campos_recibidos);
if (!empty($campos_faltantes))
{
throw new ExcepcionApi(400, 'ERR_C_HUM_CREAR_003',
'Petición inválida al tratar de crear un nuevo cliente ',
'El campo POST "cliente" contiene JSON válido, pero '
. 'los siguientes campos hacen falta en el objeto: '
. implode(', ', $campos_faltantes) . '.');
}
foreach ($campos_requeridos as $requerido)
{
if (strlen($campos[$requerido]) === 0)
{
throw new ExcepcionApi(400, 'ERR_C_HUM_CREAR_004',
'Petición inválida al tratar de crear un nuevo cliente ',
'El campo POST "cliente" contiene JSON válido, pero '
. "el campo requerido '$requerido' tiene un valor vacío. "
. 'Los siguientes campos son requeridos: '
. implode(', ', $campos_requeridos) . '.');
}
}
The previous code that validates the input before creating a row in the database would accept this JSON for example:
{
"nombre":"Juan",
"apellidos":"Castellon",
"sexo":null,
"codigo_postal":"13061",
"email":"juan.castellon@yopmail.com",
"telefono":"8877994",
"celular":null,
"direccion":null,
"ciudad":"Managua",
"empresa":"EL UNIVERSO INC."
}
This would not be accepted (because missing required fields): { "nombre":"Juan", "apellidos":"Castellon" }
This would not be accepted (because having non existent fields):
{
"nombre":"Juan",
"apellidos":"Castellon"
}
Is it right the use of array_diff and array_key from a performance point of view?