<?php
/**
 * Copyright © 2016 Filoblu S.r.l. All rights reserved.
 */

namespace FiloBlu\Esb\Helper\Format;

use Magento\Framework\App\Helper\AbstractHelper;
use SimpleXMLElement;

/**
 * Helper for formatting data in XML
 */
class Xml extends AbstractHelper implements FormatInterface
{

    /**
     * Formats data array in JSON
     *
     * @param array $data
     * @return string
     */
    public function format($data)
    {
        $xml = new SimpleXMLElement('<root/>');
        $this->array_to_xml($data, $xml);
        return $xml->asXML();
    }

    /**
     * Recursive function that converts a multidimensional array into an XML tree
     * @param array $data
     * @param SimpleXMLElement $xml
     * @return void
     */
    protected function array_to_xml($data, &$xml_data)
    {
        foreach ($data as $key => $value) {
            if (is_array($value)) {
                if (is_numeric($key)) {
                    $key = 'item';
                } elseif (preg_match("/^[0-9-]+$/", $key)) {
                    $key = 'item' . $key; //dealing with <0/>..<n/> issues
                }
                $subnode = $xml_data->addChild($key);
                $this->array_to_xml($value, $subnode);
            } else {
                if (is_numeric($key)) {
                    $key = 'item';
                } elseif (preg_match("/^[0-9-]+$/", $key)) {
                    $key = 'item' . $key; //dealing with <0/>..<n/> issues
                }
                $xml_data->addChild("$key", htmlspecialchars("$value"));
            }
        }
    }

    /**
     * Get HTTP Content Type
     *
     * @return string
     */
    public function getContentType()
    {
        return "application/xml";
    }
}
