PHP Code:
class NavigationNode {
public $title;
public $url;
public $children;
public function __construct($title = '', $url = '', array $children = []) {
$this->title = $title;
$this->url = $url;
$this->children = $children;
}
}
PHP Code:
class NavigationHtmlListRenderer {
private $rootNode;
private $charset;
public function __construct(NavigationNode $rootNode, $charset = 'utf-8') {
$this->rootNode = $rootNode;
$this->charset = $charset;
}
public function render($activeUrl = '', $formatOutput = false) {
$dom = new DOMDocument('1.0', $this->charset);
$rootElement = $this->renderNode($dom, $this->rootNode);
$listElement = $dom->createElement('ul');
$listElement->appendChild($rootElement);
$rootElement->appendChild($this->renderChildren($dom, $this->rootNode));
$dom->appendChild($listElement);
foreach ($dom->getElementsByTagName('a') as $linkElement) {
if ($linkElement->getAttribute('href') === $activeUrl) {
$linkElement->setAttribute('class', 'active');
}
}
if ($formatOutput) {
$dom->formatOutput = true;
}
return $dom->saveXML($listElement);
}
private function renderNode(DOMDocument $dom, NavigationNode $node) {
$linkElement = $dom->createElement('a', $node->title);
$linkElement->setAttribute('href', $node->url);
$listItemElement = $dom->createElement('li');
$listItemElement->appendChild($linkElement);
return $listItemElement;
}
private function renderChildren(DOMDocument $dom, NavigationNode $parentNode) {
$listElement = $dom->createElement('ul');
foreach ($parentNode->children as $node) {
$listItemElement = $this->renderNode($dom, $node);
if (!empty($node->children)) {
$listItemElement->appendChild($this->renderChildren($dom, $node));
}
$listElement->appendChild($listItemElement);
}
return $listElement;
}
}
PHP Code:
$navigation = new NavigationNode('Home', '/', [
new NavigationNode(
'Main', '/main', [
new NavigationNode(
'Main Page 1', '/main/1'
),
new NavigationNode(
'Main Page 2', '/main/2'
),
new NavigationNode(
'Main Page 3', '/main/3', [
new NavigationNode(
'Sub Page 1', '/main/3/1'
),
new NavigationNode(
'Sub Page 2', '/main/3/2'
)
]
)
]
),
new NavigationNode(
'Contact', '/contact'
)
]);
$renderer = new NavigationHtmlListRenderer($navigation);
echo $renderer->render('/main/3/1', true);
HTML Code:
<ul> <li> <a href="/">Home</a> <ul> <li> <a href="/main">Main</a> <ul> <li> <a href="/main/1">Main Page 1</a> </li> <li> <a href="/main/2">Main Page 2</a> </li> <li> <a href="/main/3">Main Page 3</a> <ul> <li> <a href="/main/3/1" class="active">Sub Page 1</a> </li> <li> <a href="/main/3/2">Sub Page 2</a> </li> </ul> </li> </ul> </li> <li> <a href="/contact">Contact</a> </li> </ul> </li> </ul>

Leave a comment: