NodeClass.php 2.21 KB
<?php

/**
 * @class NodeClass
 * @brief Generic definition of a node
 * @details
 */
class NodeClass
{
	private $name;
	private $value;
	private $attributes;
	private $children;

	public function __construct($name)
	{
		$this->name = $name;
		$this->attributes = array();
		$this->children = array();
		$this->value = "";
	}

	public function getName()
	{
		return $this->name;
	}

	protected function setValue($val)
	{
		$this->value = $val;
	}

	protected function getValue()
	{
		return $this->value;
	}

	protected function setAttribute($attName, $attVal)
	{
		$this->attributes[$attName] = $attVal;
	}

	protected function getAttribute($attName)
	{
		return $this->attributes[$attName];
	}

	protected function hasChildren()
	{
		return (count($this->children) != 0);
	}

	protected function addChild($child)
	{
		$this->children[] = $child;
	}
	
	protected function addChildBefore($child, $nodeName)
	{
		for ($i = 0; $i < count($this->children);++$i)
		{
			if ($this->children[$i]->getName() == $nodeName)
			{
				array_splice($this->children, $i, 0, array($child));
				return;
			}
		}
		
		$this->addChild($child);
	}

	protected function getChildren()
	{
		return $this->children;
	}

	protected function getChildrenByName($name)
	{
		$result = array();

		foreach ($this->children as $child)
		if ($child->getName() == $name)
			$result[] = $child;

		return $result;
	}

	protected function getFirstChildByName($name)
	{
		foreach ($this->children as $child)
		if ($child->getName() == $name)
			return $child;

		return NULL;
	}

	protected function getChildInstanceByName($name, $createIfNoExist = false)
	{
		$node = $this->getFirstChildByName($name);
		if ($node == NULL)
		if ($createIfNoExist)
		{
			$node = new NodeClass($name);
			$this->addChild($node);
		}
		return $node;
	}

	/*
	 * @brief Export node to a XML node
	*/
	public function toXMLNode($doc)
	{
		$xmlNode = $doc->createElement($this->getName());

		if ($this->getValue() != "")
			$xmlNode->nodeValue = $this->getValue();

		foreach ($this->attributes as $key => $value)
			$xmlNode->setAttribute($key,$value);

		foreach ($this->children as $child)
		{
			$xmlChildNode = $child->toXMLNode($doc);
			$xmlNode->appendChild($xmlChildNode);
		}

		return $xmlNode;
	}
}

?>