PortableInfobox/services/PortableInfoboxBuilderService.class.php

61 lines
1.6 KiB
PHP
Raw Normal View History

2015-08-31 15:42:38 +00:00
<?php
class PortableInfoboxBuilderService extends WikiaService {
2015-09-03 13:59:29 +00:00
/**
* @param $builderData
*
2015-09-03 13:59:29 +00:00
* @return string
*
* @see PortableInfoboxBuilderServiceTest:: translationsDataProvider
2015-09-03 13:59:29 +00:00
*/
2015-08-31 15:42:38 +00:00
public function translate( $builderData ) {
$out = "";
$infobox = json_decode( $builderData );
if ( $infobox ) {
2015-09-01 07:45:08 +00:00
$xml = new SimpleXMLElement( '<' . PortableInfoboxParserTagController::PARSER_TAG_NAME . '/>' );
2015-08-31 15:42:38 +00:00
foreach ( $infobox as $key => $value ) {
if ( $key !== 'data' ) {
$xml->addAttribute( $key, $value );
}
}
$this->addGroupNode( $infobox->data, $xml );
// save to xml, import to dom, to remove xml header
$dom = dom_import_simplexml( $xml );
$out = $dom->ownerDocument->saveXML( $dom->ownerDocument->documentElement );
2015-09-04 09:28:28 +00:00
// ignore errors, we only load it to remove header
libxml_clear_errors();
2015-08-31 15:42:38 +00:00
}
return $out;
}
protected function addGroupNode( $data, SimpleXMLElement $xml ) {
foreach ( $data as $item ) {
$child = $xml->addChild( $item->type, is_string( $item->data ) ? (string)$item->data : null );
if ( is_array( $item->data ) ) {
$this->addGroupNode( $item->data, $child );
} else {
$this->addNode( $item, $child );
}
}
}
protected function addNode( $node, SimpleXMLElement $xml ) {
if ( $node->source ) {
$xml->addAttribute( 'source', $node->source );
}
foreach ( $node->data as $key => $value ) {
// map defaultValue to default, as its js reserved key word
$key = strcasecmp( $key, 'defaultValue' ) == 0 ? 'default' : $key;
2015-08-31 15:42:38 +00:00
if ( is_object( $value ) ) {
$this->addNode( $value, $xml->addChild( $key ) );
} else {
$xml->addChild( $key, $value );
}
}
}
}