CC-2166: Packaging Improvements. Moved the Zend app into airtime_mvc. It is now installed to /var/www/airtime. Storage is now set to /srv/airtime/stor. Utils are now installed to /usr/lib/airtime/utils/. Added install/airtime-dircheck.php as a simple test to see if everything is install/uninstalled correctly.

This commit is contained in:
Paul Baranowski 2011-04-14 18:55:04 -04:00
parent 514777e8d2
commit b11cbd8159
4546 changed files with 138 additions and 51 deletions

View file

@ -0,0 +1,578 @@
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @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
* @version $Id: Decoder.php 20096 2010-01-06 02:05:09Z bkarwin $
*/
/**
* @see Zend_Json
*/
require_once 'Zend/Json.php';
/**
* Decode JSON encoded string to PHP variable constructs
*
* @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 Zend_Json_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 LBRACE = 2;
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
*
* @var string
*/
protected $_source;
/**
* Caches the source length
*
* @var int
*/
protected $_sourceLength;
/**
* The offset within the souce being decoded
*
* @var int
*
*/
protected $_offset;
/**
* The current token being considered in the parser cycle
*
* @var int
*/
protected $_token;
/**
* Flag indicating how objects should be decoded
*
* @var int
* @access protected
*/
protected $_decodeType;
/**
* Constructor
*
* @param string $source String source to decode
* @param int $decodeType How objects should be decoded -- see
* {@link Zend_Json::TYPE_ARRAY} and {@link Zend_Json::TYPE_OBJECT} for
* valid values
* @return void
*/
protected function __construct($source, $decodeType)
{
// Set defaults
$this->_source = self::decodeUnicodeString($source);
$this->_sourceLength = strlen($this->_source);
$this->_token = self::EOF;
$this->_offset = 0;
// Normalize and set $decodeType
if (!in_array($decodeType, array(Zend_Json::TYPE_ARRAY, Zend_Json::TYPE_OBJECT)))
{
$decodeType = Zend_Json::TYPE_ARRAY;
}
$this->_decodeType = $decodeType;
// Set pointer at first token
$this->_getNextToken();
}
/**
* Decode a JSON source string
*
* Decodes a JSON encoded string. The value returned will be one of the
* following:
* - integer
* - float
* - boolean
* - null
* - StdClass
* - array
* - array of one or more of the above types
*
* By default, decoded objects will be returned as associative arrays; to
* 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
* @param int $objectDecodeType How objects should be decoded; should be
* 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 = Zend_Json::TYPE_ARRAY)
{
if (null === $source) {
require_once 'Zend/Json/Exception.php';
throw new Zend_Json_Exception('Must specify JSON encoded source for decoding');
} elseif (!is_string($source)) {
require_once 'Zend/Json/Exception.php';
throw new Zend_Json_Exception('Can only decode JSON encoded strings');
}
$decoder = new self($source, $objectDecodeType);
return $decoder->_decodeValue();
}
/**
* Recursive driving rountine for supported toplevel tops
*
* @return mixed
*/
protected function _decodeValue()
{
switch ($this->_token) {
case self::DATUM:
$result = $this->_tokenValue;
$this->_getNextToken();
return($result);
break;
case self::LBRACE:
return($this->_decodeObject());
break;
case self::LBRACKET:
return($this->_decodeArray());
break;
default:
return null;
break;
}
}
/**
* Decodes an object of the form:
* { "attribute: value, "attribute2" : value,...}
*
* If Zend_Json_Encoder was used to encode the original object then
* a special attribute called __className which specifies a class
* name that should wrap the data contained within the encoded source.
*
* Decodes to either an array or StdClass object, based on the value of
* {@link $_decodeType}. If invalid $_decodeType present, returns as an
* array.
*
* @return array|StdClass
*/
protected function _decodeObject()
{
$members = array();
$tok = $this->_getNextToken();
while ($tok && $tok != self::RBRACE) {
if ($tok != self::DATUM || ! is_string($this->_tokenValue)) {
require_once 'Zend/Json/Exception.php';
throw new Zend_Json_Exception('Missing key in object encoding: ' . $this->_source);
}
$key = $this->_tokenValue;
$tok = $this->_getNextToken();
if ($tok != self::COLON) {
require_once 'Zend/Json/Exception.php';
throw new Zend_Json_Exception('Missing ":" in object encoding: ' . $this->_source);
}
$tok = $this->_getNextToken();
$members[$key] = $this->_decodeValue();
$tok = $this->_token;
if ($tok == self::RBRACE) {
break;
}
if ($tok != self::COMMA) {
require_once 'Zend/Json/Exception.php';
throw new Zend_Json_Exception('Missing "," in object encoding: ' . $this->_source);
}
$tok = $this->_getNextToken();
}
switch ($this->_decodeType) {
case Zend_Json::TYPE_OBJECT:
// Create new StdClass and populate with $members
$result = new StdClass();
foreach ($members as $key => $value) {
$result->$key = $value;
}
break;
case Zend_Json::TYPE_ARRAY:
default:
$result = $members;
break;
}
$this->_getNextToken();
return $result;
}
/**
* Decodes a JSON array format:
* [element, element2,...,elementN]
*
* @return array
*/
protected function _decodeArray()
{
$result = array();
$starttok = $tok = $this->_getNextToken(); // Move past the '['
$index = 0;
while ($tok && $tok != self::RBRACKET) {
$result[$index++] = $this->_decodeValue();
$tok = $this->_token;
if ($tok == self::RBRACKET || !$tok) {
break;
}
if ($tok != self::COMMA) {
require_once 'Zend/Json/Exception.php';
throw new Zend_Json_Exception('Missing "," in array encoding: ' . $this->_source);
}
$tok = $this->_getNextToken();
}
$this->_getNextToken();
return($result);
}
/**
* Removes whitepsace characters from the source input
*/
protected function _eatWhitespace()
{
if (preg_match(
'/([\t\b\f\n\r ])*/s',
$this->_source,
$matches,
PREG_OFFSET_CAPTURE,
$this->_offset)
&& $matches[0][1] == $this->_offset)
{
$this->_offset += strlen($matches[0][0]);
}
}
/**
* Retrieves the next token from the source stream
*
* @return int Token constant value specified in class definition
*/
protected function _getNextToken()
{
$this->_token = self::EOF;
$this->_tokenValue = null;
$this->_eatWhitespace();
if ($this->_offset >= $this->_sourceLength) {
return(self::EOF);
}
$str = $this->_source;
$str_length = $this->_sourceLength;
$i = $this->_offset;
$start = $i;
switch ($str{$i}) {
case '{':
$this->_token = self::LBRACE;
break;
case '}':
$this->_token = self::RBRACE;
break;
case '[':
$this->_token = self::LBRACKET;
break;
case ']':
$this->_token = self::RBRACKET;
break;
case ',':
$this->_token = self::COMMA;
break;
case ':':
$this->_token = self::COLON;
break;
case '"':
$result = '';
do {
$i++;
if ($i >= $str_length) {
break;
}
$chr = $str{$i};
if ($chr == '\\') {
$i++;
if ($i >= $str_length) {
break;
}
$chr = $str{$i};
switch ($chr) {
case '"' :
$result .= '"';
break;
case '\\':
$result .= '\\';
break;
case '/' :
$result .= '/';
break;
case 'b' :
$result .= chr(8);
break;
case 'f' :
$result .= chr(12);
break;
case 'n' :
$result .= chr(10);
break;
case 'r' :
$result .= chr(13);
break;
case 't' :
$result .= chr(9);
break;
case '\'' :
$result .= '\'';
break;
default:
require_once 'Zend/Json/Exception.php';
throw new Zend_Json_Exception("Illegal escape "
. "sequence '" . $chr . "'");
}
} elseif($chr == '"') {
break;
} else {
$result .= $chr;
}
} while ($i < $str_length);
$this->_token = self::DATUM;
//$this->_tokenValue = substr($str, $start + 1, $i - $start - 1);
$this->_tokenValue = $result;
break;
case 't':
if (($i+ 3) < $str_length && substr($str, $start, 4) == "true") {
$this->_token = self::DATUM;
}
$this->_tokenValue = true;
$i += 3;
break;
case 'f':
if (($i+ 4) < $str_length && substr($str, $start, 5) == "false") {
$this->_token = self::DATUM;
}
$this->_tokenValue = false;
$i += 4;
break;
case 'n':
if (($i+ 3) < $str_length && substr($str, $start, 4) == "null") {
$this->_token = self::DATUM;
}
$this->_tokenValue = NULL;
$i += 3;
break;
}
if ($this->_token != self::EOF) {
$this->_offset = $i + 1; // Consume the last token character
return($this->_token);
}
$chr = $str{$i};
if ($chr == '-' || $chr == '.' || ($chr >= '0' && $chr <= '9')) {
if (preg_match('/-?([0-9])*(\.[0-9]*)?((e|E)((-|\+)?)[0-9]+)?/s',
$str, $matches, PREG_OFFSET_CAPTURE, $start) && $matches[0][1] == $start) {
$datum = $matches[0][0];
if (is_numeric($datum)) {
if (preg_match('/^0\d+$/', $datum)) {
require_once 'Zend/Json/Exception.php';
throw new Zend_Json_Exception("Octal notation not supported by JSON (value: $datum)");
} else {
$val = intval($datum);
$fVal = floatval($datum);
$this->_tokenValue = ($val == $fVal ? $val : $fVal);
}
} else {
require_once 'Zend/Json/Exception.php';
throw new Zend_Json_Exception("Illegal number format: $datum");
}
$this->_token = self::DATUM;
$this->_offset = $start + strlen($datum);
}
} else {
require_once 'Zend/Json/Exception.php';
throw new Zend_Json_Exception('Illegal Token');
}
return($this->_token);
}
/**
* Decode Unicode Characters from \u0000 ASCII syntax.
*
* This algorithm was originally developed for the
* Solar Framework by Paul M. Jones
*
* @link http://solarphp.com/
* @link http://svn.solarphp.com/core/trunk/Solar/Json.php
* @param string $value
* @return string
*/
public static function decodeUnicodeString($chrs)
{
$delim = substr($chrs, 0, 1);
$utf8 = '';
$strlen_chrs = strlen($chrs);
for($i = 0; $i < $strlen_chrs; $i++) {
$substr_chrs_c_2 = substr($chrs, $i, 2);
$ord_chrs_c = ord($chrs[$i]);
switch (true) {
case preg_match('/\\\u[0-9A-F]{4}/i', substr($chrs, $i, 6)):
// single, escaped unicode character
$utf16 = chr(hexdec(substr($chrs, ($i + 2), 2)))
. chr(hexdec(substr($chrs, ($i + 4), 2)));
$utf8 .= self::_utf162utf8($utf16);
$i += 5;
break;
case ($ord_chrs_c >= 0x20) && ($ord_chrs_c <= 0x7F):
$utf8 .= $chrs{$i};
break;
case ($ord_chrs_c & 0xE0) == 0xC0:
// characters U-00000080 - U-000007FF, mask 110XXXXX
//see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
$utf8 .= substr($chrs, $i, 2);
++$i;
break;
case ($ord_chrs_c & 0xF0) == 0xE0:
// characters U-00000800 - U-0000FFFF, mask 1110XXXX
// see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
$utf8 .= substr($chrs, $i, 3);
$i += 2;
break;
case ($ord_chrs_c & 0xF8) == 0xF0:
// characters U-00010000 - U-001FFFFF, mask 11110XXX
// see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
$utf8 .= substr($chrs, $i, 4);
$i += 3;
break;
case ($ord_chrs_c & 0xFC) == 0xF8:
// characters U-00200000 - U-03FFFFFF, mask 111110XX
// see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
$utf8 .= substr($chrs, $i, 5);
$i += 4;
break;
case ($ord_chrs_c & 0xFE) == 0xFC:
// characters U-04000000 - U-7FFFFFFF, mask 1111110X
// see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
$utf8 .= substr($chrs, $i, 6);
$i += 5;
break;
}
}
return $utf8;
}
/**
* Convert a string from one UTF-16 char to one UTF-8 char.
*
* Normally should be handled by mb_convert_encoding, but
* provides a slower PHP-only method for installations
* that lack the multibye string extension.
*
* This method is from the Solar Framework by Paul M. Jones
*
* @link http://solarphp.com
* @param string $utf16 UTF-16 character
* @return string UTF-8 character
*/
protected static function _utf162utf8($utf16)
{
// Check for mb extension otherwise do by hand.
if( function_exists('mb_convert_encoding') ) {
return mb_convert_encoding($utf16, 'UTF-8', 'UTF-16');
}
$bytes = (ord($utf16{0}) << 8) | ord($utf16{1});
switch (true) {
case ((0x7F & $bytes) == $bytes):
// this case should never be reached, because we are in ASCII range
// see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
return chr(0x7F & $bytes);
case (0x07FF & $bytes) == $bytes:
// return a 2-byte UTF-8 character
// see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
return chr(0xC0 | (($bytes >> 6) & 0x1F))
. chr(0x80 | ($bytes & 0x3F));
case (0xFFFF & $bytes) == $bytes:
// return a 3-byte UTF-8 character
// see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
return chr(0xE0 | (($bytes >> 12) & 0x0F))
. chr(0x80 | (($bytes >> 6) & 0x3F))
. chr(0x80 | ($bytes & 0x3F));
}
// ignoring UTF-32 for now, sorry
return '';
}
}

View file

@ -0,0 +1,574 @@
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @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
* @version $Id: Encoder.php 20096 2010-01-06 02:05:09Z bkarwin $
*/
/**
* Encode PHP constructs to JSON
*
* @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 Zend_Json_Encoder
{
/**
* Whether or not to check for possible cycling
*
* @var boolean
*/
protected $_cycleCheck;
/**
* Additional options used during encoding
*
* @var array
*/
protected $_options = array();
/**
* Array of visited objects; used to prevent cycling.
*
* @var array
*/
protected $_visited = array();
/**
* Constructor
*
* @param boolean $cycleCheck Whether or not to check for recursion when encoding
* @param array $options Additional options used during encoding
* @return void
*/
protected function __construct($cycleCheck = false, $options = array())
{
$this->_cycleCheck = $cycleCheck;
$this->_options = $options;
}
/**
* Use the JSON encoding scheme for the value specified
*
* @param mixed $value The value to be encoded
* @param boolean $cycleCheck Whether or not to check for possible object recursion when encoding
* @param array $options Additional options used during encoding
* @return string The encoded value
*/
public static function encode($value, $cycleCheck = false, $options = array())
{
$encoder = new self(($cycleCheck) ? true : false, $options);
return $encoder->_encodeValue($value);
}
/**
* Recursive driver which determines the type of value to be encoded
* and then dispatches to the appropriate method. $values are either
* - objects (returns from {@link _encodeObject()})
* - arrays (returns from {@link _encodeArray()})
* - basic datums (e.g. numbers or strings) (returns from {@link _encodeDatum()})
*
* @param $value mixed The value to be encoded
* @return string Encoded value
*/
protected function _encodeValue(&$value)
{
if (is_object($value)) {
return $this->_encodeObject($value);
} else if (is_array($value)) {
return $this->_encodeArray($value);
}
return $this->_encodeDatum($value);
}
/**
* Encode an object to JSON by encoding each of the public properties
*
* A special property is added to the JSON object called '__className'
* that contains the name of the class of $value. This is used to decode
* the object on the client into a specific class.
*
* @param $value object
* @return string
* @throws Zend_Json_Exception If recursive checks are enabled and the object has been serialized previously
*/
protected function _encodeObject(&$value)
{
if ($this->_cycleCheck) {
if ($this->_wasVisited($value)) {
if (isset($this->_options['silenceCyclicalExceptions'])
&& $this->_options['silenceCyclicalExceptions']===true) {
return '"* RECURSION (' . get_class($value) . ') *"';
} else {
require_once 'Zend/Json/Exception.php';
throw new Zend_Json_Exception(
'Cycles not supported in JSON encoding, cycle introduced by '
. 'class "' . get_class($value) . '"'
);
}
}
$this->_visited[] = $value;
}
$props = '';
if ($value instanceof Iterator) {
$propCollection = $value;
} else {
$propCollection = get_object_vars($value);
}
foreach ($propCollection as $name => $propValue) {
if (isset($propValue)) {
$props .= ','
. $this->_encodeValue($name)
. ':'
. $this->_encodeValue($propValue);
}
}
return '{"__className":"' . get_class($value) . '"'
. $props . '}';
}
/**
* Determine if an object has been serialized already
*
* @param mixed $value
* @return boolean
*/
protected function _wasVisited(&$value)
{
if (in_array($value, $this->_visited, true)) {
return true;
}
return false;
}
/**
* JSON encode an array value
*
* Recursively encodes each value of an array and returns a JSON encoded
* array string.
*
* Arrays are defined as integer-indexed arrays starting at index 0, where
* the last index is (count($array) -1); any deviation from that is
* considered an associative array, and will be encoded as such.
*
* @param $array array
* @return string
*/
protected function _encodeArray(&$array)
{
$tmpArray = array();
// Check for associative array
if (!empty($array) && (array_keys($array) !== range(0, count($array) - 1))) {
// Associative array
$result = '{';
foreach ($array as $key => $value) {
$key = (string) $key;
$tmpArray[] = $this->_encodeString($key)
. ':'
. $this->_encodeValue($value);
}
$result .= implode(',', $tmpArray);
$result .= '}';
} else {
// Indexed array
$result = '[';
$length = count($array);
for ($i = 0; $i < $length; $i++) {
$tmpArray[] = $this->_encodeValue($array[$i]);
}
$result .= implode(',', $tmpArray);
$result .= ']';
}
return $result;
}
/**
* JSON encode a basic data type (string, number, boolean, null)
*
* If value type is not a string, number, boolean, or null, the string
* 'null' is returned.
*
* @param $value mixed
* @return string
*/
protected function _encodeDatum(&$value)
{
$result = 'null';
if (is_int($value) || is_float($value)) {
$result = (string) $value;
$result = str_replace(",", ".", $result);
} elseif (is_string($value)) {
$result = $this->_encodeString($value);
} elseif (is_bool($value)) {
$result = $value ? 'true' : 'false';
}
return $result;
}
/**
* JSON encode a string value by escaping characters as necessary
*
* @param $value string
* @return string
*/
protected function _encodeString(&$string)
{
// Escape these characters with a backslash:
// " \ / \n \r \t \b \f
$search = array('\\', "\n", "\t", "\r", "\b", "\f", '"', '/');
$replace = array('\\\\', '\\n', '\\t', '\\r', '\\b', '\\f', '\"', '\\/');
$string = str_replace($search, $replace, $string);
// Escape certain ASCII characters:
// 0x08 => \b
// 0x0c => \f
$string = str_replace(array(chr(0x08), chr(0x0C)), array('\b', '\f'), $string);
$string = self::encodeUnicodeString($string);
return '"' . $string . '"';
}
/**
* Encode the constants associated with the ReflectionClass
* parameter. The encoding format is based on the class2 format
*
* @param $cls ReflectionClass
* @return string Encoded constant block in class2 format
*/
private static function _encodeConstants(ReflectionClass $cls)
{
$result = "constants : {";
$constants = $cls->getConstants();
$tmpArray = array();
if (!empty($constants)) {
foreach ($constants as $key => $value) {
$tmpArray[] = "$key: " . self::encode($value);
}
$result .= implode(', ', $tmpArray);
}
return $result . "}";
}
/**
* Encode the public methods of the ReflectionClass in the
* class2 format
*
* @param $cls ReflectionClass
* @return string Encoded method fragment
*
*/
private static function _encodeMethods(ReflectionClass $cls)
{
$methods = $cls->getMethods();
$result = 'methods:{';
$started = false;
foreach ($methods as $method) {
if (! $method->isPublic() || !$method->isUserDefined()) {
continue;
}
if ($started) {
$result .= ',';
}
$started = true;
$result .= '' . $method->getName(). ':function(';
if ('__construct' != $method->getName()) {
$parameters = $method->getParameters();
$paramCount = count($parameters);
$argsStarted = false;
$argNames = "var argNames=[";
foreach ($parameters as $param) {
if ($argsStarted) {
$result .= ',';
}
$result .= $param->getName();
if ($argsStarted) {
$argNames .= ',';
}
$argNames .= '"' . $param->getName() . '"';
$argsStarted = true;
}
$argNames .= "];";
$result .= "){"
. $argNames
. 'var result = ZAjaxEngine.invokeRemoteMethod('
. "this, '" . $method->getName()
. "',argNames,arguments);"
. 'return(result);}';
} else {
$result .= "){}";
}
}
return $result . "}";
}
/**
* Encode the public properties of the ReflectionClass in the class2
* format.
*
* @param $cls ReflectionClass
* @return string Encode properties list
*
*/
private static function _encodeVariables(ReflectionClass $cls)
{
$properties = $cls->getProperties();
$propValues = get_class_vars($cls->getName());
$result = "variables:{";
$cnt = 0;
$tmpArray = array();
foreach ($properties as $prop) {
if (! $prop->isPublic()) {
continue;
}
$tmpArray[] = $prop->getName()
. ':'
. self::encode($propValues[$prop->getName()]);
}
$result .= implode(',', $tmpArray);
return $result . "}";
}
/**
* Encodes the given $className into the class2 model of encoding PHP
* classes into JavaScript class2 classes.
* NOTE: Currently only public methods and variables are proxied onto
* the client machine
*
* @param $className string The name of the class, the class must be
* instantiable using a null constructor
* @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
*/
public static function encodeClass($className, $package = '')
{
$cls = new ReflectionClass($className);
if (! $cls->isInstantiable()) {
require_once 'Zend/Json/Exception.php';
throw new Zend_Json_Exception("$className must be instantiable");
}
return "Class.create('$package$className',{"
. self::_encodeConstants($cls) .","
. self::_encodeMethods($cls) .","
. self::_encodeVariables($cls) .'});';
}
/**
* Encode several classes at once
*
* Returns JSON encoded classes, using {@link encodeClass()}.
*
* @param array $classNames
* @param string $package
* @return string
*/
public static function encodeClasses(array $classNames, $package = '')
{
$result = '';
foreach ($classNames as $className) {
$result .= self::encodeClass($className, $package);
}
return $result;
}
/**
* Encode Unicode Characters to \u0000 ASCII syntax.
*
* This algorithm was originally developed for the
* Solar Framework by Paul M. Jones
*
* @link http://solarphp.com/
* @link http://svn.solarphp.com/core/trunk/Solar/Json.php
* @param string $value
* @return string
*/
public static function encodeUnicodeString($value)
{
$strlen_var = strlen($value);
$ascii = "";
/**
* Iterate over every character in the string,
* escaping with a slash or encoding to UTF-8 where necessary
*/
for($i = 0; $i < $strlen_var; $i++) {
$ord_var_c = ord($value[$i]);
switch (true) {
case (($ord_var_c >= 0x20) && ($ord_var_c <= 0x7F)):
// characters U-00000000 - U-0000007F (same as ASCII)
$ascii .= $value[$i];
break;
case (($ord_var_c & 0xE0) == 0xC0):
// characters U-00000080 - U-000007FF, mask 110XXXXX
// see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
$char = pack('C*', $ord_var_c, ord($value[$i + 1]));
$i += 1;
$utf16 = self::_utf82utf16($char);
$ascii .= sprintf('\u%04s', bin2hex($utf16));
break;
case (($ord_var_c & 0xF0) == 0xE0):
// characters U-00000800 - U-0000FFFF, mask 1110XXXX
// see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
$char = pack('C*', $ord_var_c,
ord($value[$i + 1]),
ord($value[$i + 2]));
$i += 2;
$utf16 = self::_utf82utf16($char);
$ascii .= sprintf('\u%04s', bin2hex($utf16));
break;
case (($ord_var_c & 0xF8) == 0xF0):
// characters U-00010000 - U-001FFFFF, mask 11110XXX
// see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
$char = pack('C*', $ord_var_c,
ord($value[$i + 1]),
ord($value[$i + 2]),
ord($value[$i + 3]));
$i += 3;
$utf16 = self::_utf82utf16($char);
$ascii .= sprintf('\u%04s', bin2hex($utf16));
break;
case (($ord_var_c & 0xFC) == 0xF8):
// characters U-00200000 - U-03FFFFFF, mask 111110XX
// see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
$char = pack('C*', $ord_var_c,
ord($value[$i + 1]),
ord($value[$i + 2]),
ord($value[$i + 3]),
ord($value[$i + 4]));
$i += 4;
$utf16 = self::_utf82utf16($char);
$ascii .= sprintf('\u%04s', bin2hex($utf16));
break;
case (($ord_var_c & 0xFE) == 0xFC):
// characters U-04000000 - U-7FFFFFFF, mask 1111110X
// see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
$char = pack('C*', $ord_var_c,
ord($value[$i + 1]),
ord($value[$i + 2]),
ord($value[$i + 3]),
ord($value[$i + 4]),
ord($value[$i + 5]));
$i += 5;
$utf16 = self::_utf82utf16($char);
$ascii .= sprintf('\u%04s', bin2hex($utf16));
break;
}
}
return $ascii;
}
/**
* Convert a string from one UTF-8 char to one UTF-16 char.
*
* Normally should be handled by mb_convert_encoding, but
* provides a slower PHP-only method for installations
* that lack the multibye string extension.
*
* This method is from the Solar Framework by Paul M. Jones
*
* @link http://solarphp.com
* @param string $utf8 UTF-8 character
* @return string UTF-16 character
*/
protected static function _utf82utf16($utf8)
{
// Check for mb extension otherwise do by hand.
if( function_exists('mb_convert_encoding') ) {
return mb_convert_encoding($utf8, 'UTF-16', 'UTF-8');
}
switch (strlen($utf8)) {
case 1:
// this case should never be reached, because we are in ASCII range
// see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
return $utf8;
case 2:
// return a UTF-16 character from a 2-byte UTF-8 char
// see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
return chr(0x07 & (ord($utf8{0}) >> 2))
. chr((0xC0 & (ord($utf8{0}) << 6))
| (0x3F & ord($utf8{1})));
case 3:
// return a UTF-16 character from a 3-byte UTF-8 char
// see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
return chr((0xF0 & (ord($utf8{0}) << 4))
| (0x0F & (ord($utf8{1}) >> 2)))
. chr((0xC0 & (ord($utf8{1}) << 6))
| (0x7F & ord($utf8{2})));
}
// ignoring UTF-32 for now, sorry
return '';
}
}

