[Html_ajax-svn] [178] implementation and examples for Urlencoded serializer

Elizabeth Smith emsmith at elizabethmariesmith.com
Fri Nov 11 12:40:03 CST 2005


Packages in pear don't usually rely on php_compat - instead just do 
if(!function_exists and either error out with instructions to use 
php_compat or copy/paste a compatible implementation.  Lots of people 
don't have pear_compat installed and this will die a horrible death for 
them :).

>> Revision
>>     178
>> Author
>>     arpad
>> Date
>>     2005-11-09 00:23:53 -0600 (Wed, 09 Nov 2005)
>>
>>
>>       Log Message
>>
>>implementation and examples for Urlencoded serializer
>>
>>
>>       Added Paths
>>
>>     * trunk/AJAX/Serializer/Urlencoded.php
>>       <#trunkAJAXSerializerUrlencodedphp>
>>     * trunk/examples/serialize.url.examples.php
>>       <#trunkexamplesserializeurlexamplesphp>
>>     * trunk/js/UrlSerializer.js <#trunkjsUrlSerializerjs>
>>
>>
>>       Diff
>>
>>
>>         Added: trunk/AJAX/Serializer/Urlencoded.php (177 => 178)
>>
>>--- trunk/AJAX/Serializer/Urlencoded.php	2005-11-09 06:18:06 UTC (rev 177)
>>+++ trunk/AJAX/Serializer/Urlencoded.php	2005-11-09 06:23:53 UTC (rev 178)
>>@@ -0,0 +1,33 @@
>>+<?php
>>+// $Id$
>>+if (!function_exists('http_build_query')) {
>>+    require_once 'PHP/Compat/functions/http_build_query.php';
>>+}
>>+
>>+/**
>>+ * URL Encoding Serializer
>>+ *
>>+ * @category   HTML
>>+ * @package    AJAX
>>+ * @author     Arpad Ray <arpad at rajeczy.com>
>>+ * @copyright  2005 Arpad Ray
>>+ * @license    http://www.opensource.org/licenses/lgpl-license.php  LGPL
>>+ * @version    Release: @package_version@
>>+ * @link       http://pear.php.net/package/HTML_AJAX
>>+ */
>>+class HTML_AJAX_Serialize_Urlencoded
>>+{
>>+    
>>+    function serialize($input) 
>>+    {
>>+        return http_build_query(array('_HTML_AJAX' => $input));
>>+    }
>>+
>>+    function unserialize($input) 
>>+    {
>>+        parse_str($input, $ret);
>>+        return (isset($ret['_HTML_AJAX']) ? $ret['_HTML_AJAX'] : null);
>>+    }
>>+}
>>+/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
>>+?>
>>
>>
>>         Added: trunk/examples/serialize.url.examples.php (177 => 178)
>>
>>--- trunk/examples/serialize.url.examples.php	2005-11-09 06:18:06 UTC (rev 177)
>>+++ trunk/examples/serialize.url.examples.php	2005-11-09 06:23:53 UTC (rev 178)
>>@@ -0,0 +1,69 @@
>>+<script type="text/javascript" src="../js/UrlSerializer.js"></script>
>>+<script type="text/javascript" src="../js/util.js"></script>
>>+<script type="text/javascript">
>>+
>>+</script>
>>+<?php
>>+
>>+$examples = array(
>>+    '$foo = null;',
>>+    '$foo = true;',
>>+    '$foo = "foobar";',
>>+    '$foo = 337;',
>>+    '$foo = 99.99;',
>>+    '$foo = array("a" => 1, "b" => 2, 3);',
>>+    '$foo = array(1,2,array(1,2,3));',
>>+    'class Foo { var $foo; var $bar; }' 
>>+    . '$foo = new Foo; $foo->foo = "hello"; $foo->bar = array("world","universe");'
>>+);
>>+
>>+require_once '../AJAX/Serializer/Urlencoded.php';
>>+$sr = new HTML_AJAX_Serialize_Urlencoded;
>>+echo '<h1><a name="pos">Positives</a> | <a href="#neg">Negatives</a></h1>';
>>+$c = count($examples);
>>+for ($i = 0; $i < $c; $i++) {
>>+    echo "<strong>PHP Code:</strong>\n<pre>$examples[$i]</pre>\n<strong>PHP value:</strong><pre>\n";
>>+    eval($examples[$i]);
>>+    var_dump($foo);
>>+    $sfoo = $sr->serialize($foo);
>>+    echo "</pre>\n<strong>Unserialized in PHP:</strong>\n<pre>";
>>+    var_dump($sr->unserialize($sfoo));
>>+    echo "</pre>\n<strong>Unserialized in JS:</strong>\n<pre>\n",
>>+         '<script type="text/javascript">',
>>+         'var jsr = new HTML_AJAX_Serialize_Urlencoded();',
>>+         'var sfoo = unescape("', urlencode($sfoo), '"); var usfoo = jsr.unserialize(sfoo); if (jsr.error) {',
>>+         'document.write("Error: " + jsr.getError() + "\n"); } document.write(HTML_AJAX_Util.varDump(usfoo) + ',
>>+         '"</pre>\n<strong>Serialized in PHP:</strong>\n<pre>', $sfoo, '</pre>\n',
>>+         '\n<strong>Serialized in JS:</strong>\n<pre>" + jsr.serialize(usfoo));',
>>+         "\n</script>\n</pre>\n<hr />\n\n";
>>+}
>>+
>>+$bad_examples = array(
>>+    'x',
>>+    'x-1',
>>+    'x=1x=2',
>>+    'x=1&',
>>+    'x[=]1',
>>+    '[]x=1',
>>+    '_HTML_AJAX]]=1',
>>+    '_HTML_AJAX[[=1',
>>+    '_HTML_AJAX][=1',
>>+    '_HTML_AJAX[=]1',
>>+    '_HTML_AJAX[=1]',
>>+    '_HTML_AJAX[0]=1&_HTML_AJAX]]=1',
>>+    '_HTML_AJAX[0[1]]=1',
>>+    '_HTML_AJAX[0[1]=1'
>>+);
>>+
>>+echo '<h1><a href="#pos">Positives</a> | <a name="neg">Negatives</a></h1>';
>>+foreach ($bad_examples as $sfoo) {
>>+    echo "</pre>\n<strong>Invalidly serialized:</strong>\n<pre>", $sfoo, "</pre>\n",
>>+         "<strong>Unserialized in JS:</strong>\n<pre>\n",
>>+         '<script type="text/javascript">',
>>+         'var sfoo = unescape("', urlencode($sfoo), '"); var usfoo = jsr.unserialize(sfoo); if (jsr.error) {',
>>+         'document.write("Error: " + jsr.getError() + "\n"); } document.write(HTML_AJAX_Util.varDump(usfoo));',
>>+         "</script>\n</pre>\n<hr />\n\n";
>>+}
>>+
>>+
>>+?>
>>
>>
>>         Added: trunk/js/UrlSerializer.js (177 => 178)
>>
>>--- trunk/js/UrlSerializer.js	2005-11-09 06:18:06 UTC (rev 177)
>>+++ trunk/js/UrlSerializer.js	2005-11-09 06:23:53 UTC (rev 178)
>>@@ -0,0 +1,167 @@
>>+/***************************************************************************
>>+
>>+    This class can be used to serialize and unserialize data in a
>>+    format compatible with PHP's handling of HTTP query strings.
>>+    Due to limitations of the format, all input is serialized as an
>>+    array or a string. e.g. An object with another object as a
>>+    property will be serialized as a multidimensional array, where
>>+    every element is an array or a string.
>>+    
>>+    Copyright (C) 2005 Arpad Ray <arpad at rajeczy.com>
>>+
>>+    This library is free software; you can redistribute it and/or
>>+    modify it under the terms of the GNU Lesser General Public
>>+    License as published by the Free Software Foundation; either
>>+    version 2.1 of the License, or (at your option) any later version.
>>+
>>+    This library is distributed in the hope that it will be useful,
>>+    but WITHOUT ANY WARRANTY; without even the implied warranty of
>>+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
>>+    Lesser General Public License for more details.
>>+
>>+    You should have received a copy of the GNU Lesser General Public
>>+    License along with this library; if not, write to:
>>+    Free Software Foundation, Inc.,
>>+    51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
>>+
>>+***************************************************************************/
>>+
>>+// {{{ var HTML_AJAX_Serialize_Urlencoded
>>+function HTML_AJAX_Serialize_Urlencoded() {}
>>+HTML_AJAX_Serialize_Urlencoded.prototype = {
>>+    contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
>>+    base: '_HTML_AJAX',
>>+    _keys: [],
>>+    _count: 0,
>>+    error: false,
>>+    message: "",
>>+    cont: "",
>>+    // {{{ serialize
>>+    /**
>>+     *  Serializes a variable (calls _serialize().)
>>+     *
>>+     *  @param     mixed  inp the variable to serialize
>>+     *  @return    string   a string representation of the input, 
>>+     *                      which can be reconstructed by unserialize()
>>+     *  @author Arpad Ray <arpad at rajeczy.com>
>>+     *  @version 0.0.1
>>+     */
>>+    serialize: function(input) {
>>+        if (typeof input == 'undefined') {
>>+            return '';
>>+        }
>>+        var ret = this.base;
>>+        for (i in this._keys) {
>>+            ret += '[' + escape(this._keys[i]) + ']'; 
>>+        }
>>+        ret += '=';
>>+        switch (HTML_AJAX_Util.getType(input)) {
>>+            case 'string': 
>>+            case 'number':
>>+                ret += escape(input.toString());
>>+                break;
>>+            case 'boolean':
>>+                ret += (input ? '1' : '0');
>>+                break;
>>+            case 'array':
>>+            case 'object':
>>+                ret = '';
>>+                for (i in input) {
>>+                    this._keys.push(i);
>>+                    ret += this.serialize(input[i]) + '&';
>>+                    this._keys.pop();
>>+                }
>>+                ret = ret.substr(0, ret.length - 1);
>>+        }
>>+        return ret;
>>+    },
>>+    // }}}
>>+    // {{{ unserialize
>>+    /**
>>+     *  Reconstructs a serialized variable
>>+     *
>>+     *  @param    string inp the string to reconstruct
>>+     *  @return   array an array containing the variable represented by the input string, or void on failure
>>+     *  @author Arpad Ray <arpad at rajeczy.com>
>>+     *  @version 0.0.1
>>+     */
>>+    unserialize: function(input) {
>>+        if (!input.length || input.length == 0) {
>>+            // null
>>+            return;
>>+        }
>>+        if (!/^(?:_HTML_AJAX(?:\[[^\[\]]*\])*=[^&]*(?:&|$))+$/.test(input)) {
>>+            this.raiseError("invalidly formed input", input);
>>+            return;
>>+        }
>>+        input = input.split("&");
>>+        var pos, key, keys, val, _HTML_AJAX = [];
>>+        if (input.length == 1) {
>>+            if (input[0].substr(0, this.base.length + 1) != this.base + '=') {
>>+                this.raiseError("invalid input base", input);
>>+                return;    
>>+            }
>>+            return unescape(input[0].substr(this.base.length + 1));
>>+        }
>>+        for (var i in input) {
>>+            pos = input[i].indexOf("=");
>>+            if (pos < 1 || input[i].length - pos - 1 < 1) {
>>+                this.raiseError("input is too short", input[i]);
>>+                return;
>>+            }
>>+            key = unescape(input[i].substr(0, pos));
>>+            val = unescape(input[i].substr(pos + 1));
>>+            key = key.replace(/\[((?:\d*\D+)+)\]/g, '["$1"]');
>>+            keys = key.split(']');
>>+            for (j in keys) {
>>+                if (!keys[j].length || keys[j].length == 0) {
>>+                    continue;
>>+                }
>>+                try {
>>+                    if (eval('typeof ' + keys[j] + ']') == 'undefined') {
>>+                        eval(keys[j] + ']=[];');
>>+                    }
>>+                } catch (e) {
>>+                    this.raiseError("error evaluating key", input);
>>+                    return; 
>>+                }
>>+            }
>>+            try {
>>+                eval(key + '="' + val + '";');
>>+            } catch (e) {
>>+                this.raiseError("error evaluating value", input);
>>+                return; 
>>+            }
>>+        }
>>+        return _HTML_AJAX;
>>+    },
>>+    // }}}
>>+    // {{{ getError
>>+    /**
>>+    *  Gets the last error message
>>+    *
>>+    *  @return    string   the last error message from unserialize()
>>+    *  @author Arpad Ray <arpad at rajeczy.com>
>>+    *  @version 0.0.3
>>+    */    
>>+    getError: function() {
>>+        return this.message + "\n" + this.cont;
>>+    },
>>+    // }}}
>>+    // {{{ raiseError
>>+    /**
>>+    *  Raises an eror (called by unserialize().)
>>+    *
>>+    *  @param    string    message    the error message
>>+    *  @param    string    cont       the remaining unserialized content
>>+    *  @author Arpad Ray <arpad at rajeczy.com>
>>+    *  @version 0.0.3
>>+    */    
>>+    raiseError: function(message, cont) {
>>+        this.error = 1;
>>+        this.message = message;
>>+        this.cont = cont;
>>+    }
>>+    // }}}
>>+}
>>+// }}}
>>\ No newline at end of file
>>
>>  
>>
>>------------------------------------------------------------------------
>>
>>_______________________________________________
>>Html_ajax-svn mailing list
>>Html_ajax-svn at lists.bluga.net
>>http://lists.bluga.net/mailman/listinfo/html_ajax-svn
>> 
>>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://lists.bluga.net/pipermail/html_ajax-svn/attachments/20051111/71b9d8b0/attachment.html


More information about the Html_ajax-svn mailing list