summaryrefslogtreecommitdiff
path: root/app/Core/User/GroupSync.php
blob: d0bb647bf29c5749da4a995a743e0f6754498fae (plain)
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
<?php

namespace Kanboard\Core\User;

use Kanboard\Core\Base;

/**
 * Group Synchronization
 *
 * @package  user
 * @author   Frederic Guillot
 */
class GroupSync extends Base
{
    /**
     * Synchronize group membership
     *
     * @access public
     * @param  integer $userId
     * @param  array   $externalGroupIds
     */
    public function synchronize($userId, array $externalGroupIds)
    {
        $userGroups = $this->groupMemberModel->getGroups($userId);
        $this->addGroups($userId, $userGroups, $externalGroupIds);
        $this->removeGroups($userId, $userGroups, $externalGroupIds);
    }

    /**
     * Add missing groups to the user
     *
     * @access protected
     * @param integer $userId
     * @param array   $userGroups
     * @param array   $externalGroupIds
     */
    protected function addGroups($userId, array $userGroups, array $externalGroupIds)
    {
        $userGroupIds = array_column($userGroups, 'external_id', 'external_id');

        foreach ($externalGroupIds as $externalGroupId) {
            if (! isset($userGroupIds[$externalGroupId])) {
                $group = $this->groupModel->getByExternalId($externalGroupId);

                if (! empty($group)) {
                    $this->groupMemberModel->addUser($group['id'], $userId);
                }
            }
        }
    }

    /**
     * Remove groups from the user
     *
     * @access protected
     * @param integer $userId
     * @param array   $userGroups
     * @param array   $externalGroupIds
     */
    protected function removeGroups($userId, array $userGroups, array $externalGroupIds)
    {
        foreach ($userGroups as $userGroup) {
            if (! empty($userGroup['external_id']) && ! in_array($userGroup['external_id'], $externalGroupIds)) {
                $this->groupMemberModel->removeUser($userGroup['id'], $userId);
            }
        }
    }
}