<?php
namespace services\navigation;

/**
 * MenuItem class
 * Represents a single menu item
 * @author Jérôme Brilland
 * @version 1.0
 * @copyright (c) 2023, Jérôme Brilland
 * @license http://www.gnu.org/licenses/gpl.txt GNU General Public License
 */

class MenuItem implements \ArrayAccess, \Countable {
    
    /**
     * @var string
     * @access protected
     */
    protected $name;
    
    /**
     * @var string
     * @access protected
     */
    protected $link;
    
    /**
     * @var array
     * @access protected
     */
    protected $children = [];

    /**
     * Constructor of class MenuItem.
     *
     * @return void
     */
    public function __construct( string $name, string $link = null ) {
        $this->name = $name;
        $this->link = $link;
    }

    public function getName() {
        return $this->name;
    }
    
    public function getLink() {
        return $this->link;
    }
    
    public function addChild( MenuItem $child ) {
        $this->children[$child->getName()] = $child;
    }
    
    public function offsetExists( mixed $offset ): bool {
        return array_key_exists( $offset, $this->children );
    }
    
    public function offsetGet( mixed $offset ): mixed {
        if ( !array_key_exists( $offset, $this->children ) ) {
            throw new OutOfRangeException( 'Item ' . $offset . ' does not exist.' );
        }
        return $this->children[$offset];
    }
    
    public function offsetSet( mixed $offset, mixed $value ): void {
        $this->children[$offset] = $value;
    }
    
    public function offsetUnset( mixed $offset ): void {
        unset( $this->children[$offset] );
    }
    
    public function getChildren() {
        return $this->children;
    }
    
    public function count(): int {
        return count( $this->children );
    }

}