View file

@ -0,0 +1,37 @@
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @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
* @version $Id: Exception.php 20096 2010-01-06 02:05:09Z bkarwin $
*/
/**
* Zend_Exception
*/
require_once 'Zend/Exception.php';
/**
* @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 Zend_Json_Exception extends Zend_Exception
{}

View file

@ -0,0 +1,80 @@
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Json
* @subpackage Expr
* @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: Expr.php 20096 2010-01-06 02:05:09Z bkarwin $
*/
/**
* Class for Zend_Json encode method.
*
* This class simply holds a string with a native Javascript Expression,
* so objects | arrays to be encoded with Zend_Json can contain native
* Javascript Expressions.
*
* Example:
* <code>
* $foo = array(
* 'integer' =>9,
* 'string' =>'test string',
* 'function' => Zend_Json_Expr(
* 'function(){ window.alert("javascript function encoded by Zend_Json") }'
* ),
* );
*
* Zend_Json::encode($foo, false, array('enableJsonExprFinder' => true));
* // it will returns json encoded string:
* // {"integer":9,"string":"test string","function":function(){window.alert("javascript function encoded by Zend_Json")}}
* </code>
*
* @category Zend
* @package Zend_Json
* @subpackage Expr
* @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 Zend_Json_Expr
{
/**
* Storage for javascript expression.
*
* @var string
*/
protected $_expression;
/**
* Constructor
*
* @param string $expression the expression to hold.
* @return void
*/
public function __construct($expression)
{
$this->_expression = (string) $expression;
}
/**
* Cast to string
*
* @return string holded javascript expression.
*/
public function __toString()
{
return $this->_expression;
}
}

View file

@ -0,0 +1,537 @@
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @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
* @version $Id: Server.php 20096 2010-01-06 02:05:09Z bkarwin $
*/
/**
* @see Zend_Server_Abstract
*/
require_once 'Zend/Server/Abstract.php';
/**
* @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 Zend_Json_Server extends Zend_Server_Abstract
{
/**#@+
* Version Constants
*/
const VERSION_1 = '1.0';
const VERSION_2 = '2.0';
/**#@-*/
/**
* Flag: whether or not to auto-emit the response
* @var bool
*/
protected $_autoEmitResponse = true;
/**
* @var bool Flag; allow overwriting existing methods when creating server definition
*/
protected $_overwriteExistingMethods = true;
/**
* Request object
* @var Zend_Json_Server_Request
*/
protected $_request;
/**
* Response object
* @var Zend_Json_Server_Response
*/
protected $_response;
/**
* SMD object
* @var Zend_Json_Server_Smd
*/
protected $_serviceMap;
/**
* SMD class accessors
* @var array
*/
protected $_smdMethods;
/**
* @var Zend_Server_Description
*/
protected $_table;
/**
* Attach a function or callback to the server
*
* @param string|array $function Valid PHP callback
* @param string $namespace Ignored
* @return Zend_Json_Server
*/
public function addFunction($function, $namespace = '')
{
if (!is_string($function) && (!is_array($function) || (2 > count($function)))) {
require_once 'Zend/Json/Server/Exception.php';
throw new Zend_Json_Server_Exception('Unable to attach function; invalid');
}
if (!is_callable($function)) {
require_once 'Zend/Json/Server/Exception.php';
throw new Zend_Json_Server_Exception('Unable to attach function; does not exist');
}
$argv = null;
if (2 < func_num_args()) {
$argv = func_get_args();
$argv = array_slice($argv, 2);
}
require_once 'Zend/Server/Reflection.php';
if (is_string($function)) {
$method = Zend_Server_Reflection::reflectFunction($function, $argv, $namespace);
} else {
$class = array_shift($function);
$action = array_shift($function);
$reflection = Zend_Server_Reflection::reflectClass($class, $argv, $namespace);
$methods = $reflection->getMethods();
$found = false;
foreach ($methods as $method) {
if ($action == $method->getName()) {
$found = true;
break;
}
}
if (!$found) {
$this->fault('Method not found', -32601);
return $this;
}
}
$definition = $this->_buildSignature($method);
$this->_addMethodServiceMap($definition);
return $this;
}
/**
* Register a class with the server
*
* @param string $class
* @param string $namespace Ignored
* @param mixed $argv Ignored
* @return Zend_Json_Server
*/
public function setClass($class, $namespace = '', $argv = null)
{
$argv = null;
if (3 < func_num_args()) {
$argv = func_get_args();
$argv = array_slice($argv, 3);
}
require_once 'Zend/Server/Reflection.php';
$reflection = Zend_Server_Reflection::reflectClass($class, $argv, $namespace);
foreach ($reflection->getMethods() as $method) {
$definition = $this->_buildSignature($method, $class);
$this->_addMethodServiceMap($definition);
}
return $this;
}
/**
* Indicate fault response
*
* @param string $fault
* @param int $code
* @return false
*/
public function fault($fault = null, $code = 404, $data = null)
{
require_once 'Zend/Json/Server/Error.php';
$error = new Zend_Json_Server_Error($fault, $code, $data);
$this->getResponse()->setError($error);
return $error;
}
/**
* Handle request
*
* @param Zend_Json_Server_Request $request
* @return null|Zend_Json_Server_Response
*/
public function handle($request = false)
{
if ((false !== $request) && (!$request instanceof Zend_Json_Server_Request)) {
require_once 'Zend/Json/Server/Exception.php';
throw new Zend_Json_Server_Exception('Invalid request type provided; cannot handle');
} elseif ($request) {
$this->setRequest($request);
}
// Handle request
$this->_handle();
// Get response
$response = $this->_getReadyResponse();
// Emit response?
if ($this->autoEmitResponse()) {
echo $response;
return;
}
// or return it?
return $response;
}
/**
* Load function definitions
*
* @param array|Zend_Server_Definition $definition
* @return void
*/
public function loadFunctions($definition)
{
if (!is_array($definition) && (!$definition instanceof Zend_Server_Definition)) {
require_once 'Zend/Json/Server/Exception.php';
throw new Zend_Json_Server_Exception('Invalid definition provided to loadFunctions()');
}
foreach ($definition as $key => $method) {
$this->_table->addMethod($method, $key);
$this->_addMethodServiceMap($method);
}
}
public function setPersistence($mode)
{
}
/**
* Set request object
*
* @param Zend_Json_Server_Request $request
* @return Zend_Json_Server
*/
public function setRequest(Zend_Json_Server_Request $request)
{
$this->_request = $request;
return $this;
}
/**
* Get JSON-RPC request object
*
* @return Zend_Json_Server_Request
*/
public function getRequest()
{
if (null === ($request = $this->_request)) {
require_once 'Zend/Json/Server/Request/Http.php';
$this->setRequest(new Zend_Json_Server_Request_Http());
}
return $this->_request;
}
/**
* Set response object
*
* @param Zend_Json_Server_Response $response
* @return Zend_Json_Server
*/
public function setResponse(Zend_Json_Server_Response $response)
{
$this->_response = $response;
return $this;
}
/**
* Get response object
*
* @return Zend_Json_Server_Response
*/
public function getResponse()
{
if (null === ($response = $this->_response)) {
require_once 'Zend/Json/Server/Response/Http.php';
$this->setResponse(new Zend_Json_Server_Response_Http());
}
return $this->_response;
}
/**
* Set flag indicating whether or not to auto-emit response
*
* @param bool $flag
* @return Zend_Json_Server
*/
public function setAutoEmitResponse($flag)
{
$this->_autoEmitResponse = (bool) $flag;
return $this;
}
/**
* Will we auto-emit the response?
*
* @return bool
*/
public function autoEmitResponse()
{
return $this->_autoEmitResponse;
}
// overloading for SMD metadata
/**
* Overload to accessors of SMD object
*
* @param string $method
* @param array $args
* @return mixed
*/
public function __call($method, $args)
{
if (preg_match('/^(set|get)/', $method, $matches)) {
if (in_array($method, $this->_getSmdMethods())) {
if ('set' == $matches[1]) {
$value = array_shift($args);
$this->getServiceMap()->$method($value);
return $this;
} else {
return $this->getServiceMap()->$method();
}
}
}
return null;
}
/**
* Retrieve SMD object
*
* @return Zend_Json_Server_Smd
*/
public function getServiceMap()
{
if (null === $this->_serviceMap) {
require_once 'Zend/Json/Server/Smd.php';
$this->_serviceMap = new Zend_Json_Server_Smd();
}
return $this->_serviceMap;
}
/**
* Add service method to service map
*
* @param Zend_Server_Reflection_Function $method
* @return void
*/
protected function _addMethodServiceMap(Zend_Server_Method_Definition $method)
{
$serviceInfo = array(
'name' => $method->getName(),
'return' => $this->_getReturnType($method),
);
$params = $this->_getParams($method);
$serviceInfo['params'] = $params;
$serviceMap = $this->getServiceMap();
if (false !== $serviceMap->getService($serviceInfo['name'])) {
$serviceMap->removeService($serviceInfo['name']);
}
$serviceMap->addService($serviceInfo);
}
/**
* Translate PHP type to JSON type
*
* @param string $type
* @return string
*/
protected function _fixType($type)
{
return $type;
}
/**
* Get default params from signature
*
* @param array $args
* @param array $params
* @return array
*/
protected function _getDefaultParams(array $args, array $params)
{
$defaultParams = array_slice($params, count($args));
foreach ($defaultParams as $param) {
$value = null;
if (array_key_exists('default', $param)) {
$value = $param['default'];
}
array_push($args, $value);
}
return $args;
}
/**
* Get method param type
*
* @param Zend_Server_Reflection_Function_Abstract $method
* @return string|array
*/
protected function _getParams(Zend_Server_Method_Definition $method)
{
$params = array();
foreach ($method->getPrototypes() as $prototype) {
foreach ($prototype->getParameterObjects() as $key => $parameter) {
if (!isset($params[$key])) {
$params[$key] = array(
'type' => $parameter->getType(),
'name' => $parameter->getName(),
'optional' => $parameter->isOptional(),
);
if (null !== ($default = $parameter->getDefaultValue())) {
$params[$key]['default'] = $default;
}
$description = $parameter->getDescription();
if (!empty($description)) {
$params[$key]['description'] = $description;
}
continue;
}
$newType = $parameter->getType();
if (!is_array($params[$key]['type'])) {
if ($params[$key]['type'] == $newType) {
continue;
}
$params[$key]['type'] = (array) $params[$key]['type'];
} elseif (in_array($newType, $params[$key]['type'])) {
continue;
}
array_push($params[$key]['type'], $parameter->getType());
}
}
return $params;
}
/**
* Set response state
*
* @return Zend_Json_Server_Response
*/
protected function _getReadyResponse()
{
$request = $this->getRequest();
$response = $this->getResponse();
$response->setServiceMap($this->getServiceMap());
if (null !== ($id = $request->getId())) {
$response->setId($id);
}
if (null !== ($version = $request->getVersion())) {
$response->setVersion($version);
}
return $response;
}
/**
* Get method return type
*
* @param Zend_Server_Reflection_Function_Abstract $method
* @return string|array
*/
protected function _getReturnType(Zend_Server_Method_Definition $method)
{
$return = array();
foreach ($method->getPrototypes() as $prototype) {
$return[] = $prototype->getReturnType();
}
if (1 == count($return)) {
return $return[0];
}
return $return;
}
/**
* Retrieve list of allowed SMD methods for proxying
*
* @return array
*/
protected function _getSmdMethods()
{
if (null === $this->_smdMethods) {
$this->_smdMethods = array();
require_once 'Zend/Json/Server/Smd.php';
$methods = get_class_methods('Zend_Json_Server_Smd');
foreach ($methods as $key => $method) {
if (!preg_match('/^(set|get)/', $method)) {
continue;
}
if (strstr($method, 'Service')) {
continue;
}
$this->_smdMethods[] = $method;
}
}
return $this->_smdMethods;
}
/**
* Internal method for handling request
*
* @return void
*/
protected function _handle()
{
$request = $this->getRequest();
if (!$request->isMethodError() && (null === $request->getMethod())) {
return $this->fault('Invalid Request', -32600);
}
if ($request->isMethodError()) {
return $this->fault('Invalid Request', -32600);
}
$method = $request->getMethod();
if (!$this->_table->hasMethod($method)) {
return $this->fault('Method not found', -32601);
}
$params = $request->getParams();
$invocable = $this->_table->getMethod($method);
$serviceMap = $this->getServiceMap();
$service = $serviceMap->getService($method);
$serviceParams = $service->getParams();
if (count($params) < count($serviceParams)) {
$params = $this->_getDefaultParams($params, $serviceParams);
}
try {
$result = $this->_dispatch($invocable, $params);
} catch (Exception $e) {
return $this->fault($e->getMessage(), $e->getCode(), $e);
}
$this->getResponse()->setResult($result);
}
}

View file

@ -0,0 +1,102 @@
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @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
* @version $Id: Cache.php 20096 2010-01-06 02:05:09Z bkarwin $
*/
/** Zend_Server_Cache */
require_once 'Zend/Server/Cache.php';
/**
* Zend_Json_Server_Cache: cache Zend_Json_Server server definition and SMD
*
* @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 Zend_Json_Server_Cache extends Zend_Server_Cache
{
/**
* Cache a service map description (SMD) to a file
*
* Returns true on success, false on failure
*
* @param string $filename
* @param Zend_Json_Server $server
* @return boolean
*/
public static function saveSmd($filename, Zend_Json_Server $server)
{
if (!is_string($filename)
|| (!file_exists($filename) && !is_writable(dirname($filename))))
{
return false;
}
if (0 === @file_put_contents($filename, $server->getServiceMap()->toJson())) {
return false;
}
return true;
}
/**
* Retrieve a cached SMD
*
* On success, returns the cached SMD (a JSON string); an failure, returns
* boolean false.
*
* @param string $filename
* @return string|false
*/
public static function getSmd($filename)
{
if (!is_string($filename)
|| !file_exists($filename)
|| !is_readable($filename))
{
return false;
}
if (false === ($smd = @file_get_contents($filename))) {
return false;
}
return $smd;
}
/**
* Delete a file containing a cached SMD
*
* @param string $filename
* @return bool
*/
public static function deleteSmd($filename)
{
if (is_string($filename) && file_exists($filename)) {
unlink($filename);
return true;
}
return false;
}
}

View file

@ -0,0 +1,198 @@
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @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
* @version $Id: Error.php 20096 2010-01-06 02:05:09Z bkarwin $
*/
/**
* @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 Zend_Json_Server_Error
{
const ERROR_PARSE = -32768;
const ERROR_INVALID_REQUEST = -32600;
const ERROR_INVALID_METHOD = -32601;
const ERROR_INVALID_PARAMS = -32602;
const ERROR_INTERNAL = -32603;
const ERROR_OTHER = -32000;
/**
* Allowed error codes
* @var array
*/
protected $_allowedCodes = array(
self::ERROR_PARSE,
self::ERROR_INVALID_REQUEST,
self::ERROR_INVALID_METHOD,
self::ERROR_INVALID_PARAMS,
self::ERROR_INTERNAL,
self::ERROR_OTHER,
);
/**
* Current code
* @var int
*/
protected $_code = -32000;
/**
* Error data
* @var mixed
*/
protected $_data;
/**
* Error message
* @var string
*/
protected $_message;
/**
* Constructor
*
* @param string $message
* @param int $code
* @param mixed $data
* @return void
*/
public function __construct($message = null, $code = -32000, $data = null)
{
$this->setMessage($message)
->setCode($code)
->setData($data);
}
/**
* Set error code
*
* @param int $code
* @return Zend_Json_Server_Error
*/
public function setCode($code)
{
if (!is_scalar($code)) {
return $this;
}
$code = (int) $code;
if (in_array($code, $this->_allowedCodes)) {
$this->_code = $code;
} elseif (in_array($code, range(-32099, -32000))) {
$this->_code = $code;
}
return $this;
}
/**
* Get error code
*
* @return int|null
*/
public function getCode()
{
return $this->_code;
}
/**
* Set error message
*
* @param string $message
* @return Zend_Json_Server_Error
*/
public function setMessage($message)
{
if (!is_scalar($message)) {
return $this;
}
$this->_message = (string) $message;
return $this;
}
/**
* Get error message
*
* @return string
*/
public function getMessage()
{
return $this->_message;
}
/**
* Set error data
*
* @param mixed $data
* @return Zend_Json_Server_Error
*/
public function setData($data)
{
$this->_data = $data;
return $this;
}
/**
* Get error data
*
* @return mixed
*/
public function getData()
{
return $this->_data;
}
/**
* Cast error to array
*
* @return array
*/
public function toArray()
{
return array(
'code' => $this->getCode(),
'message' => $this->getMessage(),
'data' => $this->getData(),
);
}
/**
* Cast error to JSON
*
* @return string
*/
public function toJson()
{
require_once 'Zend/Json.php';
return Zend_Json::encode($this->toArray());
}
/**
* Cast to string (JSON)
*
* @return string
*/
public function __toString()
{
return $this->toJson();
}
}

View file

