diff --git a/src/Decoder.php b/src/Decoder.php index bf07d0996..fdb6778c9 100644 --- a/src/Decoder.php +++ b/src/Decoder.php @@ -16,7 +16,6 @@ * @package Zend_Json * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License - * @version $Id$ */ /** @@ -24,12 +23,16 @@ */ namespace Zend\Json; +use Zend\Json\Exception\RuntimeException, + Zend\Json\Exception\InvalidArgumentException; + /** * Decode JSON encoded string to PHP variable constructs * * @uses stdClass - * @uses \Zend\Json\Json - * @uses \Zend\Json\Exception + * @uses Zend\Json\Json + * @uses Zend\Json\Exception\RuntimeException + * @uses Zend\Json\Exception\InvalidArgumentException * @category Zend * @package Zend_Json * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) @@ -37,19 +40,20 @@ */ class Decoder { + /** * Parse tokens used to decode the JSON object. These are not * for public consumption, they are just used internally to the * class. */ - const EOF = 0; - const DATUM = 1; + const EOF = 0; + const DATUM = 1; const LBRACE = 2; - const LBRACKET = 3; - const RBRACE = 4; - const RBRACKET = 5; - const COMMA = 6; - const COLON = 7; + const LBRACKET = 3; + const RBRACE = 4; + const RBRACKET = 5; + const COMMA = 6; + const COLON = 7; /** * Use to maintain a "pointer" to the source being decoded @@ -105,12 +109,14 @@ protected function __construct($source, $decodeType) $this->_token = self::EOF; $this->_offset = 0; - // Normalize and set $decodeType - if (!in_array($decodeType, array(Json::TYPE_ARRAY, Json::TYPE_OBJECT))) - { - $decodeType = Json::TYPE_ARRAY; + switch ($decodeType) { + case Json::TYPE_ARRAY: + case Json::TYPE_OBJECT: + $this->_decodeType = $decodeType; + break; + default: + throw new InvalidArgumentException("Unknown decode type '{$decodeType}', please use one of the constants Json::TYPE_*"); } - $this->_decodeType = $decodeType; // Set pointer at first token $this->_getNextToken(); @@ -133,8 +139,6 @@ protected function __construct($source, $decodeType) * return a StdClass object instead, pass {@link Zend_Json::TYPE_OBJECT} to * the $objectDecodeType parameter. * - * Throws a Zend_Json_Exception if the source string is null. - * * @static * @access public * @param string $source String to be decoded @@ -142,22 +146,13 @@ protected function __construct($source, $decodeType) * either or {@link Zend_Json::TYPE_ARRAY} or * {@link Zend_Json::TYPE_OBJECT}; defaults to TYPE_ARRAY * @return mixed - * @throws \Zend\Json\Exception */ - public static function decode($source = null, $objectDecodeType = Json::TYPE_ARRAY) + public static function decode($source, $objectDecodeType = Json::TYPE_ARRAY) { - if (null === $source) { - throw new Exception('Must specify JSON encoded source for decoding'); - } elseif (!is_string($source)) { - throw new Exception('Can only decode JSON encoded strings'); - } - $decoder = new self($source, $objectDecodeType); - return $decoder->_decodeValue(); } - /** * Recursive driving rountine for supported toplevel tops * @@ -196,6 +191,7 @@ protected function _decodeValue() * array. * * @return array|StdClass + * @throws Zend\Json\Exception\RuntimeException */ protected function _decodeObject() { @@ -204,14 +200,14 @@ protected function _decodeObject() while ($tok && $tok != self::RBRACE) { if ($tok != self::DATUM || ! is_string($this->_tokenValue)) { - throw new Exception('Missing key in object encoding: ' . $this->_source); + throw new RuntimeException('Missing key in object encoding: ' . $this->_source); } $key = $this->_tokenValue; $tok = $this->_getNextToken(); if ($tok != self::COLON) { - throw new Exception('Missing ":" in object encoding: ' . $this->_source); + throw new RuntimeException('Missing ":" in object encoding: ' . $this->_source); } $tok = $this->_getNextToken(); @@ -223,7 +219,7 @@ protected function _decodeObject() } if ($tok != self::COMMA) { - throw new Exception('Missing "," in object encoding: ' . $this->_source); + throw new RuntimeException('Missing "," in object encoding: ' . $this->_source); } $tok = $this->_getNextToken(); @@ -252,6 +248,7 @@ protected function _decodeObject() * [element, element2,...,elementN] * * @return array + * @throws Zend\Json\Exception\RuntimeException */ protected function _decodeArray() { @@ -269,14 +266,14 @@ protected function _decodeArray() } if ($tok != self::COMMA) { - throw new Exception('Missing "," in array encoding: ' . $this->_source); + throw new RuntimeException('Missing "," in array encoding: ' . $this->_source); } $tok = $this->_getNextToken(); } $this->_getNextToken(); - return($result); + return $result; } @@ -302,6 +299,7 @@ protected function _eatWhitespace() * Retrieves the next token from the source stream * * @return int Token constant value specified in class definition + * @throws Zend\Json\Exception\RuntimeException */ protected function _getNextToken() { @@ -382,8 +380,7 @@ protected function _getNextToken() $result .= '\''; break; default: - throw new Exception("Illegal escape " - . "sequence '" . $chr . "'"); + throw new RuntimeException("Illegal escape sequence '{$chr}'"); } } elseif($chr == '"') { break; @@ -433,24 +430,24 @@ protected function _getNextToken() if (is_numeric($datum)) { if (preg_match('/^0\d+$/', $datum)) { - throw new Exception("Octal notation not supported by JSON (value: $datum)"); + throw new RuntimeException("Octal notation not supported by JSON (value: {$datum})"); } else { $val = intval($datum); $fVal = floatval($datum); $this->_tokenValue = ($val == $fVal ? $val : $fVal); } } else { - throw new Exception("Illegal number format: $datum"); + throw new RuntimeException("Illegal number format: {$datum}"); } $this->_token = self::DATUM; $this->_offset = $start + strlen($datum); } } else { - throw new Exception('Illegal Token'); + throw new RuntimeException('Illegal Token'); } - return($this->_token); + return $this->_token; } /** @@ -466,6 +463,7 @@ protected function _getNextToken() */ public static function decodeUnicodeString($chrs) { + $chrs = (string)$chrs; $delim = substr($chrs, 0, 1); $utf8 = ''; $strlen_chrs = strlen($chrs); diff --git a/src/Encoder.php b/src/Encoder.php index d8e3ab103..ac6425c80 100644 --- a/src/Encoder.php +++ b/src/Encoder.php @@ -16,7 +16,6 @@ * @package Zend_Json * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License - * @version $Id$ */ /** @@ -24,11 +23,15 @@ */ namespace Zend\Json; +use Zend\Json\Exception\RecursionException, + Zend\Json\Exception\InvalidArgumentException; + /** * Encode PHP constructs to JSON * * @uses ReflectionClass - * @uses \Zend\Json\Exception + * @uses Zend\Json\Exception\RecursionException + * @uses Zend\Json\Exception\InvalidArgumentException * @category Zend * @package Zend_Json * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) @@ -117,7 +120,8 @@ protected function _encodeValue(&$value) * * @param $value object * @return string - * @throws \Zend\Json\Exception If recursive checks are enabled and the object has been serialized previously + * @throws Zend\Json\Exception\RecursionException If recursive checks are enabled + * and the object has been serialized previously */ protected function _encodeObject(&$value) { @@ -130,7 +134,7 @@ protected function _encodeObject(&$value) return '"* RECURSION (' . str_replace('\\', '\\\\', get_class($value)) . ') *"'; } else { - throw new Exception( + throw new RecursionException( 'Cycles not supported in JSON encoding, cycle introduced by ' . 'class "' . get_class($value) . '"' ); @@ -403,13 +407,13 @@ private static function _encodeVariables(\ReflectionClass $cls) * @param $package string Optional package name appended to JavaScript * proxy class name * @return string The class2 (JavaScript) encoding of the class - * @throws \Zend\Json\Exception + * @throws Zend\Json\Exception\InvalidArgumentException */ public static function encodeClass($className, $package = '') { $cls = new \ReflectionClass($className); if (! $cls->isInstantiable()) { - throw new Exception("$className must be instantiable"); + throw new InvalidArgumentException("'{$className}' must be instantiable"); } return "Class.create('$package$className',{" diff --git a/src/Exception.php b/src/Exception.php index c1f00f0ab..b9a8c69ef 100644 --- a/src/Exception.php +++ b/src/Exception.php @@ -16,7 +16,6 @@ * @package Zend_Json * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License - * @version $Id$ */ /** @@ -25,12 +24,11 @@ namespace Zend\Json; /** - * @uses \Zend\Exception + * @uses Zend\Exception * @category Zend * @package Zend_Json * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ -class Exception extends \Zend\Exception +interface Exception {} - diff --git a/src/Exception/InvalidArgumentException.php b/src/Exception/InvalidArgumentException.php new file mode 100644 index 000000000..da4a7a95d --- /dev/null +++ b/src/Exception/InvalidArgumentException.php @@ -0,0 +1,35 @@ += 5.3 - } elseif (($jsonLastErr = json_last_error()) != JSON_ERROR_NONE) { - switch ($jsonLastErr) { - case JSON_ERROR_DEPTH: - throw new Exception('Decoding failed: Maximum stack depth exceeded'); - case JSON_ERROR_CTRL_CHAR: - throw new Exception('Decoding failed: Unexpected control character found'); - case JSON_ERROR_SYNTAX: - throw new Exception('Decoding failed: Syntax error'); - default: - throw new Exception('Decoding failed'); - } + switch (json_last_error()) { + case JSON_ERROR_NONE: + break; + case JSON_ERROR_DEPTH: + throw new RuntimeException('Decoding failed: Maximum stack depth exceeded'); + case JSON_ERROR_CTRL_CHAR: + throw new RuntimeException('Decoding failed: Unexpected control character found'); + case JSON_ERROR_SYNTAX: + throw new RuntimeException('Decoding failed: Syntax error'); + default: + throw new RuntimeException('Decoding failed'); } return $decode; @@ -157,7 +155,7 @@ public static function encode($valueToEncode, $cycleCheck = false, $options = ar } } - return $encodedResult; + return $encodedResult; } /** @@ -214,7 +212,6 @@ protected static function _recursiveJsonExprFinder( * calling a recursive (protected static) function in this class. Then, it * converts that PHP array into JSON by calling the "encode" static funcion. * - * Throws a Zend_Json_Exception if the input not a XML formatted string. * NOTE: Encoding native javascript expressions via Zend_Json_Expr is not possible. * * @static @@ -223,7 +220,7 @@ protected static function _recursiveJsonExprFinder( * @param boolean $ignoreXmlAttributes Include or exclude XML attributes in * the xml2json conversion process. * @return mixed - JSON formatted string on success - * @throws \Zend\Json\Exception + * @throws \Zend\Json\Exception\RuntimeException if the input not a XML formatted string */ public static function fromXml ($xmlStringContents, $ignoreXmlAttributes=true) { // Load the XML formatted string into a Simple XML Element object. @@ -231,7 +228,7 @@ public static function fromXml ($xmlStringContents, $ignoreXmlAttributes=true) { // If it is not a valid XML content, throw an exception. if ($simpleXmlElementObject == null) { - throw new Exception('Function fromXml was called with an invalid XML formatted string.'); + throw new RuntimeException('Function fromXml was called with an invalid XML formatted string.'); } // End of if ($simpleXmlElementObject == null) $resultArray = null; @@ -243,7 +240,7 @@ public static function fromXml ($xmlStringContents, $ignoreXmlAttributes=true) { // It is just that simple. $jsonStringOutput = self::encode($resultArray); return($jsonStringOutput); - } // End of function fromXml. + } /** * _processXml - Contains the logic for xml2json @@ -259,8 +256,6 @@ public static function fromXml ($xmlStringContents, $ignoreXmlAttributes=true) { * calling a recursive (protected static) function in this class. Once all * the XML elements are stored in the PHP array, it is returned to the caller. * - * Throws a Zend_Json_Exception if the XML tree is deeper than the allowed limit. - * * @static * @access protected * @param SimpleXMLElement $simpleXmlElementObject XML element to be converted @@ -268,13 +263,13 @@ public static function fromXml ($xmlStringContents, $ignoreXmlAttributes=true) { * the xml2json conversion process. * @param int $recursionDepth Current recursion depth of this function * @return mixed - On success, a PHP associative array of traversed XML elements - * @throws \Zend\Json\Exception + * @throws Zend\Json\Exception\RecursionException if the XML tree is deeper than the allowed limit */ protected static function _processXml ($simpleXmlElementObject, $ignoreXmlAttributes, $recursionDepth=0) { // Keep an eye on how deeply we are involved in recursion. if ($recursionDepth > self::$maxRecursionDepthAllowed) { // XML tree is too deep. Exit now by throwing an exception. - throw new Exception( + throw new RecursionException( "Function _processXml exceeded the allowed recursion depth of " . self::$maxRecursionDepthAllowed); } // End of if ($recursionDepth > self::$maxRecursionDepthAllowed) @@ -341,7 +336,7 @@ protected static function _processXml ($simpleXmlElementObject, $ignoreXmlAttrib // if it matches, we return a new Zend_Json_Expr instead of a text node $pattern = '/^[\s]*new Zend_Json_Expr[\s]*\([\s]*[\"\']{1}(.*)[\"\']{1}[\s]*\)[\s]*$/'; $matchings = array(); - $match = preg_match ($pattern, $simpleXmlElementObject, $matchings); + $match = preg_match($pattern, $simpleXmlElementObject, $matchings); if ($match) { return new Expr($matchings[1]); } else { diff --git a/src/Server/Cache.php b/src/Server/Cache.php index 05768f451..6483c331b 100644 --- a/src/Server/Cache.php +++ b/src/Server/Cache.php @@ -17,7 +17,6 @@ * @subpackage Server * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License - * @version $Id$ */ /** diff --git a/src/Server/Error.php b/src/Server/Error.php index 18bc6ec26..3fb1a235c 100644 --- a/src/Server/Error.php +++ b/src/Server/Error.php @@ -16,7 +16,6 @@ * @package Zend_Json * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License - * @version $Id$ */ /** diff --git a/src/Server/Exception.php b/src/Server/Exception.php index cbe473549..0c7beeb90 100644 --- a/src/Server/Exception.php +++ b/src/Server/Exception.php @@ -16,7 +16,6 @@ * @package Zend_Json * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License - * @version $Id$ */ /** @@ -25,14 +24,12 @@ namespace Zend\Json\Server; /** - * Zend_Json_Server exceptions - * - * @uses \Zend\Json\Exception + * @uses Zend\Json\Exception + * @category Zend * @package Zend_Json * @subpackage Server * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ -class Exception extends \Zend\Json\Exception -{ -} +interface Exception extends \Zend\Json\Exception +{} diff --git a/src/Server/Exception/InvalidArgumentException.php b/src/Server/Exception/InvalidArgumentException.php new file mode 100644 index 000000000..2a00e5c83 --- /dev/null +++ b/src/Server/Exception/InvalidArgumentException.php @@ -0,0 +1,36 @@ +_rawJson; } diff --git a/src/Server/Response.php b/src/Server/Response.php index 7a9b7d9a1..f12c4db39 100644 --- a/src/Server/Response.php +++ b/src/Server/Response.php @@ -17,7 +17,6 @@ * @subpackage Server * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License - * @version $Id$ */ /** diff --git a/src/Server/Response/Http.php b/src/Server/Response/Http.php index 565ae2625..ffdad5c52 100644 --- a/src/Server/Response/Http.php +++ b/src/Server/Response/Http.php @@ -16,7 +16,6 @@ * @package Zend_Json * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License - * @version $Id$ */ /** @@ -24,7 +23,7 @@ */ namespace Zend\Json\Server\Response; -use Zend\Json\Server\Response as JSONResponse; +use Zend\Json\Server\Response as JsonResponse; /** * @uses \Zend\Json\Server\Response\Response @@ -33,7 +32,7 @@ * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ -class Http extends JSONResponse +class Http extends JsonResponse { /** * Emit JSON diff --git a/src/Server/Server.php b/src/Server/Server.php index 1f893a991..a26d86826 100644 --- a/src/Server/Server.php +++ b/src/Server/Server.php @@ -16,7 +16,6 @@ * @package Zend_Json * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License - * @version $Id$ */ /** diff --git a/src/Server/Smd.php b/src/Server/Smd.php index 85ff4279b..75c03c8c8 100644 --- a/src/Server/Smd.php +++ b/src/Server/Smd.php @@ -17,17 +17,19 @@ * @subpackage Server * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License - * @version $Id$ */ /** * @namespace */ namespace Zend\Json\Server; +use Zend\Json\Server\Exception\InvalidArgumentException, + Zend\Json\Server\Exception\RuntimeException; /** * @uses Zend\Json\Json - * @uses Zend\Json\Server\Exception + * @uses Zend\Json\Server\Exception\InvalidArgumentException + * @uses Zend\Json\Server\Exception\RuntimeException * @uses Zend\Json\Server\Smd\Service * @category Zend * @package Zend_Json @@ -118,10 +120,9 @@ class SMD */ public function setOptions(array $options) { - $methods = get_class_methods($this); foreach ($options as $key => $value) { $method = 'set' . ucfirst($key); - if (in_array($method, $methods)) { + if (method_exists($this, $method)) { $this->$method($value); } } @@ -137,7 +138,7 @@ public function setOptions(array $options) public function setTransport($transport) { if (!in_array($transport, $this->_transportTypes)) { - throw new Exception(sprintf('Invalid transport "%s" specified', $transport)); + throw new InvalidArgumentException("Invalid transport '{$transport}' specified"); } $this->_transport = $transport; return $this; @@ -162,7 +163,7 @@ public function getTransport() public function setEnvelope($envelopeType) { if (!in_array($envelopeType, $this->_envelopeTypes)) { - throw new Exception(sprintf('Invalid envelope type "%s"', $envelopeType)); + throw new InvalidArgumentException("Invalid envelope type '{$envelopeType}'"); } $this->_envelope = $envelopeType; return $this; @@ -188,7 +189,7 @@ public function getEnvelope() public function setContentType($type) { if (!preg_match($this->_contentTypeRegex, $type)) { - throw new Exception(sprintf('Invalid content type "%s" specified', $type)); + throw new InvalidArgumentException("Invalid content type '{$type}' specified"); } $this->_contentType = $type; return $this; @@ -306,11 +307,11 @@ public function addService($service) $service = new Smd\Service($service); $name = $service->getName(); } else { - throw new Exception('Invalid service passed to addService()'); + throw new InvalidArgumentException('Invalid service passed to addService()'); } if (array_key_exists($name, $this->_services)) { - throw new Exception('Attempt to register a service already registered detected'); + throw new RuntimeException('Attempt to register a service already registered detected'); } $this->_services[$name] = $service; return $this; diff --git a/src/Server/Smd/Service.php b/src/Server/Smd/Service.php index 35e061182..231838faf 100644 --- a/src/Server/Smd/Service.php +++ b/src/Server/Smd/Service.php @@ -23,18 +23,18 @@ */ namespace Zend\Json\Server\Smd; use Zend\Json\Server\Smd, - Zend\Json\Server; + Zend\Json\Server, + Zend\Json\Server\Exception\InvalidArgumentException; /** * Create Service Mapping Description for a method * * @todo Revised method regex to allow NS; however, should SMD be revised to strip PHP NS instead when attaching functions? - * @uses \Zend\Json\Json - * @uses \Zend\Json\Server\Exception - * @uses \Zend\Json\Server\Smd\Smd + * @uses Zend\Json\Json + * @uses Zend\Json\Server\Exception\InvalidArgumentException + * @uses Zend\Json\Server\Smd\Smd * @package Zend_Json * @subpackage Server - * @version $Id$ * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ @@ -125,7 +125,7 @@ class Service * * @param string|array $spec * @return void - * @throws Zend\Json\Server\Exception if no name provided + * @throws Zend\Json\Server\Exception\InvalidArgumentException if no name provided */ public function __construct($spec) { @@ -136,7 +136,7 @@ public function __construct($spec) } if (null == $this->getName()) { - throw new Server\Exception('SMD service description requires a name; none provided'); + throw new InvalidArgumentException('SMD service description requires a name; none provided'); } } @@ -166,13 +166,13 @@ public function setOptions(array $options) * * @param string $name * @return Zend\Json\Server\Smd\Service - * @throws Zend\Json\Server\Exception + * @throws Zend\Json\Server\Exception\InvalidArgumentException */ public function setName($name) { $name = (string) $name; if (!preg_match($this->_nameRegex, $name)) { - throw new Server\Exception(sprintf('Invalid name "%s" provided for service; must follow PHP method naming conventions', $name)); + throw new InvalidArgumentException("Invalid name '{$name} provided for service; must follow PHP method naming conventions"); } $this->_name = $name; return $this; @@ -199,7 +199,7 @@ public function getName() public function setTransport($transport) { if (!in_array($transport, $this->_transportTypes)) { - throw new Server\Exception(sprintf('Invalid transport "%s"; please select one of (%s)', $transport, implode(', ', $this->_transportTypes))); + throw new InvalidArgumentException("Invalid transport '{$transport}'; please select one of (" . implode(', ', $this->_transportTypes) . ')'); } $this->_transport = $transport; @@ -247,7 +247,7 @@ public function getTarget() public function setEnvelope($envelopeType) { if (!in_array($envelopeType, $this->_envelopeTypes)) { - throw new Server\Exception(sprintf('Invalid envelope type "%s"; please specify one of (%s)', $envelopeType, implode(', ', $this->_envelopeTypes))); + throw new InvalidArgumentException("Invalid envelope type '{$envelopeType}'; please specify one of (" . implode(', ', $this->_envelopeTypes) . ')'); } $this->_envelope = $envelopeType; @@ -281,7 +281,7 @@ public function addParam($type, array $options = array(), $order = null) $type[$key] = $this->_validateParamType($paramType); } } else { - throw new Server\Exception('Invalid param type provided'); + throw new InvalidArgumentException('Invalid param type provided'); } $paramOptions = array( @@ -384,7 +384,7 @@ public function setReturn($type) $type[$key] = $this->_validateParamType($returnType, true); } } else { - throw new Server\Exception('Invalid param type provided ("' . gettype($type) .'")'); + throw new InvalidArgumentException("Invalid param type provided ('" . gettype($type) . "')"); } $this->_return = $type; return $this; @@ -452,7 +452,7 @@ public function __toString() protected function _validateParamType($type, $isReturn = false) { if (!is_string($type)) { - throw new Server\Exception('Invalid param type provided ("' . $type .'")'); + throw new InvalidArgumentException("Invalid param type provided ('{$type}')"); } if (!array_key_exists($type, $this->_paramMap)) { @@ -461,7 +461,7 @@ protected function _validateParamType($type, $isReturn = false) $paramType = $this->_paramMap[$type]; if (!$isReturn && ('null' == $paramType)) { - throw new Server\Exception('Invalid param type provided ("' . $type . '")'); + throw new InvalidArgumentException("Invalid param type provided ('{$type}')"); } return $paramType; diff --git a/test/JSONTest.php b/test/JsonTest.php similarity index 93% rename from test/JSONTest.php rename to test/JsonTest.php index cf381e8ae..572f9f7a3 100644 --- a/test/JSONTest.php +++ b/test/JsonTest.php @@ -17,7 +17,6 @@ * @subpackage UnitTests * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License - * @version $Id$ */ /** @@ -34,7 +33,7 @@ * @license http://framework.zend.com/license/new-bsd New BSD License * @group Zend_JSON */ -class JSONTest extends \PHPUnit_Framework_TestCase +class JsonTest extends \PHPUnit_Framework_TestCase { private $_originalUseBuiltinEncoderDecoderValue; @@ -303,37 +302,38 @@ public function testEarlyLineBreak() } /** - * Tests for ZF-504 - * - * Three confirmed issues reported: - * - encoder improperly encoding empty arrays as structs - * - decoder happily decoding clearly borked JSON - * - decoder decoding octal values improperly (shouldn't decode them at all, as JSON does not support them) - */ - public function testZf504() - { - $test = array(); - $this->assertSame('[]', Json\Encoder::encode($test)); - - try { - $json = '[a"],["a],[][]'; - $test = Json\Decoder::decode($json); - $this->fail("Should not be able to decode '$json'"); - - $json = '[a"],["a]'; - $test = Json\Decoder::decode($json); - $this->fail("Should not be able to decode '$json'"); - } catch (\Exception $e) { - // success - } + * @group ZF-504 + */ + public function testEncodeEmptyArrayAsStruct() + { + $this->assertSame('[]', Json\Encoder::encode(array())); + } - try { - $expected = 010; - $test = Json\Decoder::decode('010'); - $this->fail('Octal values are not supported in JSON notation'); - } catch (\Exception $e) { - // sucess - } + /** + * @group ZF-504 + */ + public function testDecodeBorkedJsonShouldThrowException1() + { + $this->setExpectedException('Zend\Json\Exception\RuntimeException'); + Json\Decoder::decode('[a"],["a],[][]'); + } + + /** + * @group ZF-504 + */ + public function testDecodeBorkedJsonShouldThrowException2() + { + $this->setExpectedException('Zend\Json\Exception\RuntimeException'); + Json\Decoder::decode('[a"],["a]'); + } + + /** + * @group ZF-504 + */ + public function testOctalValuesAreNotSupportedInJsonNotation() + { + $this->setExpectedException('Zend\Json\Exception\RuntimeException'); + Json\Decoder::decode('010'); } /** @@ -349,18 +349,12 @@ public function testZf461() $everything['allItems'] = array($item1, $item2) ; $everything['currentItem'] = $item1 ; - try { - $encoded = Json\Encoder::encode($everything); - } catch (\Exception $e) { - $this->fail('Object cycling checks should check for recursion, not duplicate usage of an item'); - } + // should not fail + $encoded = Json\Encoder::encode($everything); - try { - $encoded = Json\Encoder::encode($everything, true); - $this->fail('Object cycling not allowed when cycleCheck parameter is true'); - } catch (\Exception $e) { - // success - } + // should fail + $this->setExpectedException('Zend\Json\Exception\RecursionException'); + Json\Encoder::encode($everything, true); } /** @@ -733,7 +727,7 @@ public function testBuiltinJSONEncoderWillProperlyEncodeSolidusInStringValues() */ public function testDecodingInvalidJSONShouldRaiseAnException() { - $this->setExpectedException('Zend\Json\Exception'); + $this->setExpectedException('Zend\Json\Exception\RuntimeException'); Json\Json::decode(' some string '); } diff --git a/test/JSONXMLTest.php b/test/JsonXmlTest.php similarity index 87% rename from test/JSONXMLTest.php rename to test/JsonXmlTest.php index 387ddb54f..664768e27 100644 --- a/test/JSONXMLTest.php +++ b/test/JsonXmlTest.php @@ -17,7 +17,6 @@ * @subpackage UnitTests * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License - * @version $Id$ */ /** @@ -44,8 +43,9 @@ * @license http://framework.zend.com/license/new-bsd New BSD License * @group Zend_JSON */ -class JSONXMLTest extends \PHPUnit_Framework_TestCase +class JsonXmlTest extends \PHPUnit_Framework_TestCase { + /** * xml2json Test 1 * It tests the conversion of a contact list xml into JSON format. @@ -103,17 +103,10 @@ public function testUsingXML1() // Hence, set the flag to ignore XML attributes. $ignoreXmlAttributes = true; $jsonContents = ""; - $ex = null; - // Convert XNL to JSON now. + // Convert XML to JSON now. // fromXml function simply takes a String containing XML contents as input. - try { - $jsonContents = Json\Json::fromXml($xmlStringContents, $ignoreXmlAttributes); - } catch (\Exception $ex) { - ; - } - - $this->assertSame($ex, null, "Zend_Json::fromXml returned an exception."); + $jsonContents = Json\Json::fromXml($xmlStringContents, $ignoreXmlAttributes); // Convert the JSON string into a PHP array. $phpArray = Json\Json::decode($jsonContents); @@ -121,7 +114,7 @@ public function testUsingXML1() $this->assertNotNull($phpArray, "JSON result for XML input 1 is NULL"); // Test for one of the expected fields in the JSON result. $this->assertSame("Jane Smith", $phpArray['contacts']['contact'][3]['name'], "The last contact name converted from XML input 1 is not correct"); - } // End of function testUsingXML1 + } /** * xml2json Test 2 @@ -159,17 +152,10 @@ public function testUsingXML2() // Hence, set the flag NOT to ignore XML attributes. $ignoreXmlAttributes = false; $jsonContents = ""; - $ex = null; - // Convert XNL to JSON now. + // Convert XML to JSON now. // fromXml function simply takes a String containing XML contents as input. - try { - $jsonContents = Json\Json::fromXml($xmlStringContents, $ignoreXmlAttributes); - } catch (\Exception $ex) { - ; - } - - $this->assertSame($ex, null, "Zend_Json::fromXml returned an exception."); + $jsonContents = Json\Json::fromXml($xmlStringContents, $ignoreXmlAttributes); // Convert the JSON string into a PHP array. $phpArray = Json\Json::decode($jsonContents); @@ -179,7 +165,7 @@ public function testUsingXML2() $this->assertSame("Podcasting Hacks", $phpArray['books']['book'][2]['title'], "The last book title converted from XML input 2 is not correct"); // Test one of the expected XML attributes carried over in the JSON result. $this->assertSame("3", $phpArray['books']['book'][2]['@attributes']['id'], "The last id attribute converted from XML input 2 is not correct"); - } // End of function testUsingXML2 + } /** * xml2json Test 3 @@ -246,17 +232,10 @@ public function testUsingXML3() // Hence, set the flag to ignore XML attributes. $ignoreXmlAttributes = true; $jsonContents = ""; - $ex = null; - // Convert XNL to JSON now. + // Convert XML to JSON now. // fromXml function simply takes a String containing XML contents as input. - try { - $jsonContents = Json\Json::fromXml($xmlStringContents, $ignoreXmlAttributes); - } catch (\Exception $ex) { - ; - } - - $this->assertSame($ex, null, "Zend_Json::fromXml returned an exception."); + $jsonContents = Json\Json::fromXml($xmlStringContents, $ignoreXmlAttributes); // Convert the JSON string into a PHP array. $phpArray = Json\Json::decode($jsonContents); @@ -264,7 +243,7 @@ public function testUsingXML3() $this->assertNotNull($phpArray, "JSON result for XML input 3 is NULL"); // Test for one of the expected fields in the JSON result. $this->assertContains("Homestyle Breakfast", $phpArray['breakfast_menu']['food'][4], "The last breakfast item name converted from XML input 3 is not correct"); - } // End of function testUsingXML3 + } /** * xml2json Test 4 @@ -359,17 +338,10 @@ public function testUsingXML4() // Hence, set the flag NOT to ignore XML attributes. $ignoreXmlAttributes = false; $jsonContents = ""; - $ex = null; - // Convert XNL to JSON now. + // Convert XML to JSON now. // fromXml function simply takes a String containing XML contents as input. - try { - $jsonContents = Json\Json::fromXml($xmlStringContents, $ignoreXmlAttributes); - } catch (\Exception $ex) { - ; - } - - $this->assertSame($ex, null, "Zend_Json::fromXml returned an exception."); + $jsonContents = Json\Json::fromXml($xmlStringContents, $ignoreXmlAttributes); // Convert the JSON string into a PHP array. $phpArray = Json\Json::decode($jsonContents); @@ -411,17 +383,10 @@ public function testUsingXML5() // Hence, set the flag to ignore XML attributes. $ignoreXmlAttributes = true; $jsonContents = ""; - $ex = null; - // Convert XNL to JSON now. + // Convert XML to JSON now. // fromXml function simply takes a String containing XML contents as input. - try { - $jsonContents = Json\Json::fromXml($xmlStringContents, $ignoreXmlAttributes); - } catch (\Exception $ex) { - ; - } - - $this->assertSame($ex, null, "Zend_Json::fromXml returned an exception."); + $jsonContents = Json\Json::fromXml($xmlStringContents, $ignoreXmlAttributes); // Convert the JSON string into a PHP array. $phpArray = Json\Json::decode($jsonContents); @@ -429,7 +394,7 @@ public function testUsingXML5() $this->assertNotNull($phpArray, "JSON result for XML input 5 is NULL"); // Test for one of the expected CDATA fields in the JSON result. $this->assertContains("Lois & Clark", $phpArray['tvshows']['show'][1]['name'], "The CDATA name converted from XML input 5 is not correct"); - } // End of function testUsingXML5 + } /** * xml2json Test 6 @@ -493,17 +458,10 @@ public function testUsingXML6() // Hence, set the flag to ignore XML attributes. $ignoreXmlAttributes = true; $jsonContents = ""; - $ex = null; - // Convert XNL to JSON now. + // Convert XML to JSON now. // fromXml function simply takes a String containing XML contents as input. - try { - $jsonContents = Json\Json::fromXml($xmlStringContents, $ignoreXmlAttributes); - } catch (\Exception $ex) { - ; - } - - $this->assertSame($ex, null, "Zend_Json::fromXml returned an exception."); + $jsonContents = Json\Json::fromXml($xmlStringContents, $ignoreXmlAttributes); // Convert the JSON string into a PHP array. $phpArray = Json\Json::decode($jsonContents); @@ -513,7 +471,7 @@ public function testUsingXML6() $this->assertContains("Zend", $phpArray['demo']['framework']['name'], "The framework name field converted from XML input 6 is not correct"); // Test for one of the expected CDATA fields in the JSON result. $this->assertContains('echo getMovies()->asXML();', $phpArray['demo']['listing']['code'], "The CDATA code converted from XML input 6 is not correct"); - } // End of function testUsingXML6 + } /** * xml2json Test 7 @@ -543,19 +501,13 @@ public function testUsingXML7() // Hence, set the flag to ignore XML attributes. $ignoreXmlAttributes = true; $jsonContents = ""; - $ex = null; - // Convert XNL to JSON now. + // Convert XML to JSON now. // fromXml function simply takes a String containing XML contents as input. - try { - $jsonContents = Zend_Json::fromXml($xmlStringContents, $ignoreXmlAttributes); - } catch (Exception $ex) { - ; - } - - $this->assertNotSame($ex, null, "Zend_Json::fromXml returned an exception."); - } // End of function testUsingXML7 + $jsonContents = Zend_Json::fromXml($xmlStringContents, $ignoreXmlAttributes); + } */ -} // End of class Zend_JSON_JSONXMLTest + +} diff --git a/test/Server/CacheTest.php b/test/Server/CacheTest.php index 8bb44c5ac..a4e777bc6 100644 --- a/test/Server/CacheTest.php +++ b/test/Server/CacheTest.php @@ -17,7 +17,6 @@ * @subpackage UnitTests * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License - * @version $Id$ */ /** diff --git a/test/Server/ErrorTest.php b/test/Server/ErrorTest.php index 3e53e7d91..a53a9eee6 100644 --- a/test/Server/ErrorTest.php +++ b/test/Server/ErrorTest.php @@ -17,7 +17,6 @@ * @subpackage UnitTests * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License - * @version $Id$ */ /** diff --git a/test/Server/RequestTest.php b/test/Server/RequestTest.php index 5b284b08f..9279271bd 100644 --- a/test/Server/RequestTest.php +++ b/test/Server/RequestTest.php @@ -17,7 +17,6 @@ * @subpackage UnitTests * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License - * @version $Id$ */ /** diff --git a/test/Server/ResponseTest.php b/test/Server/ResponseTest.php index b626c4457..732c4c8d7 100644 --- a/test/Server/ResponseTest.php +++ b/test/Server/ResponseTest.php @@ -17,7 +17,6 @@ * @subpackage UnitTests * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License - * @version $Id$ */ /** diff --git a/test/Server/SMD/ServiceTest.php b/test/Server/Smd/ServiceTest.php similarity index 82% rename from test/Server/SMD/ServiceTest.php rename to test/Server/Smd/ServiceTest.php index 25a08f4d4..fa69b9958 100644 --- a/test/Server/SMD/ServiceTest.php +++ b/test/Server/Smd/ServiceTest.php @@ -17,7 +17,6 @@ * @subpackage UnitTests * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License - * @version $Id$ */ /** @@ -51,39 +50,30 @@ public function setUp() $this->service = new Service('foo'); } - public function testConstructorShouldThrowExceptionWhenNoNameSet() + public function testConstructorShouldThrowExceptionWhenNoNameSetWhenNullProvided() { - try { - $service = new Service(null); - $this->fail('Should throw exception when no name set'); - } catch (Server\Exception $e) { - $this->assertContains('requires a name', $e->getMessage()); - } - - try { - $service = new Service(array()); - $this->fail('Should throw exception when no name set'); - } catch (Server\Exception $e) { - $this->assertContains('requires a name', $e->getMessage()); - } + $this->setExpectedException('Zend\Json\Server\Exception\InvalidArgumentException', 'requires a name'); + $service = new Service(null); + } + + public function testConstructorShouldThrowExceptionWhenNoNameSetWhenArrayProvided() + { + $this->setExpectedException('Zend\Json\Server\Exception\InvalidArgumentException', 'requires a name'); + $service = new Service(null); } public function testSettingNameShouldThrowExceptionWhenContainingInvalidFormat() { - try { - $this->service->setName('0ab-?'); - $this->fail('Invalid name should throw exception'); - } catch (Server\Exception $e) { - $this->assertContains('Invalid name', $e->getMessage()); - } - try { - $this->service->setName('ab-?'); - $this->fail('Invalid name should throw exception'); - } catch (Server\Exception $e) { - $this->assertContains('Invalid name', $e->getMessage()); - } + $this->setExpectedException('Zend\Json\Server\Exception\InvalidArgumentException', 'Invalid name'); + $this->service->setName('0ab-?'); } + public function testSettingNameShouldThrowExceptionWhenContainingInvalidFormatStartingWithInt() + { + $this->setExpectedException('Zend\Json\Server\Exception\InvalidArgumentException', 'Invalid name'); + $this->service->setName('0ab-?'); + } + public function testNameAccessorsShouldWorkWithNormalInput() { $this->assertEquals('foo', $this->service->getName()); @@ -96,22 +86,18 @@ public function testTransportShouldDefaultToPost() $this->assertEquals('POST', $this->service->getTransport()); } - public function testTransportShouldBeLimitedToPost() + public function testSettingTransportThrowsExceptionWhenSetToGet() { - try { - $this->service->setTransport('GET'); - $this->fail('Invalid transport should throw exception'); - } catch (Server\Exception $e) { - $this->assertContains('Invalid transport', $e->getMessage()); - } - try { - $this->service->setTransport('REST'); - $this->fail('Invalid transport should throw exception'); - } catch (Server\Exception $e) { - $this->assertContains('Invalid transport', $e->getMessage()); - } + $this->setExpectedException('Zend\Json\Server\Exception\InvalidArgumentException', 'Invalid transport'); + $this->service->setTransport('GET'); } + public function testSettingTransportThrowsExceptionWhenSetToRest() + { + $this->setExpectedException('Zend\Json\Server\Exception\InvalidArgumentException', 'Invalid transport'); + $this->service->setTransport('REST'); + } + public function testTransportAccessorsShouldWorkUnderNormalInput() { $this->service->setTransport('POST'); @@ -154,7 +140,7 @@ public function testEnvelopeShouldOnlyComplyWithJSONRpc1And2() try { $this->service->setEnvelope('JSON-P'); $this->fail('Should not be able to set non-JSON-RPC spec envelopes'); - } catch (Server\Exception $e) { + } catch (Server\Exception\InvalidArgumentException $e) { $this->assertContains('Invalid envelope', $e->getMessage()); } } @@ -187,12 +173,8 @@ public function testParamsShouldAcceptArrayOfTypes() public function testInvalidParamTypeShouldThrowException() { - try { - $this->service->addParam(new \stdClass); - $this->fail('Invalid param type should throw exception'); - } catch (Server\Exception $e) { - $this->assertContains('Invalid param type', $e->getMessage()); - } + $this->setExpectedException('Zend\Json\Server\Exception\InvalidArgumentException', 'Invalid param type'); + $this->service->addParam(new \stdClass); } public function testShouldBeAbleToOrderParams() @@ -289,12 +271,8 @@ public function testReturnAccessorsShouldAllowArrayOfTypes() public function testInvalidReturnTypeShouldThrowException() { - try { - $this->service->setReturn(new \stdClass); - $this->fail('Invalid return type should throw exception'); - } catch (Server\Exception $e) { - $this->assertContains('Invalid param type', $e->getMessage()); - } + $this->setExpectedException('Zend\Json\Server\Exception\InvalidArgumentException', 'Invalid param type'); + $this->service->setReturn(new \stdClass); } public function testToArrayShouldCreateSmdCompatibleHash() diff --git a/test/Server/SMDTest.php b/test/Server/SmdTest.php similarity index 96% rename from test/Server/SMDTest.php rename to test/Server/SmdTest.php index e4973a7d8..f70c1d4d2 100644 --- a/test/Server/SMDTest.php +++ b/test/Server/SmdTest.php @@ -17,7 +17,6 @@ * @subpackage UnitTests * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License - * @version $Id$ */ /** @@ -26,18 +25,20 @@ namespace ZendTest\Json\Server; use Zend\Json\Server\Smd, Zend\Json\Server, + Zend\Json\Server\Exception\InvalidArgumentException, + Zend\Json\Server\Exception\RuntimeException, Zend\Json; /** * Test class for Zend_JSON_Server_Smd * * @category Zend - * @package Zend_JSON_Server + * @package Zend_Json_Server * @subpackage UnitTests * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License - * @group Zend_JSON - * @group Zend_JSON_Server + * @group Zend_Json + * @group Zend_Json_Server */ class SmdTest extends \PHPUnit_Framework_TestCase { @@ -69,7 +70,7 @@ public function testTransportShouldBeLimitedToPost() try { $this->smd->setTransport($transport); $this->fail('Invalid transport should throw exception'); - } catch (Server\Exception $e) { + } catch (InvalidArgumentException $e) { $this->assertContains('Invalid transport', $e->getMessage()); } } @@ -95,7 +96,7 @@ public function testEnvelopeShouldBeLimitedToJSONRpcVersions() try { $this->smd->setEnvelope($env); $this->fail('Invalid envelope type should throw exception'); - } catch (Server\Exception $e) { + } catch (InvalidArgumentException $e) { $this->assertContains('Invalid envelope', $e->getMessage()); } } @@ -120,7 +121,7 @@ public function testContentTypeShouldBeLimitedToMimeFormatStrings() try { $this->smd->setContentType($type); $this->fail('Invalid content type should raise exception'); - } catch (Server\Exception $e) { + } catch (InvalidArgumentException $e) { $this->assertContains('Invalid content type', $e->getMessage()); } } @@ -209,7 +210,7 @@ public function testAddingServiceWithExistingServiceNameShouldThrowException() try { $this->smd->addService($test); $this->fail('Adding service with existing service name should throw exception'); - } catch (Server\Exception $e) { + } catch (RuntimeException $e) { $this->assertContains('already register', $e->getMessage()); } } @@ -220,7 +221,7 @@ public function testAttemptingToRegisterInvalidServiceShouldThrowException() try { $this->smd->addService($service); $this->fail('Attempt to register invalid service should throw exception'); - } catch (Server\Exception $e) { + } catch (InvalidArgumentException $e) { $this->assertContains('Invalid service', $e->getMessage()); } } diff --git a/test/ServerTest.php b/test/ServerTest.php index a5614936a..9695b3b63 100644 --- a/test/ServerTest.php +++ b/test/ServerTest.php @@ -17,7 +17,6 @@ * @subpackage UnitTests * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License - * @version $Id$ */ /**