<?php

class ConfigData
{
  /** @var string */
  public $key = null;
  /** @var mixed */
  public $value = null;
  /** @var boolean */
  public $leaf = false;
  /** @var ConfigData[] */
  public $child = array();
  /** @var ConfigData */
  public $parent = null;

  /**
   *
   * @param array $array
   * @return ConfigData
   */
  public static function parse(array $array)
  {
    $config = new ConfigData();
    self::configDataWalker($array, $config);
    return $config;
  }

  private static function configDataWalker(&$array,ConfigData &$item)
  {
    foreach($array as $key => $value)
    {
      $child = new ConfigData();
      $child->parent = $item;
      $child->key = $key;
      $child->value = $value;
      if(is_array($value))
      {
        if(count($value)<=0)
        {
          $child->leaf = true;
        }
        else
        {
          self::configDataWalker($value, $child);
          $child->leaf = false;
        }
      }
      else
      {
        $child->leaf = true;
      }
      $item->child[] = $child;
    }
  }

  /**
   *
   * @param string $separator default '/'
   * @return string
   */
  public function getPath($separator = '/')
  {
    $path = $this->key;
    if($this->parent != null)
    if(!$this->parent->isRoot())
      $path = $this->parent->getPath($separator) . $separator . $path;
    return $path;
  }

  /**
   * @param string $separator default '/'
   * @return ConfigData[]
   */
  public function getItems($separator = '/')
  {
    $items = array();
    $items[$this->getPath($separator)] = $this;
    foreach($this->child as $child)
    foreach($child->getItems() as $childitem)
    {
      $items[$childitem->getPath($separator)] = $childitem;
    }
    return $items;
  }

  /**
   *
   * @return boolean
   */
  public function isRoot()
  {
    return $this->parent == null;
  }
}