<?php

class WikiTranslatorToC {



	protected $toc;



	public function __construct() {
		$this->toc = new ArrayObject();
	}



	public function append($name, $title, $depth) {
		$this->appendToToC($name, $title, $depth, $this->toc);
	}



	protected function appendToToC($name, $title, $depth, ArrayObject &$branch) {
		if ($depth > 1) {
			if (!$branch->count()) {
				$branch[] = new ArrayObject(array(
					'title' => '&mdash;',
					'name' => microtime(),
					'sub' => new ArrayObject()
				));
			}
			$lastIndex = $branch->count() - 1;
			return $this->appendToToC($name, $title, $depth - 1, $branch[$lastIndex]['sub']);
		}
		$branch[] = new ArrayObject(array(
			'title' => $title,
			'name' => $name,
			'sub' => new ArrayObject()
		));
	}



	protected function printToC(ArrayObject $tree) {
		$out = array();
		foreach ($tree as $branch) {
			$out[] = '<li><a href="#' . $branch['name'] . '">' . $branch['title'] . '</a>';
			if ($branch['sub'] and $branch['sub']->count()) {
				$out[] = '<ul>';
				$out[] = $this->printToC($branch['sub']);
				$out[] = '</ul>';
			}
			$out[] = '</li>';
		}
		return implode('', $out);
	}



	public function __toString() {
//print_r($this->toc);
		return $this->toc->count() ? $this->printToC($this->toc) : '';
	}



} // class WikiTranslatorToC

?>