FastJSON Class Reference

_______________________________________ More...

List of all members.

Static Public Member Functions


Detailed Description

_______________________________________

FastJSON, simple and fast Pear Service_JSON encoder/decoder alternative [http://pear.php.net/pepr/pepr-proposal-show.php?id=198] --------------------------------------- This class is about two time faster than Pear Service_JSON class. This class is probably not powerful as Service_JSON but it has no dependencies and converts correctly ASCII range 0x00 - 0x1F too. There's any string convertion, just regular RFC specific characters are converted into string. To don't have problems with other chars try to use utf8_encode($json_encoded_string). To recieve correctly JSON strings from JavaScript use encodeURIComponent then use, if is necessary, utef8_decode before JS to PHP convertion. decode method doesn't returns a standard object class but You can create the corret class directly with FastJSON::convert method and with them You can manage JS Date objects too. --------------------------------------- Summary of static public methods

convert extra, special method

decode converts a valid JSON string into a native PHP variable

encode converts a native php variable into a valid JSON string ---------------------------------------

Special FastJSON::convert method Informations _______________________________________ --------------------------------------- This method is used by FastJSON::encode method but should be used to do these convertions too:

  • JSON string to time() integer:

FastJSON::convert(decodedDate:String):time()

If You recieve a date string rappresentation You could convert into respective time() integer. Example: FastJSON::convert(FastJSON::decode($clienttime)); // i.e. $clienttime = 2006-11-09T14:42:30 // returned time will be an integer useful with gmdate or date // to create, for example, this string // Thu Nov 09 2006 14:42:30 GMT+0100 (Rome, Europe)

  • time() to JSON string:

FastJSON::convert(time():Int32, true:Boolean):JSON Date String format

You could send server time() informations and send them to clients. Example: FastJSON::convert(time(), true); // i.e. 2006-11-09T14:42:30

  • associative array to generic class:

FastJSON::convert(array(params=>values), new GenericClass):new Instance of GenericClass

With a decoded JSON object You could convert them into a new instance of your Generic Class. Example: class MyClass { var $param = "somevalue"; function MyClass($somevar) { $this->somevar = $somevar; }; function getVar = function(){ return $this->somevar; }; };

$instance = new MyClass("example"); $encoded = FastJSON::encode($instance); // {"param":"somevalue"}

$decoded = FastJSON::decode($encoded); // $decoded instanceof Object => true // $decoded instanceof MyClass => false

$decoded = FastJSON::convert($decoded, new MyClass("example")); // $decoded instanceof Object => true // $decoded instanceof MyClass => true

$decoded->getVar(); // example

---------------------------------------

Author:
Andrea Giammarchi http://www.devpro.it/
Version:
0.4 [fixed string convertion problems, add stdClass optional convertion instead of associative array (used by default)] anything PHP >= 4 ---------------------------------------

Copyright (c) 2006 - 2007 Andrea Giammarchi

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. _______________________________________

Definition at line 126 of file FastJSON.php.


Member Function Documentation

static FastJSON::__decode ( &$  encode,
&$  pos,
&$  slen,
&$  stdClass 
) [static]

Definition at line 280 of file FastJSON.php.

Referenced by decode().

00280                                                                             {
00281                 switch($encode{$pos}) {
00282                         case 't':
00283                                 $result = true;
00284                                 $pos += 4;
00285                                 break;
00286                         case 'f':
00287                                 $result = false;
00288                                 $pos += 5;
00289                                 break;
00290                         case 'n':
00291                                 $result = null;
00292                                 $pos += 4;
00293                                 break;
00294                         case '[':
00295                                 $result = array();
00296                                 ++$pos;
00297                                 while($encode{$pos} !== ']') {
00298                                         array_push($result, FastJSON::__decode($encode, $pos, $slen, $stdClass));
00299                                         if($encode{$pos} === ',')
00300                                                 ++$pos;
00301                                 }
00302                                 ++$pos;
00303                                 break;
00304                         case '{':
00305                                 $result = $stdClass ? new stdClass : array();
00306                                 ++$pos;
00307                                 while($encode{$pos} !== '}') {
00308                                         $tmp = FastJSON::__decodeString($encode, $pos);
00309                                         ++$pos;
00310                                         if($stdClass)
00311                                                 $result->$tmp = FastJSON::__decode($encode, $pos, $slen, $stdClass);
00312                                         else
00313                                                 $result[$tmp] = FastJSON::__decode($encode, $pos, $slen, $stdClass);
00314                                         if($encode{$pos} === ',')
00315                                                 ++$pos;
00316                                 }
00317                                 ++$pos;
00318                                 break;
00319                         case '"':
00320                                 switch($encode{++$pos}) {
00321                                         case '"':
00322                                                 $result = "";
00323                                                 break;
00324                                         default:
00325                                                 $result = FastJSON::__decodeString($encode, $pos);
00326                                                 break;
00327                                 }
00328                                 ++$pos;
00329                                 break;
00330                         default:
00331                                 $tmp = '';
00332                                 preg_replace('/^(\-)?([0-9]+)(\.[0-9]+)?([eE]\+[0-9]+)?/e', '$tmp = "\\1\\2\\3\\4"', substr($encode, $pos));
00333                                 if($tmp !== '') {
00334                                         $pos += strlen($tmp);
00335                                         $nint = intval($tmp);
00336                                         $nfloat = floatval($tmp);
00337                                         $result = $nfloat == $nint ? $nint : $nfloat;
00338                                 }
00339                                 break;
00340                 }
00341                 return $result;
00342         }

static FastJSON::__decodeString ( &$  encode,
&$  pos 
) [static]

Definition at line 343 of file FastJSON.php.

Referenced by __decode().

00343                                                                {
00344                 $replacement = FastJSON::__getStaticReplacement();
00345                 $endString = FastJSON::__endString($encode, $pos, $pos);
00346                 $result = str_replace($replacement['replace'], $replacement['find'], substr($encode, $pos, $endString));
00347                 $pos += $endString;
00348                 return $result;
00349         }

static FastJSON::__endString ( &$  encode,
position,
&$  pos 
) [static]

Definition at line 350 of file FastJSON.php.

Referenced by __decodeString().

00350                                                                        {
00351                 do {
00352                         $position = strpos($encode, '"', $position + 1);
00353                 }while($position !== false && FastJSON::__slashedChar($encode, $position - 1));
00354                 if($position === false)
00355                         trigger_error('', E_USER_WARNING);
00356                 return $position - $pos;
00357         }

static FastJSON::__exit ( str,
a,
b 
) [static]

Definition at line 358 of file FastJSON.php.

00358                                                     {
00359                 exit($a.'FATAL: FastJSON decode method failure [malicious or incorrect JSON string]');
00360         }

static FastJSON::__getStaticReplacement (  )  [static]

Definition at line 268 of file FastJSON.php.

Referenced by __decodeString(), and encode().

00268                                                        {
00269                 static $replacement = array('find'=>array(), 'replace'=>array());
00270                 if($replacement['find'] == array()) {
00271                         foreach(array_merge(range(0, 7), array(11), range(14, 31)) as $v) {
00272                                 $replacement['find'][] = chr($v);
00273                                 $replacement['replace'][] = "\\u00".sprintf("%02x", $v);
00274                         }
00275                         $replacement['find'] = array_merge(array(chr(0x5c), chr(0x2F), chr(0x22), chr(0x0d), chr(0x0c), chr(0x0a), chr(0x09), chr(0x08)), $replacement['find']);
00276                         $replacement['replace'] = array_merge(array('\\\\', '\\/', '\\"', '\r', '\f', '\n', '\t', '\b'), $replacement['replace']);
00277                 }
00278                 return $replacement;
00279         }

static FastJSON::__slashedChar ( &$  encode,
position 
) [static]

Definition at line 361 of file FastJSON.php.

Referenced by __endString().

00361                                                                   {
00362                 $pos = 0;
00363                 while($encode{$position--} === '\\')
00364                         $pos++;
00365                 return $pos % 2;
00366         }

static FastJSON::convert ( params,
result = null 
) [static]

public static method

FastJSON::convert(params:* [, result:Instance]):*

Parameters:
* String or Object
Instance optional new generic class instance if first parameter is an object.
Returns:
* time() value or new Instance with object parameters.
Note:
please read Special FastJSON::convert method Informations

Definition at line 142 of file FastJSON.php.

Referenced by encode().

00142                                                                {
00143                 switch(gettype($params)){
00144                         case    'array':
00145                                         $tmp = array();
00146                                         foreach($params as $key => $value) {
00147                                                 if(($value = FastJSON::encode($value)) !== '')
00148                                                         array_push($tmp, FastJSON::encode(strval($key)).':'.$value);
00149                                         };
00150                                         $result = '{'.implode(',', $tmp).'}';
00151                                         break;
00152                         case    'boolean':
00153                                         $result = $params ? 'true' : 'false';
00154                                         break;
00155                         case    'double':
00156                         case    'float':
00157                         case    'integer':
00158                                         $result = $result !== null ? strftime('%Y-%m-%dT%H:%M:%S', $params) : strval($params);
00159                                         break;
00160                         case    'NULL':
00161                                         $result = 'null';
00162                                         break;
00163                         case    'string':
00164                                         $i = create_function('&$e, $p, $l', 'return intval(substr($e, $p, $l));');
00165                                         if(preg_match('/^[0-9]{4}\-[0-9]{2}\-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}$/', $params))
00166                                                 $result = mktime($i($params, 11, 2), $i($params, 14, 2), $i($params, 17, 2), $i($params, 5, 2), $i($params, 9, 2), $i($params, 0, 4));
00167                                         break;
00168                         case    'object':
00169                                         $tmp = array();
00170                                         if(is_object($result)) {
00171                                                 foreach($params as $key => $value)
00172                                                         $result->$key = $value;
00173                                         } else {
00174                                                 $result = get_object_vars($params);
00175                                                 foreach($result as $key => $value) {
00176                                                         if(($value = FastJSON::encode($value)) !== '')
00177                                                                 array_push($tmp, FastJSON::encode($key).':'.$value);
00178                                                 };
00179                                                 $result = '{'.implode(',', $tmp).'}';
00180                                         }
00181                                         break;
00182                 }
00183                 return $result;
00184         }

static FastJSON::decode ( encode,
stdClass = false 
) [static]

Definition at line 208 of file FastJSON.php.

00208                                                                  {
00209                 $pos = 0;
00210                 $slen = is_string($encode) ? strlen($encode) : null;
00211                 if($slen !== null) {
00212                         $error = error_reporting(0);
00213                         set_error_handler(array('FastJSON', '__exit'));
00214                         $result = FastJSON::__decode($encode, $pos, $slen, $stdClass);
00215                         error_reporting($error);
00216                         restore_error_handler();
00217                 }
00218                 else
00219                         $result = null;
00220                 return $result;
00221         }

static FastJSON::encode ( decode  )  [static]

Definition at line 240 of file FastJSON.php.

Referenced by convert().

00240                                               {
00241                 $result = '';
00242                 switch(gettype($decode)){
00243                         case    'array':
00244                                         if(!count($decode) || array_keys($decode) === range(0, count($decode) - 1)) {
00245                                                 $keys = array();
00246                                                 foreach($decode as $value) {
00247                                                         if(($value = FastJSON::encode($value)) !== '')
00248                                                                 array_push($keys, $value);
00249                                                 }
00250                                                 $result = '['.implode(',', $keys).']';
00251                                         }
00252                                         else
00253                                                 $result = FastJSON::convert($decode);
00254                                         break;
00255                         case    'string':
00256                                         $replacement = FastJSON::__getStaticReplacement();
00257                                         $result = '"'.str_replace($replacement['find'], $replacement['replace'], $decode).'"';
00258                                         break;
00259                         default:
00260                                         if(!is_callable($decode))
00261                                                 $result = FastJSON::convert($decode);
00262                                         break;
00263                 }
00264                 return $result;
00265         }


The documentation for this class was generated from the following file: