Skip to content

Instantly share code, notes, and snippets.

@atdt
Created July 21, 2016 03:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save atdt/8359a364bde7463117087e1f35b41ac5 to your computer and use it in GitHub Desktop.
Save atdt/8359a364bde7463117087e1f35b41ac5 to your computer and use it in GitHub Desktop.
<?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