GoogleAppsService::getUsers()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 14
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 9
nc 2
nop 1
dl 0
loc 14
rs 9.4285
c 0
b 0
f 0
1
<?php
2
3
namespace Acacha\Users\Services\GoogleApps;
4
5
use Acacha\Users\Models\GoogleApps\GoogleUser;
6
use Cache;
7
use Google;
8
9
/**
10
 * Class GoogleAppsService.
11
 *
12
 * @package Acacha\Users\Services\GoogleApps
13
 */
14
class GoogleAppsService
15
{
16
17
    /**
18
     * Get connection state.
19
     *
20
     * @return string
21
     */
22
    public function getConnectionState()
23
    {
24
        $directory = Google::make('directory');
25
26
        try {
27
            $r = $directory->users->get($email = config('users.google_apps_user_email_to_check_connection'));
28
            if($r) {
29
                $state = 'connected';
30
            } else {
31
                echo 'User does not exists: $email<br/>';
32
            }
33
        } catch (\Exception $e) {
34
            $state = 'error';
35
            $message = json_decode($e->getMessage());
36
        }
37
38
        $result = [
39
            'state' => $state
0 ignored issues
show
Bug introduced by
The variable $state does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
40
        ];
41
42
        if ($state != 'connected') $result['message'] = $message;
0 ignored issues
show
Bug introduced by
The variable $message does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
43
44
        return $result;
45
    }
46
47
    /**
48
     * Get total number of users.
49
     */
50
    public function totalNumberOfUsers()
51
    {
52
        return count($this->allUsers());
53
    }
54
55
    /**
56
     * Get all users from google apps.
57
     *
58
     * @return array|mixed
59
     */
60
    protected function allUsers()
61
    {
62
        $directory = Google::make('directory');
63
        $pageToken = null;
64
        $users = [];
65 View Code Duplication
        do {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
66
            try {
67
                $r = $directory->users->listUsers([
68
                    'domain' => config('users.google_apps_domain'),
69
                    'maxResults' => config('users.google_apps_users_maxResults'),
70
                    'pageToken' => $pageToken
71
                ]);
72
                $pageToken = $r->nextPageToken;
73
                $users = array_merge($users, $r->users);
74
            } catch (\Exception $e) {
75
                return json_decode($e->getMessage());
76
            }
77
        } while ($pageToken);
78
        return $users;
79
    }
80
81
    /**
82
     * Sync local database with remote Google apps info.
83
     */
84
    public function localSync()
85
    {
86
        $users = Cache::rememberForever('google_app_users', function () {
87
            return $this->allUsers();
88
        });
89
90
        try {
91
            foreach ($users as $user) {
92
                $user = GoogleUser::firstOrCreate([
93
                    'customerId' => $user->customerId,
94
                    'kind' => $user->kind,
95
                    'google_id'=> $user->id,
96
                    'etag'=> $user->etag,
97
                    'primaryEmail'=> $user->primaryEmail,
98
                    'givenName'=> $user->name->givenName,
99
                    'familyName'=> $user->name->familyName,
100
                    'fullName'=> $user->name->fullName,
101
                    'orgUnitPath'=> $user->orgUnitPath,
102
                    'organizations'=> json_decode($user->organizations),
103
                    'isAdmin'=> $user->isAdmin,
104
                    'isDelegatedAdmin'=> $user->isDelegatedAdmin,
105
                    'lastLoginTime'=> $user->lastLoginTime,
106
                    'creationTime'=> $user->creationTime,
107
                    'deletionTime'=> $user->deletionTime,
108
                    'agreedToTerms'=> $user->agreedToTerms,
109
                    'password'=> $user->password,
110
                    'hashFunction'=> $user->hashFunction,
111
                    'suspended'=> $user->suspended,
112
                    'suspensionReason'=> $user->suspensionReason,
113
                    'changePasswordAtNextLogin'=> $user->changePasswordAtNextLogin,
114
                    'emails'=> json_encode($user->emails),
115
                ]);
116
            }
117
        } catch (\Exception $e) {
118
            return [
119
                'completed' => 'false',
120
                'message' => $e->getMessage()
121
            ];
122
        }
123
124
        return [
125
            'completed' => 'true'
126
        ];
127
    }
128
129
    /**
130
     * Get users.
131
     *
132
     * @param int $perPage
133
     * @return int|mixed
134
     */
135
    public function getUsers($perPage = 15)
136
    {
137
        $directory = Google::make('directory');
138
        try {
139
            $r = $directory->users->listUsers([
140
                'domain' => config('users.google_apps_domain'),
141
                'maxResults' => $perPage
142
            ]);
143
        } catch (\Exception $e) {
144
            return json_decode($e->getMessage());
145
        }
146
147
        return $r->users;
148
    }
149
}