@ -0,0 +1,36 @@
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @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
* @version $Id: Exception.php 20096 2010-01-06 02:05:09Z bkarwin $
*/
/** Zend_Json_Exception */
require_once 'Zend/Json/Exception.php';
/**
* Zend_Json_Server exceptions
*
* @uses Zend_Json_Exception
* @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 Zend_Json_Server_Exception extends Zend_Json_Exception
{
}

View file

@ -0,0 +1,289 @@
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @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
* @version $Id: Request.php 20096 2010-01-06 02:05:09Z bkarwin $
*/
/**
* @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 Zend_Json_Server_Request
{
/**
* Request ID
* @var mixed
*/
protected $_id;
/**
* Flag
* @var bool
*/
protected $_isMethodError = false;
/**
* Requested method
* @var string
*/
protected $_method;
/**
* Regex for method
* @var string
*/
protected $_methodRegex = '/^[a-z][a-z0-9_.]*$/i';
/**
* Request parameters
* @var array
*/
protected $_params = array();
/**
* JSON-RPC version of request
* @var string
*/
protected $_version = '1.0';
/**
* Set request state
*
* @param array $options
* @return Zend_Json_Server_Request
*/
public function setOptions(array $options)
{
$methods = get_class_methods($this);
foreach ($options as $key => $value) {
$method = 'set' . ucfirst($key);
if (in_array($method, $methods)) {
$this->$method($value);
} elseif ($key == 'jsonrpc') {
$this->setVersion($value);
}
}
return $this;
}
/**
* Add a parameter to the request
*
* @param mixed $value
* @param string $key
* @return Zend_Json_Server_Request
*/
public function addParam($value, $key = null)
{
if ((null === $key) || !is_string($key)) {
$index = count($this->_params);
$this->_params[$index] = $value;
} else {
$this->_params[$key] = $value;
}
return $this;
}
/**
* Add many params
*
* @param array $params
* @return Zend_Json_Server_Request
*/
public function addParams(array $params)
{
foreach ($params as $key => $value) {
$this->addParam($value, $key);
}
return $this;
}
/**
* Overwrite params
*
* @param array $params
* @return Zend_Json_Server_Request
*/
public function setParams(array $params)
{
$this->_params = array();
return $this->addParams($params);
}
/**
* Retrieve param by index or key
*
* @param int|string $index
* @return mixed|null Null when not found
*/
public function getParam($index)
{
if (array_key_exists($index, $this->_params)) {
return $this->_params[$index];
}
return null;
}
/**
* Retrieve parameters
*
* @return array
*/
public function getParams()
{
return $this->_params;
}
/**
* Set request method
*
* @param string $name
* @return Zend_Json_Server_Request
*/
public function setMethod($name)
{
if (!preg_match($this->_methodRegex, $name)) {
$this->_isMethodError = true;
} else {
$this->_method = $name;
}
return $this;
}
/**
* Get request method name
*
* @return string
*/
public function getMethod()
{
return $this->_method;
}
/**
* Was a bad method provided?
*
* @return bool
*/
public function isMethodError()
{
return $this->_isMethodError;
}
/**
* Set request identifier
*
* @param mixed $name
* @return Zend_Json_Server_Request
*/
public function setId($name)
{
$this->_id = (string) $name;
return $this;
}
/**
* Retrieve request identifier
*
* @return mixed
*/
public function getId()
{
return $this->_id;
}
/**
* Set JSON-RPC version
*
* @param string $version
* @return Zend_Json_Server_Request
*/
public function setVersion($version)
{
if ('2.0' == $version) {
$this->_version = '2.0';
} else {
$this->_version = '1.0';
}
return $this;
}
/**
* Retrieve JSON-RPC version
*
* @return string
*/
public function getVersion()
{
return $this->_version;
}
/**
* Set request state based on JSON
*
* @param string $json
* @return void
*/
public function loadJson($json)
{
require_once 'Zend/Json.php';
$options = Zend_Json::decode($json);
$this->setOptions($options);
}
/**
* Cast request to JSON
*
* @return string
*/
public function toJson()
{
$jsonArray = array(
'method' => $this->getMethod()
);
if (null !== ($id = $this->getId())) {
$jsonArray['id'] = $id;
}
$params = $this->getParams();
if (!empty($params)) {
$jsonArray['params'] = $params;
}
if ('2.0' == $this->getVersion()) {
$jsonArray['jsonrpc'] = '2.0';
}
require_once 'Zend/Json.php';
return Zend_Json::encode($jsonArray);
}
/**
* Cast request to string (JSON)
*
* @return string
*/
public function __toString()
{
return $this->toJson();
}
}

View file

@ -0,0 +1,66 @@
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @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
* @version $Id: Http.php 20096 2010-01-06 02:05:09Z bkarwin $
*/
/**
* @see Zend_Json_Server_Request
*/
require_once 'Zend/Json/Server/Request.php';
/**
* @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 Zend_Json_Server_Request_Http extends Zend_Json_Server_Request
{
/**
* Raw JSON pulled from POST body
* @var string
*/
protected $_rawJson;
/**
* Constructor
*
* Pull JSON request from raw POST body and use to populate request.
*
* @return void
*/
public function __construct()
{
$json = file_get_contents('php://input');
$this->_rawJson = $json;
if (!empty($json)) {
$this->loadJson($json);
}
}
/**
* Get JSON from raw POST body
*
* @return string
*/
public function getRawJson()
{
return $this->_rawJson;
}
}

View file

@ -0,0 +1,250 @@
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @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
* @version $Id: Response.php 20096 2010-01-06 02:05:09Z bkarwin $
*/
/**
* @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 Zend_Json_Server_Response
{
/**
* Response error
* @var null|Zend_Json_Server_Error
*/
protected $_error;
/**
* Request ID
* @var mixed
*/
protected $_id;
/**
* Result
* @var mixed
*/
protected $_result;
/**
* Service map
* @var Zend_Json_Server_Smd
*/
protected $_serviceMap;
/**
* JSON-RPC version
* @var string
*/
protected $_version;
/**
* Set result
*
* @param mixed $value
* @return Zend_Json_Server_Response
*/
public function setResult($value)
{
$this->_result = $value;
return $this;
}
/**
* Get result
*
* @return mixed
*/
public function getResult()
{
return $this->_result;
}
// RPC error, if response results in fault
/**
* Set result error
*
* @param Zend_Json_Server_Error $error
* @return Zend_Json_Server_Response
*/
public function setError(Zend_Json_Server_Error $error)
{
$this->_error = $error;
return $this;
}
/**
* Get response error
*
* @return null|Zend_Json_Server_Error
*/
public function getError()
{
return $this->_error;
}
/**
* Is the response an error?
*
* @return bool
*/
public function isError()
{
return $this->getError() instanceof Zend_Json_Server_Error;
}
/**
* Set request ID
*
* @param mixed $name
* @return Zend_Json_Server_Response
*/
public function setId($name)
{
$this->_id = $name;
return $this;
}
/**
* Get request ID
*
* @return mixed
*/
public function getId()
{
return $this->_id;
}
/**
* Set JSON-RPC version
*
* @param string $version
* @return Zend_Json_Server_Response
*/
public function setVersion($version)
{
$version = (string) $version;
if ('2.0' == $version) {
$this->_version = '2.0';
} else {
$this->_version = null;
}
return $this;
}
/**
* Retrieve JSON-RPC version
*
* @return string
*/
public function getVersion()
{
return $this->_version;
}
/**
* Cast to JSON
*
* @return string
*/
public function toJson()
{
if ($this->isError()) {
$response = array(
'result' => null,
'error' => $this->getError()->toArray(),
'id' => $this->getId(),
);
} else {
$response = array(
'result' => $this->getResult(),
'id' => $this->getId(),
'error' => null,
);
}
if (null !== ($version = $this->getVersion())) {
$response['jsonrpc'] = $version;
}
require_once 'Zend/Json.php';
return Zend_Json::encode($response);
}
/**
* Retrieve args
*
* @return mixed
*/
public function getArgs()
{
return $this->_args;
}
/**
* Set args
*
* @param mixed $args
* @return self
*/
public function setArgs($args)
{
$this->_args = $args;
return $this;
}
/**
* Set service map object
*
* @param Zend_Json_Server_Smd $serviceMap
* @return Zend_Json_Server_Response
*/
public function setServiceMap($serviceMap)
{
$this->_serviceMap = $serviceMap;
return $this;
}
/**
* Retrieve service map
*
* @return Zend_Json_Server_Smd|null
*/
public function getServiceMap()
{
return $this->_serviceMap;
}
/**
* Cast to string (JSON)
*
* @return string
*/
public function __toString()
{
return $this->toJson();
}
}

View file

