blog/app/service/MenuService.php

110 lines
3.2 KiB
PHP
Raw Permalink Normal View History

2024-06-08 15:54:41 +08:00
<?php
namespace app\service;
use app\model\Menu;
class MenuService
{
/**
* @Inject
* @var Menu
*/
private $menu;
public function getList(int $userId = 0)
{
$info = $this->menu->getList();
if ($info['result']) {
$data = $this->package($info['data']);
$arr = $this->buildTree($data);
$tempArr['menu'] = $arr;
}
$tempArr['permissions'] = ["list.add", "list.delete", "user.edit", "user.delete"];
$tempArr['dashboardGrid'] = ["welcome", "ver", "time", "progress", "echarts", "about"];
$info['data'] = $tempArr;
return $info;
}
public function myMenu(int $userId = 0):array {
$info = $this->menu->getList();
return $info;
$arr = [];
if ($info['result']) {
$data = $this->package($info['data']);
$arr = $this->buildTree($data);
}
$info['data'] = $arr;
return $info;
}
public function package(array $data): array
{
$arr = [];
foreach ($data as $v) {
$arr[] = [
'id' => $v['id'],
'parent_id' => $v['parent_id'],
'name' => $v['name'],
'path' => $v['path'],
'meta' => [
'title' => $v['title'],
'icon' => $v['icon'],
'type' => 'menu'
],
'component' => $v['component']
];
}
return $arr;
}
public function buildTree(array $array, int $parentId = 0): array
{
$tree = [];
foreach ($array as $element) {
if ($element['parent_id'] == $parentId) {
$children = $this->buildTree($array, $element['id']);
if ($children) {
$element['children'] = $children;
}
$tree[] = $element;
}
}
return $tree;
}
public function add($data)
{
$data = json_decode($data, true);
foreach ($data as $k => $v) {
$arr = [
'parent_id' => 0,
'name' => $v['name'],
'path' => $v['path'],
'title' => $v['meta']['title'],
'icon' => $v['meta']['icon'],
'type' => 'menu',
'component' => $v['component'] ?? ''
];
$id = $this->menu->insertGetId($arr);
if (isset($v['children'])) $this->buld($id, $v['children']);
}
}
public function buld($pid, $data)
{
foreach ($data as $v) {
$arr = [
'parent_id' => $pid,
'name' => $v['name'],
'path' => $v['path'],
'title' => $v['meta']['title'],
'icon' => $v['meta']['icon'] ?? '',
'type' => 'menu',
'component' => $v['component'] ?? ''
];
$id = $this->menu->insertGetId($arr);
if (isset($v['children'])) $this->buld($id, $v['children']);
}
}
}