/
Groups.php
86 lines (75 loc) · 2.35 KB
/
Groups.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
<?php
namespace Maicol07\SSO\Addons;
use Illuminate\Support\Arr;
/**
* Class Groups
* @package Maicol07\SSO\Addons
*/
class Groups extends Core
{
protected $actions = [
'after_login' => 'setGroups',
'after_update' => 'setGroups'
];
/**
* Sets groups to a user
*
*/
public function setGroups(): void
{
$user = $this->flarum->user();
if ($user->id !== null && $user->id !== 0) {
$user_groups = $user->getDirtyRelationships()['groups'] ?? null;
if ($user_groups !== null) {
$groups = [];
/** Search flarum groups - @noinspection NullPointerExceptionInspection */
$flarum_groups = Arr::pluck(
$this->flarum->api->groups()->request()->collect()->all(),
'attributes.nameSingular',
'id'
);
foreach ($user_groups as $group) {
if (empty($group) || !is_string($group)) {
continue;
}
// Find ID of the group
$id = array_key_first(Arr::where($flarum_groups, static fn($name): bool => $name === $group));
// If it doesn't exists, create it
if ($id === 0 || $id === '' || $id === null) {
$id = $this->createGroup($group);
}
$groups[] = [
'type' => 'groups',
'id' => $id
];
}
$this->flarum->api->users($user->id)->patch([
'relationships' => [
'groups' => [
'data' => $groups
],
],
])->request();
$user->relationships->clearDirty();
}
}
}
/**
* Add a group to Flarum
*
*
* @return mixed
* @noinspection MissingReturnTypeInspection
*/
public function createGroup(string $group)
{
$response = $this->flarum->api->groups()->post([
'type' => 'groups',
'attributes' => [
'namePlural' => $group,
'nameSingular' => $group
]
])->request();
return $response->id;
}
}