Completed
Pull Request — master (#106)
by Renato
02:32
created

Gitlab::getProjectSharedGroupsMembers()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 16
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 16
rs 9.4285
cc 3
eloc 8
nc 2
nop 1
1
<?php
2
3
namespace GitScrum\Classes;
4
5
use Auth;
6
use GitScrum\Models\User;
7
use GitScrum\Models\Issue;
8
use GitScrum\Models\Organization;
9
use GitScrum\Models\ProductBacklog;
10
use Carbon\Carbon;
11
use GitScrum\Contracts\ProviderInterface;
12
13
class Gitlab implements ProviderInterface
14
{
15
    private $gitlabGroups;
16
17
    public function tplUser($obj)
18
    {
19
        return [
20
            'provider_id' => $obj->id,
21
            'provider' => 'gitlab',
22
            'username' => $obj->nickname,
23
            'name' => $obj->name,
24
            'token' => $obj->token,
25
            'avatar' => @$obj->user['avatar_url'],
26
            'html_url' => @$obj->user['web_url'],
27
            'bio' => @$obj->user['bio'],
28
            'since' => Carbon::parse($obj->user['created_at'])->toDateTimeString(),
29
            'location' => @$obj->user['location'],
30
            'blog' => @$obj->user['blog'],
31
            'email' => $obj->email,
32
        ];
33
    }
34
35
    public function tplRepository($repo, $slug = false)
0 ignored issues
show
Documentation introduced by
The return type could not be reliably inferred; please add a @return annotation.

Our type inference engine in quite powerful, but sometimes the code does not provide enough clues to go by. In these cases we request you to add a @return annotation as described here.

Loading history...
36
    {
37
        $organization = $this->organization($repo);
38
39
        if (!$organization) {
40
            return;
41
        }
42
43
        return (object) [
44
            'provider_id' => $repo->id,
45
            'organization_id' => $organization->id,
46
            'organization_title' => $organization->username,
47
            'slug' => $slug ? $slug : Helper::slug($repo->path),
48
            'title' => $repo->path,
49
            'fullname' => $repo->name,
50
            'is_private' => $repo->public == true,
51
            'html_url' => $repo->http_url_to_repo,
52
            'description' => $repo->description,
53
            'fork' => null,
54
            'url' => $repo->web_url,
55
            'since' => Carbon::parse($repo->created_at)->toDateTimeString(),
56
            'pushed_at' => Carbon::parse($repo->last_activity_at)->toDateTimeString(),
57
            'ssh_url' => $repo->ssh_url_to_repo,
58
            'clone_url' => $repo->ssh_url_to_repo,
59
            'homepage' => $repo->web_url,
60
            'default_branch' => $repo->default_branch,
61
        ];
62
    }
63
64
    public function tplIssue($obj, $productBacklogId)
65
    {
66
        $user = User::where('username', @$obj->assignee->username)
67
            ->where('provider', 'gitlab')->first();
68
69
        return [
70
            'provider_id' => $obj->id,
71
            'user_id' => isset($user->id) ? $user->id : Auth::user()->id,
72
            'product_backlog_id' => $productBacklogId,
73
            'effort' => 0,
74
            'config_issue_effort_id' => 1,
75
            'issue_type_id' => 1,
76
            'number' => $obj->iid,
77
            'title' => $obj->title,
78
            'description' => $obj->description,
79
            'state' => $obj->state,
80
            'html_url' => $obj->web_url,
81
            'created_at' => Carbon::parse($obj->created_at)->toDateTimeString(),
82
            'updated_at' => Carbon::parse($obj->updated_at)->toDateTimeString(),
83
        ];
84
    }
85
86
    public function readRepositories()
87
    {
88
        $repos = collect(Helper::request(env('GITLAB_INSTANCE_URI').'api/v3/projects?access_token='.Auth::user()->token));
89
90
        $response = $repos->map(function ($repo) {
91
            return $this->tplRepository($repo);
92
        });
93
94
        return $response;
95
    }
96
97
    public function createOrUpdateRepository($owner, $obj, $oldTitle = null)
98
    {
99
    }
100
101
    public function organization($obj)
0 ignored issues
show
Documentation introduced by
The return type could not be reliably inferred; please add a @return annotation.

Our type inference engine in quite powerful, but sometimes the code does not provide enough clues to go by. In these cases we request you to add a @return annotation as described here.

Loading history...
102
    {
103
104
        if (!isset($obj->owner) && !isset($obj->namespace)) {
105
            return false;
106
        }
107
108
        if (!isset($obj->owner) && isset($obj->namespace)) {
109
            // To avoid to make unnecessary calls to the api to get the groups info saving the fetched groups into a private variable
110
            if (!isset($this->gitlabGroups[$obj->namespace->id])) {
111
                $group = current(collect(Helper::request(env('GITLAB_INSTANCE_URI').'api/v3/groups/'.$obj->namespace->id.'?access_token='.Auth::user()->token)));
112
113
                $this->gitlabGroups[$obj->namespace->id] = $group;
114
            }
115
116
            $group = $this->gitlabGroups[$obj->namespace->id];
117
118
            $obj->owner = new \stdClass;
119
            $obj->owner->id = $group['id'];
120
            $obj->owner->username = $group['path'];
121
            $obj->owner->web_url = $group['web_url'];
122
            $obj->owner->avatar_url = $group['avatar_url'];
123
        }
124
125
        $data = [
126
            'provider_id' => $obj->owner->id,
127
            'username' => $obj->owner->username,
128
            'url' => $obj->owner->web_url,
129
            'repos_url' => null,
130
            'events_url' => null,
131
            'hooks_url' => null,
132
            'issues_url' => null,
133
            'members_url' => null,
134
            'public_members_url' => null,
135
            'avatar_url' => $obj->owner->avatar_url,
136
            'description' => null,
137
            'title' => $obj->owner->username,
138
            'blog' => null,
139
            'location' => null,
140
            'email' => null,
141
            'public_repos' => null,
142
            'html_url' => null,
143
            'total_private_repos' => null,
144
            'since' => @Carbon::parse($obj->namespace->created_at)->toDateTimeString(),
145
            'disk_usage' => null,
146
        ];
147
148
        try {
149
            $organization = Organization::create($data);
150
        } catch (\Illuminate\Database\QueryException $e) {
151
            $organization = Organization::where('username', $data['username'])
152
                ->where('provider', 'gitlab')->first();
153
        }
154
155
        $organization->users()->sync([Auth::id()]);
156
157
        return $organization;
158
    }
159
160
    /**
161
     * Get all members from a specific group in gitlab
162
     *
163
     * @param $group
164
     * @return \Illuminate\Support\Collection
165
     */
166
    private function getGroupsMembers($group)
167
    {
168
        $members = collect(Helper::request(env('GITLAB_INSTANCE_URI').'api/v3/groups/'.$group.'/members?access_token='.Auth::user()->token));
169
170
        return $members;
171
    }
172
173
    /**
174
     * Get all members from the project in gitlab
175
     *
176
     * @param $projectId
177
     * @return \Illuminate\Support\Collection
178
     */
179
    private function getProjectMembers($projectId)
180
    {
181
        $members = collect(Helper::request(env('GITLAB_INSTANCE_URI').'api/v3/projects/'.$projectId.'/members?access_token='.Auth::user()->token));
182
183
        return $members;
184
    }
185
186
    /**
187
     * A project can be shared with many groups and each group has its members
188
     * This method retrieves all members from the groups that the project is shared with
189
     *
190
     * @param $projectId
191
     * @return \Illuminate\Support\Collection|static
192
     */
193
    private function getProjectSharedGroupsMembers($projectId)
194
    {
195
        $project = Helper::request(env('GITLAB_INSTANCE_URI').'api/v3/projects/'.$projectId.'?access_token='.Auth::user()->token);
196
197
        $members = new \Illuminate\Support\Collection();
198
199
        if (!empty($project->shared_with_groups)) {
200
            foreach ($project->shared_with_groups as $group) {
201
                $groupsMembers = $this->getGroupsMembers($group->group_id);
202
203
                $members = $members->merge($groupsMembers);
204
            }
205
        }
206
207
        return $members;
208
    }
209
210
    /**
211
     * Retrives all project members from three pespectives
212
     *  Members from the project itself
213
     *  Members of the groups that the project is owned by
214
     *  Members by the groups that the project is shared with
215
     *
216
     * @param $owner
217
     * @param $repo
218
     * @param null $providerId
219
     */
220
    public function readCollaborators($owner, $repo, $providerId = null)
221
    {
222
        $collaborators = $this->getGroupsMembers($owner);
223
224
        if ($providerId) {
225
            $projectMembers = $this->getProjectMembers($providerId);
226
            $collaborators = $collaborators->merge($projectMembers);
227
228
            $projectSharedGroupsMembers = $this->getProjectSharedGroupsMembers($providerId);
229
            $collaborators = $collaborators->merge($projectSharedGroupsMembers);
230
        }
231
232
        foreach ($collaborators as $collaborator) {
233
            if (isset($collaborator->id)) {
234
                $data = [
235
                    'provider_id' => $collaborator->id,
236
                    'username' => $collaborator->username,
237
                    'name' => $collaborator->name,
238
                    'avatar' => $collaborator->avatar_url,
239
                    'html_url' => $collaborator->web_url,
240
                    'email' => null,
241
                    'remember_token' => null,
242
                    'bio' => null,
243
                    'location' => null,
244
                    'blog' => null,
245
                    'since' => null,
246
                    'token' => null,
247
                    'position_held' => null,
248
                ];
249
250
                try {
251
                    $user = User::firstOrCreate($data);
0 ignored issues
show
Bug introduced by
The method firstOrCreate() does not exist on GitScrum\Models\User. Did you maybe mean create()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
252
                } catch (\Exception $e) {
253
                    $user = User::where('username', $collaborator->username)
254
                        ->where('provider', 'gitlab')->first();
255
                }
256
257
                $userId[] = $user->id;
0 ignored issues
show
Coding Style Comprehensibility introduced by
$userId was never initialized. Although not strictly required by PHP, it is generally a good practice to add $userId = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
258
            }
259
        }
260
261
        $organization = Organization::where('username', $owner)
262
            ->where('provider', 'gitlab')->first()->users();
263
264
        if(!$organization->where('user_id', Auth::user()->id)->count())
265
        {
266
            $organization->attach($userId);
0 ignored issues
show
Bug introduced by
The variable $userId 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...
267
        }
268
269
    }
270
271
    public function createBranches($owner, $product_backlog_id, $repo)
272
    {
273
    }
274
275
    public function readIssues()
276
    {
277
        $repos = ProductBacklog::all();
278
279
        foreach ($repos as $repo) {
280
            $issues = Helper::request(env('GITLAB_INSTANCE_URI').'api/v3/projects/'.$repo->provider_id.
281
                '/issues?access_token='.Auth::user()->token);
282
283
            $issues = is_array($issues) ? $issues : [$issues];
284
285
            foreach ($issues as $issue) {
286
                try{
287
                    $data = $this->tplIssue($issue, $repo->id);
288
                    if (!Issue::where('provider_id', $data['provider_id'])->where('provider', 'gitlab')->first()) {
289
                        Issue::create($data)->users()->sync([$data['user_id']]);
290
                    }
291
                } catch( \Exception $e){
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
292
293
                }
294
            }
295
        }
296
    }
297
298
    public function createOrUpdateIssue($obj)
299
    {
300
    }
301
302
    public function createOrUpdateIssueComment($obj, $verb = 'POST')
303
    {
304
    }
305
306
    public function deleteIssueComment($obj)
307
    {
308
    }
309
}
310