Skip to content

Commit

Permalink
Throws an ConversionException if the json encoding fails
Browse files Browse the repository at this point in the history
  • Loading branch information
Taluu committed Jan 25, 2016
1 parent dee0141 commit 8b7f768
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 1 deletion.
12 changes: 12 additions & 0 deletions lib/Doctrine/DBAL/Types/ConversionException.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
));
}
}
41 changes: 40 additions & 1 deletion lib/Doctrine/DBAL/Types/JsonType.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}

/**
Expand Down Expand Up @@ -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';
}
}
}

0 comments on commit 8b7f768

Please sign in to comment.