简体   繁体   English

验证数据,如何将空类型计数为字符串类型

[英]Verify data, how can I make null type count as string type

I'm trying to verify data from users before inserting it into DB. 我试图在将用户的数据插入数据库之前对其进行验证。 I have an array of a list of fields with various field types those input data has to be. 我有一个字段列表数组,其中包含输入数据必须具有的各种字段类型。

Example: 例:

$fields = ['id' => 'integer', 'contents' => 'string', 'display' => 'boolean'];

So, if a user wants to do a POST request, the user needs to supply all the required fields first, then those fields has to of the correct type. 因此,如果用户想要发出POST请求,则用户需要首先提供所有必填字段,然后这些字段必须为正确的类型。

Example: 例:

$data = ['id' => 123, 'contents' => 'hello', 'display' => true];

In the list of fields I have some type values set as 'string' . 在字段列表中,我将一些类型值设置为'string' The problem is that I want all those 'string' values to also include null value types that the user might provide. 问题是我希望所有这些'string'值也包括用户可能提供的null值类型。

Here's my gist of the function and some tests . 这是我的功能要点和一些测试

<?php

function verifyData (array $fields, array $data, array $excludeFields = []) {
  $array = [
    'data'  => [],
    'debug' => []
  ];

  foreach ($fields as $key => $value) {
    // If key is in exclude: ignore field
    if (!empty($excludeFields) && in_array($key, $excludeFields)) {
      continue;
    }

    $type = gettype($data[$key]);

    // How can I make null count as a string?
    // If data type is null, and it's field value is a string it should NOT get added to $array['data']
    if ($type !== $value || ($value === 'string' && is_null($data[$key]))) {
      $array['data'][] = [
        'field'   => $key,
        'message' => "Type of '$key' field is incorrect. Current type is: '$type', it should be: '$value'"
      ];
    } else {
      $array['debug'][] = "$key, $type, $value";
    }
  }

  print_r($array);
  echo '<hr>';

  // return $array;
}



// -----------------------------------------------------------------------------
// Tests
// -----------------------------------------------------------------------------
echo '<pre>';

// -----------------------------------------------------------------------------

$fields  = ['id' => 'integer', 'contents' => 'string', 'display' => 'boolean'];
$data    = ['id' => 123,       'contents' => 'hello',  'display' => true];
$exclude = [];

echo 'Output OK <br>';
verifyData($fields, $data, $exclude);

// -----------------------------------------------------------------------------

$fields  = ['id' => 'integer', 'contents' => 'string', 'display' => 'boolean'];
$data    = ['id' => 123,       'contents' => 'hi',     'display' => true];
$exclude = ['id'];

echo 'Output OK - Field "id" is excluded from debug output <br>';
verifyData($fields, $data, $exclude);

// -----------------------------------------------------------------------------

$fields  = ['id' => 'integer', 'contents' => 'string', 'display' => 'boolean'];
$data    = ['id' => 123,       'contents' => 123,      'display' => true];
$exclude = [];

echo 'Output OK - Field "contents" should not be an integer <br>';
verifyData($fields, $data, $exclude);

// -----------------------------------------------------------------------------

$fields  = ['id' => 'integer', 'contents' => 'string', 'display' => 'boolean'];
$data    = ['id' => 123,       'contents' => null,     'display' => true];
$exclude = [];

echo 'Output failed - Field "contents" should be in the debug output (null should be counted as a string) <br>';
verifyData($fields, $data, $exclude);

I hope I've made myself clear on the problem (English isn't my main language). 我希望我已经清楚地说明了这个问题(英语不是我的主要语言)。


(Optional reading) My entire workflow right now: (可选阅读)我现在的整个工作流程:

I'm using Slim Framework to handle requests and response. 我正在使用Slim Framework处理请求和响应。

A user does a POST request with a JSON body (with header 'Content-Type' set to 'application/json;charset=utf-8' ): 用户使用JSON正文(标头'Content-Type'设置为'application/json;charset=utf-8' )执行POST请求:

{"contents": "Some text", "display": true}

I handle the body data and use json_decode($body, true) to convert it to php array. 我处理主体数据,并使用json_decode($body, true)将其转换为php数组。

I use that array to verify it's data types by comparing it to the $fields example I provided before to check if the body data is of the correct type. 我使用该数组,通过将其与我之前提供的$fields示例进行比较来验证其数据类型,以检查主体数据是否为正确的类型。

If any of them were not of the correct type, I throw an Exception and the users gets a response with all the errors (see below). 如果其中任何一个不是正确的类型,我都会抛出一个Exception,并且用户会收到一个包含所有错误的响应(请参见下文)。

If the user had posted for example: 例如,如果用户已发布:

{"contents": null, "display": true}

Currently the user will get this response: 目前,用户将收到以下响应:

{
  "status": 400,
  "data": {
    "type": "invalid_request_error",
    "message": "Malformed request: Field(s) doesn't match the required type",
    "code": 203,
    "errors": [
      {
        "field": "contents",
        "message": "Type of 'contents' field is incorrect. Current type is: 'NULL', it should be: 'string'"
      }
    ]
  }
}

I want the verification to handle null's as a string, making the above error message not to appear and everything is OK, resulting in something like this: 我希望验证将null当作字符串来处理,从而使上述错误消息不出现并且一切正常,结果如下所示:

{
  "status": 201,
  "data": {
    "id": 1,
    "contents": null,
    "display": true
  }
}

您为什么不这样做:遍历所有元素,如果一个元素为null,则将其更改为“ null”(字符串),另一方面,将其更改回。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如果在wordpress中show_count小于2,如何使输出显示Type而不是Types - How can I make my output say Type and not Types if show_count is less than 2 in wordpress 如何将此字符串类型变量转换为数组类型? - How can i convert this string type variable in array type? 如何让字符串类型变成数组类型 - How to Make String Type Become Array Type 使用 null 合并运算符时如何键入 cast? - How can I type cast when using the null coalescing operator? 如何从 PHP 中任何图像类型的 base64 字符串中去除 data:image 部分 - How can I strip the data:image part from a base64 string of any image type in PHP 我如何在 PHP 中从 JSON 数据字符串转换为浮点数或数字类型 - How i can convert from JSON data string to float or number type in PHP 当没有选择文件时,如何使输入类型文件发送空字符串而不是null - How to make input type file send empty string instead of null when no file is selected 如何在PHP中创建类型为“ class”的数组? - How can I make an array of type “class” in PHP? 在PHP类中,如何使变量成为特定类型? - In a PHP class, how can I make it so that the variables are a specific type? 如何将字符串添加到具有html的数据类型? - How do i add a string to a data type that had html?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM