<?php


namespace common\util;


use common\models\BaseMenu;
use JsonSerializable;

/**
 * Class MenuObject
 * @package common\util
 * @property int $id
 * @property int|null $pid
 * @property string $name
 * @property string $title
 * @property array $children
 */
class MenuObject implements JsonSerializable
{
    private int $id;

    private int|null $pid;

    private string $name;

    private string $title;

    /**
     * 节点属性
     */
    private array $children = [];

    /**
     * @return int
     */
    public function getId(): int
    {
        return $this->id;
    }

    /**
     * @param int $id
     */
    public function setId(int $id)
    {
        $this->id = $id;
    }

    /**
     * @return int|null
     */
    public function getPid(): int|null
    {
        return $this->pid;
    }

    /**
     * @param int|null $pid
     */
    public function setPid(int|null $pid)
    {
        $this->pid = $pid;
    }

    /**
     * @return string
     */
    public function getName(): string
    {
        return $this->name;
    }

    /**
     * @param string $name
     */
    public function setName(string $name)
    {
        $this->name = $name;
    }

    /**
     * @return string
     */
    public function getTitle(): string
    {
        return $this->title;
    }

    /**
     * @param string $title
     */
    public function setTitle(string $title)
    {
        $this->title = $title;
    }

    /**
     * @return array
     */
    public function getChildren(): array
    {
        return $this->children;
    }

    /**
     * @param array $children
     */
    public function setChildren(array $children)
    {
        $this->children = $children;
    }

    /**
     * @param MenuObject $children
     */
    public function addChildrenToTop(MenuObject $children)
    {
        array_unshift($this->children, $children);
    }

    /**
     * @param MenuObject $children
     */
    public function addChildrenToBottom(MenuObject $children)
    {
        $this->children[] = $children;
    }


    public function __construct(BaseMenu $menu)
    {
        $this->id = $menu->id;
        $this->pid = $menu->parentid;
        $this->name = $menu->url;
        $this->title = $menu->name;
    }

    /**
     * json_encode无法转化私有属性，需要使用jsonSerialize自定义转换私有的属性
     * @return array
     */
    public function jsonSerialize(): array
    {
        return [
            "id" => $this->id,
            "pid" => $this->pid,
            "name" => $this->name,
            "title" => $this->title,
            "children" => $this->children,
        ];
    }
}