Created
May 3, 2012 22:13
-
-
Save tewha/2589891 to your computer and use it in GitHub Desktop.
Example output mapping function for Presto
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// NOTE that responses are automatically generated by Presto (this example simulates the call as a demonstration) | |
// 1. Create new Response (faking $ctx) | |
$r = new Response((object) array( 'res' => 'htm' ) ); // htm intentional, tests type matching | |
// 2. Add a new type handler, with a custom mapping (anon fn) | |
Response::add_type_handler('.*\/htm.*', encode_html, function($k, &$n, &$a, $d) { | |
static $parents = array(); | |
static $at = 0; // current depth | |
// remap node name | |
switch ($k) { | |
case 'chapters': | |
$k = 'body'; break; | |
case 'title': | |
$k = 'h'.($d-1); break; | |
case 'ideas': | |
$k = 'ul'; break; | |
case 'li': | |
if (end($parents) === 'body') { | |
$k = 'section'; | |
// also pull out the ID as an attribute | |
if (array_key_exists('id', $n)) { | |
$a = " id='{$n['id']}'"; | |
unset($n['id']); | |
} | |
} | |
break; | |
} | |
// track parent nodes | |
if ($at > $d || empty($parents)) $parents[] = $k; | |
elseif ($at != $d) array_pop($p); | |
if ($d != $at) $at = $d; | |
return $k; | |
} ); | |
// 3. Return the transformed DOM to the client | |
$r->ok($dom); | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{"chapters" : [ | |
{"title": "This is chapter 1", | |
"id": 101, | |
"content" : "This is some text", | |
"ideas" : ["This is a list of things", "And another item"] | |
}, | |
{"title": "This is chapter 2", | |
"id": 102, | |
"content" : "This is some more text", | |
"ideas" : ["This is a list of things", "And another item"] | |
} | |
] } |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<body> | |
<section id='101'> | |
<h1> | |
This is chapter 1 | |
</h1> | |
<content> | |
This is some text | |
</content> | |
<ul> | |
<section> | |
This is a list of things | |
</section> | |
<section> | |
And another item | |
</section> | |
</ul> | |
</section> | |
<section id='102'> | |
<h1> | |
This is chapter 2 | |
</h1> | |
<content> | |
This is some more text | |
</content> | |
<ul> | |
<li> | |
This is a list of things | |
</li> | |
<li> | |
And another item | |
</li> | |
</ul> | |
</section> | |
</body> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment