Completed
Push — master ( bd2348...f2f7cf )
by Renato
02:33
created

Github::organization()   B

Complexity

Conditions 4
Paths 8

Size

Total Lines 48
Code Lines 36

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 48
rs 8.7396
c 0
b 0
f 0
cc 4
eloc 36
nc 8
nop 1
1
<?php
2
3
namespace GitScrum\Classes;
4
5
use Auth;
6
use GitScrum\Models\Branch;
7
use GitScrum\Models\Commit;
8
use GitScrum\Models\ConfigStatus;
9
use GitScrum\Models\User;
10
use GitScrum\Models\Issue;
11
use GitScrum\Models\Organization;
12
use GitScrum\Models\ProductBacklog;
13
use Carbon\Carbon;
14
use GitScrum\Libraries\Phpcs;
0 ignored issues
show
Bug introduced by
This use statement conflicts with another class in this namespace, GitScrum\Classes\Phpcs.

Let’s assume that you have a directory layout like this:

.
|-- OtherDir
|   |-- Bar.php
|   `-- Foo.php
`-- SomeDir
    `-- Foo.php

and let’s assume the following content of Bar.php:

// Bar.php
namespace OtherDir;

use SomeDir\Foo; // This now conflicts the class OtherDir\Foo

If both files OtherDir/Foo.php and SomeDir/Foo.php are loaded in the same runtime, you will see a PHP error such as the following:

PHP Fatal error:  Cannot use SomeDir\Foo as Foo because the name is already in use in OtherDir/Foo.php

However, as OtherDir/Foo.php does not necessarily have to be loaded and the error is only triggered if it is loaded before OtherDir/Bar.php, this problem might go unnoticed for a while. In order to prevent this error from surfacing, you must import the namespace with a different alias:

// Bar.php
namespace OtherDir;

use SomeDir\Foo as SomeDirFoo; // There is no conflict anymore.
Loading history...
15
16
class Github
17
{
18
    public function templateRepository($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...
19
    {
20
        return (object) [
21
            'github_id' => $repo->id,
22
            'organization_id' => $this->organization($repo->owner->login),
23
            'organization_title' => $repo->owner->login,
24
            'slug' => $slug ? $slug : Helper::slug($repo->name),
25
            'title' => $repo->name,
26
            'fullname' => $repo->full_name,
27
            'is_private' => $repo->private,
28
            'html_url' => $repo->html_url,
29
            'description' => $repo->description,
30
            'fork' => $repo->fork,
31
            'url' => $repo->url,
32
            'since' => Carbon::parse($repo->created_at)->toDateTimeString(),
33
            'pushed_at' => Carbon::parse($repo->pushed_at)->toDateTimeString(),
34
            'ssh_url' => $repo->ssh_url,
35
            'clone_url' => $repo->clone_url,
36
            'homepage' => $repo->homepage,
37
            'default_branch' => $repo->default_branch,
38
        ];
39
    }
40
41
    public function readRepositories()
42
    {
43
        $repos = $this->request('https://api.github.com/user/repos');
44
45
        $response = [];
46
        foreach ($repos as $repo) {
47
            $response[] = $this->templateRepository($repo);
48
        }
49
50
        return collect($response);
51
    }
52
53
    public function createOrUpdateRepository($owner, $obj, $oldTitle = null)
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...
54
    {
55
        $params = [
56
            'name' => str_slug($obj->title, '-'),
57
            'description' => $obj->description,
58
        ];
59
60
        if (is_null($oldTitle)) {
61
            $response = $this->request('https://api.github.com/orgs/'.$owner.'/repos', true, 'POST', $params);
62
        } else {
63
            $oldTitle = str_slug($oldTitle, '-');
64
            $response = $this->request('https://api.github.com/repos/'.$owner.'/'.$oldTitle, true, 'POST', $params);
65
        }
66
        return (object) $response;
67
    }
68
69
    public function organization($login)
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...
70
    {
71
        $orgData = $this->request('https://api.github.com/orgs/'.$login);
72
73
        if (!isset($orgData->id)) {
74
            $orgData = $this->request('https://api.github.com/users/'.$login);
75
        }
76
77
        $data = [
78
            'github_id' => @$orgData->id,
79
            'username' => @$orgData->login,
80
            'url' => @$orgData->url,
81
            'repos_url' => @$orgData->repos_url,
82
            'events_url' => @$orgData->events_url,
83
            'hooks_url' => @$orgData->hooks_url,
84
            'issues_url' => @$orgData->issues_url,
85
            'members_url' => @$orgData->members_url,
86
            'public_members_url' => @$orgData->public_members_url,
87
            'avatar_url' => @$orgData->avatar_url,
88
            'description' => @$orgData->description,
89
            'title' => @$orgData->name,
90
            'blog' => @$orgData->blog,
91
            'location' => @$orgData->location,
92
            'email' => @$orgData->email,
93
            'public_repos' => @$orgData->public_repos,
94
            'html_url' => @$orgData->html_url,
95
            'total_private_repos' => @$orgData->total_private_repos,
96
            'since' => @Carbon::parse($orgData->created_at)->toDateTimeString(),
97
            'disk_usage' => @$orgData->disk_usage,
98
        ];
99
100
        try {
101
            $organization = Organization::create($data);
102
        } catch (\Illuminate\Database\QueryException $e) {
103
            $organization = Organization::where('username', $orgData->login)->first();
104
        }
105
106
        if (!isset(Auth::user()->organizations()->where(
107
            'organization_id',
108
            $organization->id
109
        )->first()->id)) {
110
            Auth::user()->organizations()->attach($organization->id);
111
        }
112
113
        $this->members($orgData->login);
114
115
        return $organization->id;
116
    }
117
118
    public function members($org)
119
    {
120
        $members = $this->request('https://api.github.com/orgs/'.$org.'/members');
121
        $organization = Organization::where('username', $org)->first()->users();
122
123
        foreach ($members as $member) {
124
            if (isset($member->id)) {
125
                $data = [
126
                    'github_id' => $member->id,
127
                    'username' => $member->login,
128
                    'name' => $member->login,
129
                    'avatar' => $member->avatar_url,
130
                    'html_url' => $member->html_url,
131
                    'email' => null,
132
                    'remember_token' => null,
133
                    'bio' => null,
134
                    'location' => null,
135
                    'blog' => null,
136
                    'since' => null,
137
                    'token' => null,
138
                    'position_held' => null,
139
                ];
140
141
                try {
142
                    $user = User::create($data);
143
                } catch (\Exception $e) {
144
                    $user = User::where('username', $member->login)->first();
145
                }
146
147
                if (!isset($organization->where('user_id', Auth::user()->id)->first()->id)) {
148
                    $organization->attach($user->id);
149
                }
150
            }
151
        }
152
    }
153
154
    public function createBranches($owner, $product_backlog_id, $repo)
155
    {
156
        $y = 0;
157
        for ($i = 1; $i > $y; ++$i) {
158
            $branches = $this->request('https://api.github.com/repos/'.$owner.'/'.$repo.'/branches?page='.$i);
159
            foreach ($branches as $branch) {
160
                $data = [
161
                    'product_backlog_id' => $product_backlog_id,
162
                    'title' => $branch->name,
163
                    'sha' => $branch->commit->sha,
164
                ];
165
                Branch::create($data);
166
            }
167
            if (count($branches) < 30) {
168
                $y = $i + 2;
169
            }
170
        }
171
    }
172
173
    public function readIssues()
174
    {
175
        $repos = ProductBacklog::all();
176
177
        foreach ($repos as $repo) {
178
            $issues = $this->request('https://api.github.com/repos/'.$repo->organization->username.'/'.$repo->title.'/issues?state=all');
179
180
            foreach ($issues as $issue) {
181
                $user = User::where('username', $issue->user->login)->first();
182
183
                $data = [
184
                    'github_id' => $issue->id,
185
                    'user_id' => isset($user_id) ? $user->id : Auth::user()->id,
186
                    'product_backlog_id' => $repo->id,
187
                    'effort' => 0,
188
                    'config_issue_effort_id' => 1,
189
                    'issue_type_id' => 1,
190
                    'number' => $issue->number,
191
                    'title' => $issue->title,
192
                    'description' => $issue->body,
193
                    'state' => $issue->state,
194
                    'html_url' => $issue->html_url,
195
                    'created_at' => $issue->created_at,
196
                    'updated_at' => $issue->updated_at,
197
                ];
198
199
                if (!is_null($issue->closed_at)) {
200
                    $data['closed_at'] = Carbon::parse($issue->closed_at)->format('Y-m-d h:m:s');
201
                    $data['closed_user_id'] = $data['user_id'];
202
                    $data['config_status_id'] = ConfigStatus::where('type', 'issue')
203
                        ->where('is_closed', 1)->first()->id;
204
                }
205
206
                if (!Issue::where('github_id', $issue->id)->first()) {
207
                    Issue::create($data)->users()->sync([$data['user_id']]);
208
                }
209
                //foreach ($issue->assignees as $assign) {
210
                //    User::where('github_id', $assign->id)->first()->issues()->sync([$issueId], false);
211
                //}
212
            }
213
        }
214
    }
215
216
    public function createOrUpdateIssue($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...
217
    {
218
        $params = [
219
            'title' => $obj->title,
220
            'body' => $obj->description,
221
        ];
222
223
        $response = $this->request('https://api.github.com/repos/'.
224
            $obj->productBacklog->organization->username.'/'.
225
            $obj->productBacklog->title.'/issues'.(isset($obj->number) ? '/'.$obj->number : ''),
226
            true, 'POST', $params);
227
228
        return (object) $response;
229
    }
230
231
    public function createOrUpdateIssueComment($obj, $verb='POST')
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...
232
    {
233
        $params = [
234
            'body' => $obj->comment,
235
        ];
236
237
        $response = $this->request('https://api.github.com/repos/'.
238
            $obj->issue->productBacklog->organization->username.'/'.
239
            $obj->issue->productBacklog->title.'/issues'.(isset($obj->github_id)?'':'/'.$obj->issue->number).'/comments'.
240
            (isset($obj->github_id)?'/'.$obj->github_id:''),
241
            true, $verb, $params);
242
243
        return (object) $response;
244
245
    }
246
247
    public function deleteIssueComment($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...
248
    {
249
        return $this->createOrUpdateIssueComment($obj, 'DELETE');
250
    }
251
252
    private function request($url, $auth = true, $customRequest = null, $postFields = null)
253
    {
254
        $user = Auth::user();
255
        $ch = curl_init();
256
        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 5.1; rv:31.0) Gecko/20100101 Firefox/31.0');
257
        curl_setopt($ch, CURLOPT_URL, $url);
258
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
259
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
260
        curl_setopt($ch, CURLOPT_AUTOREFERER, true);
261
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
262
263
        if (!is_null($postFields)) {
264
            $postFields = json_encode($postFields);
265
            curl_setopt($ch, CURLOPT_POST, true);
266
            curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields);
267
            curl_setopt($ch, CURLOPT_HTTPHEADER,  ['Content-Type: application/json',
268
                'Content-Length: '.strlen($postFields), ]);
269
        }
270
271
        if (!is_null($customRequest)) {
272
            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $customRequest); //'PATCH'
273
        }
274
275
        if ($auth) {
276
            curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
277
            curl_setopt($ch, CURLOPT_USERPWD, $user->username.':'.$user->token);
278
        }
279
280
        $status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
0 ignored issues
show
Unused Code introduced by
$status_code is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
281
        $result = curl_exec($ch);
282
        curl_close($ch);
283
284
        return json_decode($result);
285
    }
286
287
    /*
288
    public function organizations(){
289
        $this->request('https://api.github.com/user/orgs');
290
    }
291
292
    public function repositories($org){
293
        ///orgs/:org/repos
294
        return $this->request('https://api.github.com/orgs/'.$org.'/repos');
295
    }
296
    */
297
298
    public function setCommits($owner, $repo, $branch, $since = null)
299
    {
300
        ////repos/:owner/:repo/commits?sha=branchname
301
        $y = 0;
302
        for ($i = 1; $i > $y; ++$i) {
303
            $commits = $this->request('https://api.github.com/repos/'.$owner.'/'.$repo.'/commits?page='.$i.'&sha='.$branch.(is_null($since) ? '' : '&since='.$since));
304
            $branch = Branch::join('product_backlogs', 'branches.product_backlog_id', '=', 'repositories.id')
305
                            ->where('branches.name', $branch)
306
                            ->where('product_backlogs.name', $repo)
307
                            ->select('branches.id AS branch_id', 'repositories.id AS product_backlog_id')->first();
308
            $CommitRepository = new CommitRepository();
309
            foreach ($commits as $commit) {
310
                try {
311
                    $user = User::where('github_id', $commit->author->id)->first();
312
                    $userId = $user->id;
313
                } catch (\Exception $e) {
314
                    $userId = 0;
315
                }
316
                try {
317
                    if (isset($commit->sha)) {
318
                        $data = [
319
                            'product_backlog_id' => $branch->product_backlog_id,
320
                            'branch_id' => $branch->branch_id,
321
                            'user_id' => $userId,
322
                            'sha' => $commit->sha,
323
                            'url' => $commit->url,
324
                            'message' => $commit->commit->message,
325
                            'html_url' => $commit->html_url,
326
                            'date' => $commit->commit->author->date,
327
                            'tree_sha' => $commit->commit->tree->sha,
328
                            'tree_url' => $commit->commit->tree->url,
329
                        ];
330
                        $commitData = $CommitRepository->add($data);
331
                        $this->setCommitFiles($owner, $repo, $commitData->sha, $commitData);
332
                    }
333
                } catch (\Exception $e) {
334
                    dd($data, $commit);
335
                }
336
            }
337
            if (count($commits) < 30) {
338
                $y = $i + 2;
339
            }
340
        }
341
    }
342
343
    public function setCommitFiles($owner, $repo, $sha, $objCommit)
344
    {
345
        // /repos/:owner/:repo/commits/:sha
346
        $commits = $this->request('https://api.github.com/repos/'.$owner.'/'.$repo.'/commits/'.$sha);
347
        $Phpcs = new Phpcs();
0 ignored issues
show
Unused Code introduced by
$Phpcs is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
348
        $CommitRepository = new CommitRepository();
349
        foreach ($commits->files as $commit) {
350
            try {
351
                $contents = $this->request($commit->contents_url);
352
                $fileRaw = file_get_contents($contents->download_url);
353
                $data = [
354
                    'commit_id' => $objCommit->id,
355
                    'sha' => $commit->sha,
356
                    'filename' => $commit->filename,
357
                    'status' => $commit->status,
358
                    'additions' => $commit->additions,
359
                    'deletions' => $commit->deletions,
360
                    'changes' => $commit->changes,
361
                    'raw_url' => $commit->raw_url,
362
                    'raw' => $fileRaw,
363
                    'patch' => (isset($commit->patch) ? $commit->patch : ''),
364
                ];
365
                $commitData = $CommitRepository->addFile($data);
0 ignored issues
show
Unused Code introduced by
$commitData is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
366
                //$Phpcs->init($fileRaw, $commitData->id);
367
            } catch (\Exception $e) {
368
                echo 'erro files ... ';
369
            }
370
        }
371
    }
372
373
    public function getCommit($owner, $repo, $sha)
374
    {
375
        // /repos/:owner/:repo/commits/:sha
376
        $commits = $this->request('https://api.github.com/repos/'.$owner.'/'.$repo.'/commits/'.$sha);
377
        dd($commits);
378
        /*
379
        foreach ($commits as $commit) {
380
            $data = [
381
                'commit_id'=>$objCommit->id,
382
                'sha'=>,
383
                'filename'=>,
384
                'status'=>,
385
                'additions'=>,
386
                'deletetions'=>,
387
                'changes'=>,
388
                'raw_url'=>,
389
                'patch'=>
390
            ];
391
        }*/
392
    }
393
394
    public function setPullRequest($owner, $repo)
395
    {
396
        ///repos/:owner/:repo/pulls
397
        $pulls = $this->request('https://api.github.com/repos/'.$owner.'/'.$repo.'/pulls');
398
        $repository = Repository::where('name', $repo)->first();
399
        $PullRequestRepository = new PullRequestRepository();
400
        foreach ($pulls as $pull) {
401
            $branch = Branch::where('name', $pull->head->ref)->first();
402
            try {
403
                $user = User::where('github_id', $pull->user->id)->first();
404
                $userId = $user->id;
405
            } catch (\Exception $e) {
406
                $userId = 0;
407
            }
408
409
            try {
410
                $headBranchId = $branch->id;
411
            } catch (\Exception $e) {
0 ignored issues
show
Unused Code introduced by
catch (\Exception $e) { $headBranchId = 0; } does not seem to be reachable.

This check looks for unreachable code. It uses sophisticated control flow analysis techniques to find statements which will never be executed.

Unreachable code is most often the result of return, die or exit statements that have been added for debug purposes.

function fx() {
    try {
        doSomething();
        return true;
    }
    catch (\Exception $e) {
        return false;
    }

    return false;
}

In the above example, the last return false will never be executed, because a return statement has already been met in every possible execution path.

Loading history...
412
                $headBranchId = 0;
413
            }
414
415
            try {
416
                $branch = Branch::where('name', $pull->base->ref)->first();
417
                $baseBranchId = $branch->id;
418
            } catch (\Exception $e) {
419
                $baseBranchId = 0;
420
            }
421
422
            $data = [
423
                'github_id' => $pull->id,
424
                'number' => $pull->number,
425
                'user_id' => $userId,
426
                'product_backlog_id' => $repository->id,
427
                'url' => $pull->url,
428
                'html_url' => $pull->html_url,
429
                'issue_url' => $pull->issue_url,
430
                'commits_url' => $pull->commits_url,
431
                'state' => $pull->state,
432
                'title' => $pull->title,
433
                'body' => $pull->body,
434
                'github_created_at' => $pull->created_at,
435
                'github_updated_at' => $pull->updated_at,
436
                'head_branch_id' => $headBranchId,
437
                'base_branch_id' => $baseBranchId,
438
            ];
439
440
            $pull = $PullRequestRepository->add($data);
441
442
            $commits = $this->request('https://api.github.com/repos/'.$owner.'/'.$repo.'/pulls/'.$pull->number.'/commits');
443
            //dd($commits);
444
            foreach ($commits as $commit) {
445
                $c = Commit::where('sha', '=', $commit->sha)->first();
446
                $pull->commit()->sync([$c->id], false);
447
            }
448
        }
449
    }
450
451
    public function getStatsCommitActivity($owner, $repo)
452
    {
453
        ///repos/:owner/:repo/stats/contributors
454
        $stats = $this->request('https://api.github.com/repos/'.$owner.'/'.$repo.'/stats/commit_activity');
455
        $arr = [];
456
        foreach ($stats as $stat) {
457
            $arr[] = $stat->total;
458
        }
459
460
        return $arr;
461
    }
462
}
463