<?php
/**
 * @copyright (c) Kufer Software GmbH, Loisachstrasse 4, D-84453 Mühldorf
 */


class XElement extends stdClass
{
  
  public function ToXML($pName = '', $pIndent = '')
  {
    $vars = get_object_vars($this);
    $varsFiltered = array_diff_key($vars, array('_attributes' => ''));

    if ($pName == '' && count($varsFiltered) != 1) {
      
      $pName = 'root';
    }

    if ($pName == '' && count($varsFiltered) == 1 && is_array(array_values($varsFiltered)[0])) {
      
      $pName = 'root';
    }

    $attributeString = '';
    if (isset($this->_attributes)) {
      $attributeString .= ' ';
      $attributes = get_object_vars($this->_attributes);
      foreach ($attributes as $name => $value) {
        $attributeString .= $name . '="' . $value . '" ';
      }
    }

    $indentChar = '  ';

    $content = '';
    foreach ($varsFiltered as $key => $value) {
      if (is_array($value)) {
        foreach ($value as $val) {
          $content .= $val->ToXML($key, $pIndent . $indentChar);
        }
      } else {
        if ($value instanceof XElement) {
          $content .= $value->ToXML($key, $pIndent . $indentChar);
        } else {
          if ($value == '') {
            $content .= $pIndent . $indentChar . '<' . $key . ' />' . "\r\n";
          } else {
            $content .= $pIndent . $indentChar . '<' . $key . '>';
            $content .= $value;
            $content .= '</' . $key . '>' . "\r\n";
          }
        }
      }
    }

    if ($pName != '') {
      if ($content == '') {
        $ret = $pIndent . '<' . $pName . $attributeString . ' />' . "\r\n";
      } else {
        $ret = $pIndent . '<' . $pName . $attributeString . '>' . "\r\n";
        $ret .= $content;
        $ret .= $pIndent . '</' . $pName . '>' . "\r\n";
      }
    } else {
      $ret = $pIndent . $content;
    }

    return $ret;
  }
}