Skip to content

Instantly share code, notes, and snippets.

@Saucy
Created July 31, 2015 21:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Saucy/779d915c0622d9d12316 to your computer and use it in GitHub Desktop.
Save Saucy/779d915c0622d9d12316 to your computer and use it in GitHub Desktop.
PHP - verify data types
<?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);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment