Penambahan Menu Service Provider

This commit is contained in:
Daeng Deni Mardaeni 2024-10-29 11:57:32 +07:00
parent 9ec32469ce
commit 58606ec9be
3 changed files with 163 additions and 99 deletions

View File

@ -0,0 +1,72 @@
<?php
namespace App\Providers;
use Illuminate\Support\Facades\File;
use Illuminate\Support\ServiceProvider;
class MenuServiceProvider extends ServiceProvider
{
protected $menus = [];
public function boot()
{
$this->loadMenus();
$this->shareMenusWithViews();
}
protected function loadMenus()
{
$modulesPath = base_path('Modules');
$moduleDirs = File::directories($modulesPath);
foreach ($moduleDirs as $moduleDir) {
$moduleJsonPath = $moduleDir . '/module.json';
if (File::exists($moduleJsonPath)) {
$moduleConfig = json_decode(File::get($moduleJsonPath), true);
if (isset($moduleConfig['menu'])) {
$this->mergeMenus($moduleConfig['menu']);
}
}
}
}
protected function mergeMenus(array $menu)
{
foreach ($menu as $key => $items) {
if (!isset($this->menus[$key])) {
$this->menus[$key] = [];
}
foreach ($items as $newItem) {
$existingItemKey = $this->findExistingMenuItem($this->menus[$key], $newItem);
if ($existingItemKey !== null) {
// Merge submenus if the item already exists
$this->menus[$key][$existingItemKey]['sub'] = array_merge(
$this->menus[$key][$existingItemKey]['sub'] ?? [],
$newItem['sub'] ?? []
);
} else {
// Add new item if it doesn't exist
$this->menus[$key][] = $newItem;
}
}
}
}
protected function findExistingMenuItem(array $menuItems, array $newItem)
{
foreach ($menuItems as $index => $item) {
if ($item['title'] === $newItem['title'] || $item['path'] === $newItem['path']) {
return $index;
}
}
return null;
}
protected function shareMenusWithViews()
{
view()->share('menus', $this->menus);
}
}

View File

@ -2,4 +2,5 @@
return [
App\Providers\AppServiceProvider::class,
App\Providers\MenuServiceProvider::class,
];

View File

@ -43,13 +43,7 @@
$headingMain = 0;
$headingMaster = 0;
@endphp
@foreach($module as $row => $key)
@if($key)
@if(file_exists(dirname(__FILE__, 4) . '/Modules/'.$row.'/module.json'))
@php
$module = json_decode(file_get_contents(dirname(__FILE__, 4) . '/Modules/'.$row.'/module.json'));
$menus = $module->menu;
@endphp
@php $menus = json_decode(json_encode($menus)); @endphp
@foreach($menus as $key => $value)
@foreach($value as $menu)
@if($key=='main')
@ -135,9 +129,6 @@
@endif
@endforeach
@endforeach
@endif
@endif
@endforeach
</div>
</div>
</div>