Skip to content

Commit

Permalink
Fix EZP-22437: JSON decode result is not checked in the input parser
Browse files Browse the repository at this point in the history
  • Loading branch information
dpobel committed Mar 5, 2014
1 parent 06e491c commit 8e6f5fe
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 1 deletion.
40 changes: 39 additions & 1 deletion eZ/Publish/Core/REST/Common/Input/Handler/Json.php
Expand Up @@ -10,6 +10,7 @@
namespace eZ\Publish\Core\REST\Common\Input\Handler;

use eZ\Publish\Core\REST\Common\Input\Handler;
use eZ\Publish\Core\REST\Common\Exceptions\Parser as ParserException;

/**
* Input format handler base class
Expand All @@ -19,12 +20,49 @@ class Json extends Handler
/**
* Converts the given string to an array structure
*
* @throw eZ\Publish\Core\REST\Common\Exceptions\Parser
* @param string $string
*
* @return array
*/
public function convert( $string )
{
return json_decode( $string, true );
$json = json_decode( $string, true );
if ( JSON_ERROR_NONE !== ( $jsonErrorCode = json_last_error() ) )
{
$message = "An error occured while decoding the JSON input:\n";
$message .= $this->jsonDecodeErrorMessage( $jsonErrorCode );
$message .= "\nInput JSON:\n\n" . $string;
throw new ParserException( $message );
}
return $json;
}

/**
* Returns the error message associated with the $jsonErrorCode
*
* @param $jsonErrorCode
* @return string
*/
private function jsonDecodeErrorMessage( $jsonErrorCode )
{
if ( function_exists( 'json_last_error_msg' ) )
{
return json_last_error_msg();
}
switch ( $jsonErrorCode )
{
case JSON_ERROR_DEPTH:
return 'Maximum stack depth exceeded';
case JSON_ERROR_STATE_MISMATCH:
return 'Underflow or the modes mismatch';
case JSON_ERROR_CTRL_CHAR:
return 'Unexpected control character found';
case JSON_ERROR_SYNTAX:
return 'Syntax error, malformed JSON';
case JSON_ERROR_UTF8:
return 'Malformed UTF-8 characters, possibly incorrectly encoded';
}
return 'Unknown JSON decode error';
}
}
9 changes: 9 additions & 0 deletions eZ/Publish/Core/REST/Common/Tests/Input/Handler/JsonTest.php
Expand Up @@ -17,6 +17,15 @@
*/
class JsonTest extends PHPUnit_Framework_TestCase
{
/**
* @expectedException \eZ\Publish\Core\REST\Common\Exceptions\Parser
*/
public function testConvertInvalidJson()
{
$handler = $this->getHandler();
$handler->convert( '{text:"Hello world!"}' );
}

/**
* Tests conversion of array to JSON
*/
Expand Down

0 comments on commit 8e6f5fe

Please sign in to comment.