Passed
Pull Request — 1.11.x (#5763)
by Angel Fernando Quiroz
13:34
created

AzureSyncUsersCommand::__invoke()   A

Complexity

Conditions 4
Paths 6

Size

Total Lines 54
Code Lines 33

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 33
c 1
b 0
f 0
dl 0
loc 54
rs 9.392
cc 4
nc 6
nop 0

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
/* For license terms, see /license.txt */
4
5
use League\OAuth2\Client\Token\AccessTokenInterface;
6
7
class AzureSyncUsersCommand extends AzureCommand
8
{
9
    /**
10
     * @return Generator<int, string>
11
     * @throws Exception
12
     */
13
    public function __invoke(): Generator
14
    {
15
        yield 'Synchronizing users from Azure.';
16
17
        $token = $this->provider->getAccessToken(
18
            'client_credentials',
19
            ['resource' => $this->provider->resource]
20
        );
21
22
        $existingUsers = [];
23
24
        foreach ($this->getAzureUsers($token) as $azureUserInfo) {
25
            try {
26
                $userId = $this->plugin->registerUser(
27
                    $token,
28
                    $this->provider,
29
                    $azureUserInfo,
30
                    'users/' . $azureUserInfo['id'] . '/memberOf',
31
                    'id',
32
                    'id'
33
                );
34
            } catch (Exception $e) {
35
                yield $e->getMessage();
36
37
                continue;
38
            }
39
40
            $existingUsers[] = $userId;
41
42
            $userInfo = api_get_user_info($userId);
43
44
            yield sprintf('User info: %s', serialize($userInfo));
45
        }
46
47
        if ('true' === $this->plugin->get(AzureActiveDirectory::SETTING_DEACTIVATE_NONEXISTING_USERS)) {
48
            yield '----------------';
49
50
            yield 'Trying deactivate non-existing users in Azure';
51
52
            $users = UserManager::getRepository()->findByAuthSource('azure');
53
            $userIdList = array_map(
54
                function ($user) {
55
                    return $user->getId();
56
                },
57
                $users
58
            );
59
60
            $nonExistingUsers = array_diff($userIdList, $existingUsers);
61
62
            UserManager::deactivate_users($nonExistingUsers);
63
64
            yield sprintf(
65
                'Deactivated users IDs: %s',
66
                implode(', ', $nonExistingUsers)
67
            );
68
        }
69
    }
70
71
    /**
72
     * @return Generator<int, array<string, string>>
73
     * @throws Exception
74
     */
75
    private function getAzureUsers(AccessTokenInterface $token): Generator
76
    {
77
        $userFields = [
78
            'givenName',
79
            'surname',
80
            'mail',
81
            'userPrincipalName',
82
            'businessPhones',
83
            'mobilePhone',
84
            'accountEnabled',
85
            'mailNickname',
86
            'id'
87
        ];
88
89
        $query = sprintf(
90
            '$top=%d&$select=%s',
91
            AzureActiveDirectory::API_PAGE_SIZE,
92
            implode(',', $userFields)
93
        );
94
95
        do {
96
            try {
97
                $azureUsersRequest = $this->provider->request('get', "users?$query", $token);
98
            } catch (Exception $e) {
99
                throw new Exception('Exception when requesting users from Azure: '.$e->getMessage());
100
            }
101
102
            $azureUsersInfo = $azureUsersRequest['value'] ?? [];
103
104
            foreach ($azureUsersInfo as $azureUserInfo) {
105
                yield $azureUserInfo;
106
            }
107
108
            $hasNextLink = false;
109
110
            if (!empty($azureUsersRequest['@odata.nextLink'])) {
111
                $hasNextLink = true;
112
                $query = parse_url($azureUsersRequest['@odata.nextLink'], PHP_URL_QUERY);
113
            }
114
        } while ($hasNextLink);
115
    }
116
}
117