Commit 33f55969 authored by Baptiste Clavié's avatar Baptiste Clavié

Throws an ConversionException if the json encoding fails

parent dee01418
......@@ -99,4 +99,16 @@ class ConversionException extends \Doctrine\DBAL\DBALException
implode(', ', $possibleTypes)
));
}
static public function conversionFailedSerialization($value, $format, $error, \Exception $previous = null)
{
$actualType = is_object($value) ? get_class($value) : gettype($value);
return new self(sprintf(
"Could not convert PHP type '%s' to '%s', as an '%s' error was triggered by the serialization",
$actualType,
$format,
$error
));
}
}
......@@ -46,7 +46,13 @@ class JsonType extends Type
return null;
}
return json_encode($value);
$encoded = json_encode($value);
if (JSON_ERROR_NONE !== json_last_error()) {
throw ConversionException::conversionFailedSerialization($value, 'json', $this->getLastErrorMessage());
}
return $encoded;
}
/**
......@@ -91,4 +97,44 @@ class JsonType extends Type
//return ! $platform->hasNativeJsonType();
return true;
}
/**
* Get the latest json error message
*
* This method declaration has been extracted from symfony's php 5.5 polyfill
*
* @link https://github.com/symfony/polyfill-php55/blob/master/Php55.php
* @link http://nl1.php.net/manual/en/function.json-last-error-msg.php
*
* @return string
*/
private function getLastErrorMessage()
{
if (function_exists('json_last_error_msg')) {
return json_last_error_msg();
}
switch (json_last_error()) {
case JSON_ERROR_NONE:
return 'No error';
case JSON_ERROR_DEPTH:
return 'Maximum stack depth exceeded';
case JSON_ERROR_STATE_MISMATCH:
return 'State mismatch (invalid or malformed JSON)';
case JSON_ERROR_CTRL_CHAR:
return 'Control character error, possibly incorrectly encoded';
case JSON_ERROR_SYNTAX:
return 'Syntax error';
case JSON_ERROR_UTF8:
return 'Malformed UTF-8 characters, possibly incorrectly encoded';
default:
return 'Unknown error';
}
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment