duancheng7743 2015-06-16 22:22
浏览 57
已采纳

性能是否可以使用PHP array_keys和array_diff函数来验证JSON的字段?

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?

  • 写回答

1条回答 默认 最新

  • duannian7116 2015-06-17 00:33
    关注

    Since your JSON is returning objects I would suggest that you use the property_exists() function to determine if the object has a certain property (field in your terms).

    you will have to keep an array of VALID or REQUIRED fields such as the following.

    <?php
    $required = ('nombre', 'apellidos');
    
    foreach($required_fields as $required) {
        if(property_exists($campos, $required) {
            // the field exists, do what you want
        } else {
           // the field does not exist throw exception
           throw new Exception('Whoops the field '.$required.' does not exist in the response from the server.';
        }
    

    Surely using one function call vs two function calls would be better for performance.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 求螺旋焊缝的图像处理
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案
  • ¥50 yalmip+Gurobi
  • ¥20 win10修改放大文本以及缩放与布局后蓝屏无法正常进入桌面
  • ¥15 itunes恢复数据最后一步发生错误
  • ¥15 关于#windows#的问题:2024年5月15日的win11更新后资源管理器没有地址栏了顶部的地址栏和文件搜索都消失了