adrema/app/Initialize/InitializeGroups.php

40 lines
1002 B
PHP
Raw Permalink Normal View History

2022-03-11 20:19:17 +01:00
<?php
namespace App\Initialize;
use App\Group;
2022-09-02 00:45:39 +02:00
use DB;
use Zoomyboy\LaravelNami\Api;
2022-03-11 20:19:17 +01:00
class InitializeGroups
{
private Api $api;
2022-03-11 20:19:17 +01:00
public function __construct(Api $api)
{
$this->api = $api;
}
public function handle(): void
{
2022-03-11 20:19:17 +01:00
$this->api->groups()->each(function ($group) {
$parent = Group::updateOrCreate(['nami_id' => $group->id], ['nami_id' => $group->id, 'name' => $group->name]);
2022-03-15 10:24:04 +01:00
$this->syncChildren($group->id, $parent);
});
}
private function syncChildren(int $groupId, Group $parent): void
{
$this->api->subgroupsOf($groupId)->each(function ($subgroup) use ($parent) {
$newParent = Group::updateOrCreate(['nami_id' => $subgroup->id], ['nami_id' => $subgroup->id, 'name' => $subgroup->name, 'parent_id' => $parent->id]);
$this->syncChildren($subgroup->id, $newParent);
});
}
2022-09-02 00:45:39 +02:00
public function restore(): void
{
DB::table('groups')->delete();
}
}