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 33f5596
Show file tree
Hide file tree
Showing 2 changed files with 59 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
));
}
}
48 changes: 47 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', $this->getLastErrorMessage());
}

return $encoded;
}

/**
Expand Down Expand Up @@ -91,4 +97,44 @@ public function requiresSQLCommentHint(AbstractPlatform $platform)
//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';
}
}
}

0 comments on commit 33f5596

Please sign in to comment.