<?php
namespace App\Tools;
use App\Constants\ErrorCode;
class Result
{
    public static function success($data = [])
    {
        return static::result(ErrorCode::SUCCESS, ErrorCode::getMessage(ErrorCode::SUCCESS), $data);
    }
    public static function error($message = '', $code = ErrorCode::ERROR, $data = [])
    {
        if (empty($message)) {
            return static::result($code, ErrorCode::getMessage($code), $data);
        } else {
            return static::result($code, $message, $data);
        }
    }
    protected static function result($code, $message, $data)
    {
        return [
            'code' => $code,
            'message' => $message,
            'data' => $data,
        ];
    }
    /**
     * 递归查询
     * @param $menuItems
     * @param $parentId
     * @return array
     */
    public static  function buildMenuTree($menuItems, $parentId = 0) {
        $tree = [];
        foreach ($menuItems as $item) {
            if ($item['pid'] == $parentId) {
                // 找到子菜单
                $children = self::buildMenuTree($menuItems, $item['category_id']);
                // 如果子菜单存在，则添加到当前菜单的children中
                if ($children) {
                    $item['children'] = $children;
                }
                // 将当前菜单添加到树中
                $tree[] = $item;
            }
        }
        return $tree;
    }
}