【问题标题】:Verify data, how can I make null type count as string type验证数据,如何将空类型计为字符串类型
【发布时间】:2015-10-23 17:36:23
【问题描述】:

我正在尝试在将用户数据插入数据库之前对其进行验证。我有一个字段列表的数组,其中包含输入数据必须是的各种字段类型。

例子:

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

因此,如果用户想要进行 POST 请求,则用户需要先提供所有必需的字段,然后这些字段必须是正确的类型。

例子:

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

在字段列表中,我将一些类型值设置为'string'。问题是我希望所有这些 '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);

我希望我已经明确了这个问题(英语不是我的主要语言)。


(可选阅读)我现在的整个工作流程:

我正在使用Slim Framework 来处理请求和响应。

用户使用 JSON 正文发出 POST 请求(标头 'Content-Type' 设置为 'application/json;charset=utf-8'):

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

我处理正文数据并使用json_decode($body, true)将其转换为php数组。

我使用该数组来验证它的数据类型,方法是将它与我​​之前提供的 $fields 示例进行比较,以检查正文数据是否属于正确类型。

如果其中任何一个类型不正确,我会抛出一个异常,并且用户会收到包含所有错误的响应(见下文)。

如果用户发布了例如:

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

目前用户会收到这样的回复:

{
  "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'"
      }
    ]
  }
}

我希望验证将null作为字符串处理,使上述错误消息不出现并且一切正常,结果如下:

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

【问题讨论】:

  • 注意:如果你把null变成一个字符串,它很可能不会作为null进入数据库;它可能会以字符串“null”的形式出现,我相信你不会。将空值保留为空值是有充分理由的
  • 我不会将任何空值转换为字符串。我想检查数据值的类型是否为 null 并将其作为字符串处理,因此它不应该导致任何错误。在我的 $fields 数组中,不是说“字符串”,而是说“空”。但我也使用 $fields 来检查其他一些东西,所以我不能这样做。
  • 你能做类似if ($value==null) {$value = 'null';}的事情吗?
  • 你可以在你的第一个 foreach 循环中尝试上述方法,而不是排除它吗?正如下面的答案所建议的(没有真正解释清楚),如果你将它转换为一个名为 null 的字符串,那么它将使它通过下一个测试,然后你可以将它改回 null
  • 我知道这可能不是最优雅的解决方案,但有时最好使用简单可行的解决方案,然后再进行优化

标签: php string null


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2017-10-16
    • 1970-01-01
    • 2020-09-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-17
    • 2011-02-18
    相关资源
    最近更新 更多