Created
July 21, 2016 03:57
-
-
Save atdt/8359a364bde7463117087e1f35b41ac5 to your computer and use it in GitHub Desktop.
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 | |
class Node implements JsonSerializable { | |
public function __construct( $name, $contents ) { | |
$this->name = $name; | |
$this->store = []; | |
foreach ( (array)$contents as $k => $v ) { | |
if ( is_int( $k ) ) { | |
$this->addChild( $v ); | |
} else { | |
$this->addAttribute( $k, $v ); | |
} | |
} | |
} | |
public function addChild( $child ) { | |
$this->store[] = $child; | |
} | |
public function addAttribute( $attribute, $value ) { | |
$this->addChild( new Node( "@{$attribute}", $value ) ); | |
} | |
public function jsonSerialize() { | |
return [ $this->name, $this->store ]; | |
} | |
} | |
$k = 42; | |
$val = 'abcd'; | |
$fancyNode = new Node( 'part', [ | |
new Node( 'name', [ 'index' => $k ] ), | |
new Node( 'value', $val ), | |
] ); | |
$rawNode = [ 'part', [ | |
[ 'name', [ [ '@index', [ $k ] ] ] ], | |
[ 'value', [ strval( $val ) ] ], | |
] ]; | |
assert( json_encode( $fancyNode ) === json_encode( $rawNode ) ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment