Completed
Push — master ( e2a414...b5f838 )
by Renato
8s
created

Gitlab::deleteIssueComment()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 3
rs 10
cc 1
eloc 1
nc 1
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 GitScrum\Models\Branch;
11
use Carbon\Carbon;
12
use GitScrum\Contracts\ProviderInterface;
13
14
class Gitlab implements ProviderInterface
15
{
16
    private $gitlabGroups;
17
18
    public function tplUser($obj)
19
    {
20
        return [
21
            'provider_id' => $obj->id,
22
            'provider' => 'gitlab',
23
            'username' => $obj->nickname,
24
            'name' => $obj->name,
25
            'token' => $obj->token,
26
            'avatar' => @$obj->user['avatar_url'],
27
            'html_url' => @$obj->user['web_url'],
28
            'bio' => @$obj->user['bio'],
29
            'since' => Carbon::parse($obj->user['created_at'])->toDateTimeString(),
30
            'location' => @$obj->user['location'],
31
            'blog' => @$obj->user['blog'],
32
            'email' => $obj->email,
33
        ];
34
    }
35
36
    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...
37
    {
38
        $organization = $this->organization($repo);
39
40
        if (!$organization) {
41
            return;
42
        }
43
44
        return (object) [
45
            'provider_id' => $repo->id,
46
            'organization_id' => $organization->id,
47
            'organization_title' => $organization->username,
48
            'slug' => $slug ? $slug : Helper::slug($repo->path),
49
            'title' => $repo->path,
50
            'fullname' => $repo->name,
51
            'is_private' => $repo->public == true,
52
            'html_url' => $repo->http_url_to_repo,
53
            'description' => $repo->description,
54
            'fork' => null,
55
            'url' => $repo->web_url,
56
            'since' => Carbon::parse($repo->created_at)->toDateTimeString(),
57
            'pushed_at' => Carbon::parse($repo->last_activity_at)->toDateTimeString(),
58
            'ssh_url' => $repo->ssh_url_to_repo,
59
            'clone_url' => $repo->ssh_url_to_repo,
60
            'homepage' => $repo->web_url,
61
            'default_branch' => $repo->default_branch,
62
        ];
63
    }
64
65
    public function tplIssue($obj, $productBacklogId)
66
    {
67
        if (isset($obj->assignee->username)) {
68
            $user = User::where('username', @$obj->assignee->username)
69
                ->where('provider', 'gitlab')->first();
70
        }
71
72
        return [
73
            'provider_id' => $obj->id,
74
            'user_id' => isset($user->id) ? $user->id : Auth::user()->id,
0 ignored issues
show
Bug introduced by
The variable $user 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...
75
            'product_backlog_id' => $productBacklogId,
76
            'effort' => 0,
77
            'config_issue_effort_id' => 1,
78
            'issue_type_id' => 1,
79
            'number' => $obj->iid,
80
            'title' => $obj->title,
81
            'description' => $obj->description,
82
            'state' => $obj->state,
83
            'html_url' => isset($obj->web_url) ? $obj->web_url : '',
84
            'created_at' => Carbon::parse($obj->created_at)->toDateTimeString(),
85
            'updated_at' => Carbon::parse($obj->updated_at)->toDateTimeString(),
86
        ];
87
    }
88
89
    public function readRepositories()
90
    {
91
        $repos = collect(Helper::request(env('GITLAB_INSTANCE_URI').'api/v3/projects?access_token='.Auth::user()->token));
92
93
        $response = $repos->map(function ($repo) {
94
            return $this->tplRepository($repo);
95
        });
96
97
        return $response;
98
    }
99
100
    public function createOrUpdateRepository($owner, $obj, $oldTitle = null)
101
    {
102
    }
103
104
    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...
105
    {
106
107
        if (!isset($obj->owner) && !isset($obj->namespace)) {
108
            return false;
109
        }
110
111
        if (!isset($obj->owner) && isset($obj->namespace)) {
112
            // To avoid to make unnecessary calls to the api to get the groups info saving the fetched groups into a private variable
113
            if (!isset($this->gitlabGroups[$obj->namespace->id])) {
114
                $group = current(collect(Helper::request(env('GITLAB_INSTANCE_URI').'api/v3/groups/'.$obj->namespace->id.'?access_token='.Auth::user()->token)));
115
116
                $this->gitlabGroups[$obj->namespace->id] = $group;
117
            }
118
119
            $group = $this->gitlabGroups[$obj->namespace->id];
120
121
            $obj->owner = new \stdClass;
122
            $obj->owner->id = $group['id'];
123
            $obj->owner->username = $group['path'];
124
            $obj->owner->web_url = $group['web_url'];
125
            $obj->owner->avatar_url = $group['avatar_url'];
126
        }
127
128
        $data = [
129
            'provider_id' => $obj->owner->id,
130
            'username' => $obj->owner->username,
131
            'url' => $obj->owner->web_url,
132
            'repos_url' => null,
133
            'events_url' => null,
134
            'hooks_url' => null,
135
            'issues_url' => null,
136
            'members_url' => null,
137
            'public_members_url' => null,
138
            'avatar_url' => $obj->owner->avatar_url,
139
            'description' => null,
140
            'title' => $obj->owner->username,
141
            'blog' => null,
142
            'location' => null,
143
            'email' => null,
144
            'public_repos' => null,
145
            'html_url' => null,
146
            'total_private_repos' => null,
147
            'since' => @Carbon::parse($obj->namespace->created_at)->toDateTimeString(),
148
            'disk_usage' => null,
149
        ];
150
151
        try {
152
            $organization = Organization::create($data);
153
        } catch (\Illuminate\Database\QueryException $e) {
154
            $organization = Organization::where('username', $data['username'])
155
                ->where('provider', 'gitlab')->first();
156
        }
157
158
        $organization->users()->sync([Auth::id()]);
159
160
        return $organization;
161
    }
162
163
    /**
164
     * Get all members from a specific group in gitlab
165
     *
166
     * @param $group
167
     * @return \Illuminate\Support\Collection
168
     */
169
    private function getGroupsMembers($group)
170
    {
171
        $members = collect(Helper::request(env('GITLAB_INSTANCE_URI').'api/v3/groups/'.$group.'/members?access_token='.Auth::user()->token));
172
173
        return $members;
174
    }
175
176
    /**
177
     * Get all members from the project in gitlab
178
     *
179
     * @param $projectId
180
     * @return \Illuminate\Support\Collection
181
     */
182
    private function getProjectMembers($projectId)
183
    {
184
        $members = collect(Helper::request(env('GITLAB_INSTANCE_URI').'api/v3/projects/'.$projectId.'/members?access_token='.Auth::user()->token));
185
186
        return $members;
187
    }
188
189
    /**
190
     * A project can be shared with many groups and each group has its members
191
     * This method retrieves all members from the groups that the project is shared with
192
     *
193
     * @param $projectId
194
     * @return \Illuminate\Support\Collection|static
195
     */
196
    private function getProjectSharedGroupsMembers($projectId)
197
    {
198
        $project = Helper::request(env('GITLAB_INSTANCE_URI').'api/v3/projects/'.$projectId.'?access_token='.Auth::user()->token);
199
200
        $members = new \Illuminate\Support\Collection();
201
202
        if (!empty($project->shared_with_groups)) {
203
            foreach ($project->shared_with_groups as $group) {
204
                $groupsMembers = $this->getGroupsMembers($group->group_id);
205
206
                $members = $members->merge($groupsMembers);
207
            }
208
        }
209
210
        return $members;
211
    }
212
213
    /**
214
     * Retrives all project members from three pespectives
215
     *  Members from the project itself
216
     *  Members of the groups that the project is owned by
217
     *  Members by the groups that the project is shared with
218
     *
219
     * @param $owner
220
     * @param $repo
221
     * @param null $providerId
222
     */
223
    public function readCollaborators($owner, $repo, $providerId = null)
224
    {
225
        $collaborators = $this->getGroupsMembers($owner);
226
227
        if ($providerId) {
228
            $projectMembers = $this->getProjectMembers($providerId);
229
            $collaborators = $collaborators->merge($projectMembers);
230
231
            $projectSharedGroupsMembers = $this->getProjectSharedGroupsMembers($providerId);
232
            $collaborators = $collaborators->merge($projectSharedGroupsMembers);
233
        }
234
235
        foreach ($collaborators as $collaborator) {
236
            if (isset($collaborator->id)) {
237
                $data = [
238
                    'provider_id' => $collaborator->id,
239
                    'username' => $collaborator->username,
240
                    'name' => $collaborator->name,
241
                    'avatar' => $collaborator->avatar_url,
242
                    'html_url' => $collaborator->web_url,
243
                    'email' => null,
244
                    'remember_token' => null,
245
                    'bio' => null,
246
                    'location' => null,
247
                    'blog' => null,
248
                    'since' => null,
249
                    'token' => null,
250
                    'position_held' => null,
251
                ];
252
253
                try {
254
                    $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...
255
                } catch (\Exception $e) {
256
                    $user = User::where('username', $collaborator->username)
257
                        ->where('provider', 'gitlab')->first();
258
                }
259
260
                $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...
261
            }
262
        }
263
264
        $organization = Organization::where('username', $owner)
265
            ->where('provider', 'gitlab')->first()->users();
266
267
        if(!$organization->where('user_id', Auth::user()->id)->count())
268
        {
269
            $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...
270
        }
271
272
    }
273
274
    public function createBranches($owner, $product_backlog_id, $repo, $providerId = null)
275
    {
276
        $branches = collect(Helper::request(env('GITLAB_INSTANCE_URI').'api/v3/projects/'.$providerId.'/repository/branches?access_token='.Auth::user()->token));
277
278
        $branchesData = [];
279
        foreach ($branches as $branch) {
280
            $branchesData[] = [
281
                'product_backlog_id' => $product_backlog_id,
282
                'title' => $branch->name,
283
                'sha' => $branch->commit->id,
284
                'created_at' => Carbon::now(),
285
                'updated_at' => Carbon::now()
286
            ];
287
        }
288
289
        if ($branchesData) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $branchesData of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
290
            Branch::insert($branchesData);
0 ignored issues
show
Bug introduced by
The method insert() does not exist on GitScrum\Models\Branch. Did you maybe mean insertAndSetId()?

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...
291
        }
292
    }
293
294
    public function readIssues()
295
    {
296
        $repos = ProductBacklog::all();
297
298
        foreach ($repos as $repo) {
299
            $issues = Helper::request(env('GITLAB_INSTANCE_URI').'api/v3/projects/'.$repo->provider_id.
300
                '/issues?access_token='.Auth::user()->token);
301
302
            $issues = is_array($issues) ? $issues : [$issues];
303
304
            foreach ($issues as $issue) {
305
                try{
306
                    $data = $this->tplIssue($issue, $repo->id);
307
                    if (!Issue::where('provider_id', $data['provider_id'])->where('provider', 'gitlab')->first()) {
308
                        Issue::create($data)->users()->sync([$data['user_id']]);
309
                    }
310
                } catch( \Exception $e){
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
311
                    
312
                }
313
            }
314
        }
315
    }
316
317
    public function createOrUpdateIssue($obj)
318
    {
319
    }
320
321
    public function createOrUpdateIssueComment($obj, $verb = 'POST')
322
    {
323
    }
324
325
    public function deleteIssueComment($obj)
326
    {
327
    }
328
}
329