@ -0,0 +1,81 @@
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @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
* @version $Id: Http.php 20096 2010-01-06 02:05:09Z bkarwin $
*/
/**
* @see Zend_Json_Server_Response
*/
require_once 'Zend/Json/Server/Response.php';
/**
* @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 Zend_Json_Server_Response_Http extends Zend_Json_Server_Response
{
/**
* Emit JSON
*
* Send appropriate HTTP headers. If no Id, then return an empty string.
*
* @return string
*/
public function toJson()
{
$this->sendHeaders();
if (!$this->isError() && null === $this->getId()) {
return '';
}
return parent::toJson();
}
/**
* Send headers
*
* If headers are already sent, do nothing. If null ID, send HTTP 204
* header. Otherwise, send content type header based on content type of
* service map.
*
* @return void
*/
public function sendHeaders()
{
if (headers_sent()) {
return;
}
if (!$this->isError() && (null === $this->getId())) {
header('HTTP/1.1 204 No Content');
return;
}
if (null === ($smd = $this->getServiceMap())) {
return;
}
$contentType = $smd->getContentType();
if (!empty($contentType)) {
header('Content-Type: ' . $contentType);
}
}
}

View file

@ -0,0 +1,480 @@
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @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
* @version $Id: Smd.php 20096 2010-01-06 02:05:09Z bkarwin $
*/
/**
* @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 Zend_Json_Server_Smd
{
const ENV_JSONRPC_1 = 'JSON-RPC-1.0';
const ENV_JSONRPC_2 = 'JSON-RPC-2.0';
const SMD_VERSION = '2.0';
/**
* Content type
* @var string
*/
protected $_contentType = 'application/json';
/**
* Content type regex
* @var string
*/
protected $_contentTypeRegex = '#[a-z]+/[a-z][a-z-]+#i';
/**
* Service description
* @var string
*/
protected $_description;
/**
* Generate Dojo-compatible SMD
* @var bool
*/
protected $_dojoCompatible = false;
/**
* Current envelope
* @var string
*/
protected $_envelope = self::ENV_JSONRPC_1;
/**
* Allowed envelope types
* @var array
*/
protected $_envelopeTypes = array(
self::ENV_JSONRPC_1,
self::ENV_JSONRPC_2,
);
/**
* Service id
* @var string
*/
protected $_id;
/**
* Services offerred
* @var array
*/
protected $_services = array();
/**
* Service target
* @var string
*/
protected $_target;
/**
* Global transport
* @var string
*/
protected $_transport = 'POST';
/**
* Allowed transport types
* @var array
*/
protected $_transportTypes = array('POST');
/**
* Set object state via options
*
* @param array $options
* @return Zend_Json_Server_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)) {
$this->$method($value);
}
}
return $this;
}
/**
* Set transport
*
* @param string $transport
* @return Zend_Json_Server_Smd
*/
public function setTransport($transport)
{
if (!in_array($transport, $this->_transportTypes)) {
require_once 'Zend/Json/Server/Exception.php';
throw new Zend_Json_Server_Exception(sprintf('Invalid transport "%s" specified', $transport));
}
$this->_transport = $transport;
return $this;
}
/**
* Get transport
*
* @return string
*/
public function getTransport()
{
return $this->_transport;
}
/**
* Set envelope
*
* @param string $envelopeType
* @return Zend_Json_Server_Smd
*/
public function setEnvelope($envelopeType)
{
if (!in_array($envelopeType, $this->_envelopeTypes)) {
require_once 'Zend/Json/Server/Exception.php';
throw new Zend_Json_Server_Exception(sprintf('Invalid envelope type "%s"', $envelopeType));
}
$this->_envelope = $envelopeType;
return $this;
}
/**
* Retrieve envelope
*
* @return string
*/
public function getEnvelope()
{
return $this->_envelope;
}
// Content-Type of response; default to application/json
/**
* Set content type
*
* @param string $type
* @return Zend_Json_Server_Smd
*/
public function setContentType($type)
{
if (!preg_match($this->_contentTypeRegex, $type)) {
require_once 'Zend/Json/Server/Exception.php';
throw new Zend_Json_Server_Exception(sprintf('Invalid content type "%s" specified', $type));
}
$this->_contentType = $type;
return $this;
}
/**
* Retrieve content type
*
* @return string
*/
public function getContentType()
{
return $this->_contentType;
}
/**
* Set service target
*
* @param string $target
* @return Zend_Json_Server_Smd
*/
public function setTarget($target)
{
$this->_target = (string) $target;
return $this;
}
/**
* Retrieve service target
*
* @return string
*/
public function getTarget()
{
return $this->_target;
}
/**
* Set service ID
*
* @param string $Id
* @return Zend_Json_Server_Smd
*/
public function setId($id)
{
$this->_id = (string) $id;
return $this->_id;
}
/**
* Get service id
*
* @return string
*/
public function getId()
{
return $this->_id;
}
/**
* Set service description
*
* @param string $description
* @return Zend_Json_Server_Smd
*/
public function setDescription($description)
{
$this->_description = (string) $description;
return $this->_description;
}
/**
* Get service description
*
* @return string
*/
public function getDescription()
{
return $this->_description;
}
/**
* Indicate whether or not to generate Dojo-compatible SMD
*
* @param bool $flag
* @return Zend_Json_Server_Smd
*/
public function setDojoCompatible($flag)
{
$this->_dojoCompatible = (bool) $flag;
return $this;
}
/**
* Is this a Dojo compatible SMD?
*
* @return bool
*/
public function isDojoCompatible()
{
return $this->_dojoCompatible;
}
/**
* Add Service
*
* @param Zend_Json_Server_Smd_Service|array $service
* @return void
*/
public function addService($service)
{
require_once 'Zend/Json/Server/Smd/Service.php';
if ($service instanceof Zend_Json_Server_Smd_Service) {
$name = $service->getName();
} elseif (is_array($service)) {
$service = new Zend_Json_Server_Smd_Service($service);
$name = $service->getName();
} else {
require_once 'Zend/Json/Server/Exception.php';
throw new Zend_Json_Server_Exception('Invalid service passed to addService()');
}
if (array_key_exists($name, $this->_services)) {
require_once 'Zend/Json/Server/Exception.php';
throw new Zend_Json_Server_Exception('Attempt to register a service already registered detected');
}
$this->_services[$name] = $service;
return $this;
}
/**
* Add many services
*
* @param array $services
* @return Zend_Json_Server_Smd
*/
public function addServices(array $services)
{
foreach ($services as $service) {
$this->addService($service);
}
return $this;
}
/**
* Overwrite existing services with new ones
*
* @param array $services
* @return Zend_Json_Server_Smd
*/
public function setServices(array $services)
{
$this->_services = array();
return $this->addServices($services);
}
/**
* Get service object
*
* @param string $name
* @return false|Zend_Json_Server_Smd_Service
*/
public function getService($name)
{
if (array_key_exists($name, $this->_services)) {
return $this->_services[$name];
}
return false;
}
/**
* Return services
*
* @return array
*/
public function getServices()
{
return $this->_services;
}
/**
* Remove service
*
* @param string $name
* @return boolean
*/
public function removeService($name)
{
if (array_key_exists($name, $this->_services)) {
unset($this->_services[$name]);
return true;
}
return false;
}
/**
* Cast to array
*
* @return array
*/
public function toArray()
{
if ($this->isDojoCompatible()) {
return $this->toDojoArray();
}
$transport = $this->getTransport();
$envelope = $this->getEnvelope();
$contentType = $this->getContentType();
$SMDVersion = self::SMD_VERSION;
$service = compact('transport', 'envelope', 'contentType', 'SMDVersion');
if (null !== ($target = $this->getTarget())) {
$service['target'] = $target;
}
if (null !== ($id = $this->getId())) {
$service['id'] = $id;
}
$services = $this->getServices();
if (!empty($services)) {
$service['services'] = array();
foreach ($services as $name => $svc) {
$svc->setEnvelope($envelope);
$service['services'][$name] = $svc->toArray();
}
$service['methods'] = $service['services'];
}
return $service;
}
/**
* Export to DOJO-compatible SMD array
*
* @return array
*/
public function toDojoArray()
{
$SMDVersion = '.1';
$serviceType = 'JSON-RPC';
$service = compact('SMDVersion', 'serviceType');
$target = $this->getTarget();
$services = $this->getServices();
if (!empty($services)) {
$service['methods'] = array();
foreach ($services as $name => $svc) {
$method = array(
'name' => $name,
'serviceURL' => $target,
);
$params = array();
foreach ($svc->getParams() as $param) {
$paramName = array_key_exists('name', $param) ? $param['name'] : $param['type'];
$params[] = array(
'name' => $paramName,
'type' => $param['type'],
);
}
if (!empty($params)) {
$method['parameters'] = $params;
}
$service['methods'][] = $method;
}
}
return $service;
}
/**
* Cast to JSON
*
* @return string
*/
public function toJson()
{
require_once 'Zend/Json.php';
return Zend_Json::encode($this->toArray());
}
/**
* Cast to string (JSON)
*
* @return string
*/
public function __toString()
{
return $this->toJson();
}
}

View file

