From 8b7f768dc960d51be046a7ea38379c6a050634ba Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Baptiste=20Clavi=C3=A9?= Date: Mon, 25 Jan 2016 13:48:13 +0100 Subject: [PATCH] Throws an ConversionException if the json encoding fails --- .../DBAL/Types/ConversionException.php | 12 ++++++ lib/Doctrine/DBAL/Types/JsonType.php | 41 ++++++++++++++++++- 2 files changed, 52 insertions(+), 1 deletion(-) diff --git a/lib/Doctrine/DBAL/Types/ConversionException.php b/lib/Doctrine/DBAL/Types/ConversionException.php index e37a79058f7..7c47286faf4 100644 --- a/lib/Doctrine/DBAL/Types/ConversionException.php +++ b/lib/Doctrine/DBAL/Types/ConversionException.php @@ -99,4 +99,16 @@ static public function conversionFailedInvalidType($value, $toType, array $possi 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 + )); + } } diff --git a/lib/Doctrine/DBAL/Types/JsonType.php b/lib/Doctrine/DBAL/Types/JsonType.php index f91fbd405a5..66d0f41ff8b 100644 --- a/lib/Doctrine/DBAL/Types/JsonType.php +++ b/lib/Doctrine/DBAL/Types/JsonType.php @@ -46,7 +46,13 @@ public function convertToDatabaseValue($value, AbstractPlatform $platform) return null; } - return json_encode($value); + $encoded = json_encode($value); + + if (JSON_ERROR_NONE !== json_last_error()) { + throw ConversionException::conversionFailedSerialization($value, 'json', self::json_last_error_msg()); + } + + return $encoded; } /** @@ -91,4 +97,37 @@ public function requiresSQLCommentHint(AbstractPlatform $platform) //return ! $platform->hasNativeJsonType(); return true; } + + // 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 + private static function json_last_error_msg() + { + 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'; + } + } }