Throw exception on mixed data type arrays

Modified the parser so as to throw an exception on encountering mixed
data types within an array. Also corrected the extended.toml to prevent
from throwing this exception because of malformed key "key"
This commit is contained in:
ayushchd 2013-03-01 19:58:58 +05:30
parent c2f86aea0a
commit f5879641e9
2 changed files with 62 additions and 1 deletions

View File

@ -256,7 +256,7 @@ class Toml
} }
} }
// Datetime. Parsed to UNIX time value. // Datetime. Parsed to UNIX time value.
elseif(preg_match('/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z$/', $val)) elseif(self::isISODate($val))
{ {
$parsedVal = strtotime($val); $parsedVal = strtotime($val);
} }
@ -313,6 +313,9 @@ class Toml
$result[] = self::parseValue( trim($buffer) ); $result[] = self::parseValue( trim($buffer) );
} }
if (!self::checkDataType($result)) {
throw new Exception('Data types cannot be mixed in an array: ' . $buffer);
}
// Skip first and las brackets. We're finish. // Skip first and las brackets. We're finish.
return $result; return $result;
} }
@ -325,6 +328,9 @@ class Toml
if( $val[$i] == ',' && !$openString && $openBrackets == 1) if( $val[$i] == ',' && !$openString && $openBrackets == 1)
{ {
$result[] = self::parseValue( trim($buffer) ); $result[] = self::parseValue( trim($buffer) );
if (!self::checkDataType($result)) {
throw new Exception('Data types cannot be mixed in an array: ' . $buffer);
}
$buffer = ''; $buffer = '';
} }
else else
@ -337,4 +343,57 @@ class Toml
throw new Exception('Wrong array definition: ' . $val); throw new Exception('Wrong array definition: ' . $val);
} }
/**
* Function that checks the data type of the first and last elements of an array,
* and returns false if they don't match
*
* @param (array) $array
*
* @return boolean
*/
private static function checkDataType($array) {
if(count($array) <= 1)
return true;
$last = count($array) - 1;
$type = self::getCustomDataType($array[$last]);
if ($type != self::getCustomDataType($array[0])) {
return false;
} else {
return true;
}
}
/**
* Returns the data type of a variable
*
* @param (mixed) $val
* @return (string) Data type of value
*/
private static function getCustomDataType($val) {
$val = (!is_array($val)) ? trim($val) : $val;
if (!is_array($val) && self::isISODate($val)) {
$type = "date";
} else {
$type = gettype($val);
}
return $type;
}
/**
* Return whether the given value is a valid ISODate
* @param (string) $val
* @return boolean
*/
private static function isISODate($val) {
return preg_match('/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z$/', $val);
}
} }

View File

@ -31,7 +31,9 @@ data = [ ["gamma", "delta"], [1, 2] ] # just an update to make sure parsers supp
# Multi-line array check # Multi-line array check
key = [ key = [
[
1, 2, 3, 1, 2, 3,
],
[ [
1979-05-27T07:32:00Z, 1979-05-27T07:32:00Z,
1979-05-27T07:32:00Z 1979-05-27T07:32:00Z