@ -0,0 +1,473 @@
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @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
*/
/**
* @see Zend_Json_Server_Smd
*/
require_once 'Zend/Json/Server/Smd.php';
/**
* Create Service Mapping Description for a method
*
* @package Zend_Json
* @subpackage Server
* @version $Id: Service.php 20096 2010-01-06 02:05:09Z bkarwin $
* @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 Zend_Json_Server_Smd_Service
{
/**#@+
* Service metadata
* @var string
*/
protected $_envelope = Zend_Json_Server_Smd::ENV_JSONRPC_1;
protected $_name;
protected $_return;
protected $_target;
protected $_transport = 'POST';
/**#@-*/
/**
* Allowed envelope types
* @var array
*/
protected $_envelopeTypes = array(
Zend_Json_Server_Smd::ENV_JSONRPC_1,
Zend_Json_Server_Smd::ENV_JSONRPC_2,
);
/**
* Regex for names
* @var string
*/
protected $_nameRegex = '/^[a-z][a-z0-9._]+$/i';
/**
* Parameter option types
* @var array
*/
protected $_paramOptionTypes = array(
'name' => 'is_string',
'optional' => 'is_bool',
'default' => null,
'description' => 'is_string',
);
/**
* Service params
* @var array
*/
protected $_params = array();
/**
* Mapping of parameter types to JSON-RPC types
* @var array
*/
protected $_paramMap = array(
'any' => 'any',
'arr' => 'array',
'array' => 'array',
'assoc' => 'object',
'bool' => 'boolean',
'boolean' => 'boolean',
'dbl' => 'float',
'double' => 'float',
'false' => 'boolean',
'float' => 'float',
'hash' => 'object',
'integer' => 'integer',
'int' => 'integer',
'mixed' => 'any',
'nil' => 'null',
'null' => 'null',
'object' => 'object',
'string' => 'string',
'str' => 'string',
'struct' => 'object',
'true' => 'boolean',
'void' => 'null',
);
/**
* Allowed transport types
* @var array
*/
protected $_transportTypes = array(
'POST',
);
/**
* Constructor
*
* @param string|array $spec
* @return void
* @throws Zend_Json_Server_Exception if no name provided
*/
public function __construct($spec)
{
if (is_string($spec)) {
$this->setName($spec);
} elseif (is_array($spec)) {
$this->setOptions($spec);
}
if (null == $this->getName()) {
require_once 'Zend/Json/Server/Exception.php';
throw new Zend_Json_Server_Exception('SMD service description requires a name; none provided');
}
}
/**
* Set object state
*
* @param array $options
* @return Zend_Json_Server_Smd_Service
*/
public function setOptions(array $options)
{
$methods = get_class_methods($this);
foreach ($options as $key => $value) {
if ('options' == strtolower($key)) {
continue;
}
$method = 'set' . ucfirst($key);
if (in_array($method, $methods)) {
$this->$method($value);
}
}
return $this;
}
/**
* Set service name
*
* @param string $name
* @return Zend_Json_Server_Smd_Service
* @throws Zend_Json_Server_Exception
*/
public function setName($name)
{
$name = (string) $name;
if (!preg_match($this->_nameRegex, $name)) {
require_once 'Zend/Json/Server/Exception.php';
throw new Zend_Json_Server_Exception(sprintf('Invalid name "%s" provided for service; must follow PHP method naming conventions', $name));
}
$this->_name = $name;
return $this;
}
/**
* Retrieve name
*
* @return string
*/
public function getName()
{
return $this->_name;
}
/**
* Set Transport
*
* Currently limited to POST
*
* @param string $transport
* @return Zend_Json_Server_Smd_Service
*/
public function setTransport($transport)
{
if (!in_array($transport, $this->_transportTypes)) {
require_once 'Zend/Json/Server/Exception.php';
throw new Zend_Json_Server_Exception(sprintf('Invalid transport "%s"; please select one of (%s)', $transport, implode(', ', $this->_transportTypes)));
}
$this->_transport = $transport;
return $this;
}
/**
* Get transport
*
* @return string
*/
public function getTransport()
{
return $this->_transport;
}
/**
* Set service target
*
* @param string $target
* @return Zend_Json_Server_Smd_Service
*/
public function setTarget($target)
{
$this->_target = (string) $target;
return $this;
}
/**
* Get service target
*
* @return string
*/
public function getTarget()
{
return $this->_target;
}
/**
* Set envelope type
*
* @param string $envelopeType
* @return Zend_Json_Server_Smd_Service
*/
public function setEnvelope($envelopeType)
{
if (!in_array($envelopeType, $this->_envelopeTypes)) {
require_once 'Zend/Json/Server/Exception.php';
throw new Zend_Json_Server_Exception(sprintf('Invalid envelope type "%s"; please specify one of (%s)', $envelopeType, implode(', ', $this->_envelopeTypes)));
}
$this->_envelope = $envelopeType;
return $this;
}
/**
* Get envelope type
*
* @return string
*/
public function getEnvelope()
{
return $this->_envelope;
}
/**
* Add a parameter to the service
*
* @param string|array $type
* @param array $options
* @param int|null $order
* @return Zend_Json_Server_Smd_Service
*/
public function addParam($type, array $options = array(), $order = null)
{
if (is_string($type)) {
$type = $this->_validateParamType($type);
} elseif (is_array($type)) {
foreach ($type as $key => $paramType) {
$type[$key] = $this->_validateParamType($paramType);
}
} else {
require_once 'Zend/Json/Server/Exception.php';
throw new Zend_Json_Server_Exception('Invalid param type provided');
}
$paramOptions = array(
'type' => $type,
);
foreach ($options as $key => $value) {
if (in_array($key, array_keys($this->_paramOptionTypes))) {
if (null !== ($callback = $this->_paramOptionTypes[$key])) {
if (!$callback($value)) {
continue;
}
}
$paramOptions[$key] = $value;
}
}
$this->_params[] = array(
'param' => $paramOptions,
'order' => $order,
);
return $this;
}
/**
* Add params
*
* Each param should be an array, and should include the key 'type'.
*
* @param array $params
* @return Zend_Json_Server_Smd_Service
*/
public function addParams(array $params)
{
ksort($params);
foreach ($params as $options) {
if (!is_array($options)) {
continue;
}
if (!array_key_exists('type', $options)) {
continue;
}
$type = $options['type'];
$order = (array_key_exists('order', $options)) ? $options['order'] : null;
$this->addParam($type, $options, $order);
}
return $this;
}
/**
* Overwrite all parameters
*
* @param array $params
* @return Zend_Json_Server_Smd_Service
*/
public function setParams(array $params)
{
$this->_params = array();
return $this->addParams($params);
}
/**
* Get all parameters
*
* Returns all params in specified order.
*
* @return array
*/
public function getParams()
{
$params = array();
$index = 0;
foreach ($this->_params as $param) {
if (null === $param['order']) {
if (array_search($index, array_keys($params), true)) {
++$index;
}
$params[$index] = $param['param'];
++$index;
} else {
$params[$param['order']] = $param['param'];
}
}
ksort($params);
return $params;
}
/**
* Set return type
*
* @param string|array $type
* @return Zend_Json_Server_Smd_Service
*/
public function setReturn($type)
{
if (is_string($type)) {
$type = $this->_validateParamType($type, true);
} elseif (is_array($type)) {
foreach ($type as $key => $returnType) {
$type[$key] = $this->_validateParamType($returnType, true);
}
} else {
require_once 'Zend/Json/Server/Exception.php';
throw new Zend_Json_Server_Exception('Invalid param type provided ("' . gettype($type) .'")');
}
$this->_return = $type;
return $this;
}
/**
* Get return type
*
* @return string|array
*/
public function getReturn()
{
return $this->_return;
}
/**
* Cast service description to array
*
* @return array
*/
public function toArray()
{
$name = $this->getName();
$envelope = $this->getEnvelope();
$target = $this->getTarget();
$transport = $this->getTransport();
$parameters = $this->getParams();
$returns = $this->getReturn();
if (empty($target)) {
return compact('envelope', 'transport', 'parameters', 'returns');
}
return $paramInfo = compact('envelope', 'target', 'transport', 'parameters', 'returns');
}
/**
* Return JSON encoding of service
*
* @return string
*/
public function toJson()
{
$service = array($this->getName() => $this->toArray());
require_once 'Zend/Json.php';
return Zend_Json::encode($service);
}
/**
* Cast to string
*
* @return string
*/
public function __toString()
{
return $this->toJson();
}
/**
* Validate parameter type
*
* @param string $type
* @return true
* @throws Zend_Json_Server_Exception
*/
protected function _validateParamType($type, $isReturn = false)
{
if (!is_string($type)) {
require_once 'Zend/Json/Server/Exception.php';
throw new Zend_Json_Server_Exception('Invalid param type provided ("' . $type .'")');
}
if (!array_key_exists($type, $this->_paramMap)) {
$type = 'object';
}
$paramType = $this->_paramMap[$type];
if (!$isReturn && ('null' == $paramType)) {
require_once 'Zend/Json/Server/Exception.php';
throw new Zend_Json_Server_Exception('Invalid param type provided ("' . $type . '")');
}
return $paramType;
}
}