简体   繁体   中英

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.

Example:

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

In the list of fields I have some type values set as 'string' . The problem is that I want all those 'string' values to also include null value types that the user might provide.

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.

A user does a POST request with a JSON body (with header 'Content-Type' set to 'application/json;charset=utf-8' ):

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

I handle the body data and use json_decode($body, true) to convert it to php array.

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.

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).

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:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM