Completed
Push — master ( 7bc3eb...84c9ab )
by Renato
02:34
created

Github::getCommit()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 20
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 20
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 3
nc 1
nop 3
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 = collect($this->request('https://api.github.com/user/repos'));
44
45
        $response = $repos->map(function ($repo) {
46
            return $this->templateRepository($repo);
47
        });
48
49
        return $response;
50
    }
51
52
    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...
53
    {
54
        $params = [
55
            'name' => str_slug($obj->title, '-'),
56
            'description' => $obj->description,
57
        ];
58
59
        if (is_null($oldTitle)) {
60
            $response = $this->request('https://api.github.com/orgs/'.$owner.'/repos', true, 'POST', $params);
61
        } else {
62
            $oldTitle = str_slug($oldTitle, '-');
63
            $response = $this->request('https://api.github.com/repos/'.$owner.DIRECTORY_SEPARATOR.$oldTitle, true, 'POST', $params);
64
        }
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.DIRECTORY_SEPARATOR.$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.DIRECTORY_SEPARATOR.$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.DIRECTORY_SEPARATOR.
225
            $obj->productBacklog->title.'/issues'.(isset($obj->number) ? DIRECTORY_SEPARATOR.$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.DIRECTORY_SEPARATOR.
239
            $obj->issue->productBacklog->title.'/issues'.(isset($obj->github_id) ? '' : DIRECTORY_SEPARATOR.$obj->issue->number).'/comments'.
240
            (isset($obj->github_id) ? DIRECTORY_SEPARATOR.$obj->github_id : ''),
241
            true, $verb, $params);
242
243
        return (object) $response;
244
    }
245
246
    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...
247
    {
248
        return $this->createOrUpdateIssueComment($obj, 'DELETE');
249
    }
250
251
    private function request($url, $auth = true, $customRequest = null, $postFields = null)
252
    {
253
        $user = Auth::user();
254
        $ch = curl_init();
255
        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 5.1; rv:31.0) Gecko/20100101 Firefox/31.0');
256
        curl_setopt($ch, CURLOPT_URL, $url);
257
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
258
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
259
        curl_setopt($ch, CURLOPT_AUTOREFERER, true);
260
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
261
262
        if (env('PROXY_PORT')) {
263
            curl_setopt($ch, CURLOPT_PROXYPORT, env('PROXY_PORT'));
264
            curl_setopt($ch, CURLOPT_PROXYTYPE, env('PROXY_METHOD'));
265
            curl_setopt($ch, CURLOPT_PROXY, env('PROXY_SERVER'));
266
        }
267
268
        if (env('PROXY_USER')) {
269
            curl_setopt($ch, CURLOPT_PROXYUSERPWD, env('PROXY_USER').':'.env('PROXY_USER'));
270
        }
271
272
        if (!is_null($postFields)) {
273
            $postFields = json_encode($postFields);
274
            curl_setopt($ch, CURLOPT_POST, true);
275
            curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields);
276
            curl_setopt($ch, CURLOPT_HTTPHEADER,  ['Content-Type: application/json',
277
                'Content-Length: '.strlen($postFields), ]);
278
        }
279
280
        if (!is_null($customRequest)) {
281
            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $customRequest); //'PATCH'
282
        }
283
284
        if ($auth && isset($user->username)) {
285
            curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
286
            curl_setopt($ch, CURLOPT_USERPWD, $user->username.':'.$user->token);
287
        }
288
289
        $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...
290
        $result = curl_exec($ch);
291
        curl_close($ch);
292
293
        return json_decode($result);
294
    }
295
296
    /*
297
    public function organizations(){
298
        $this->request('https://api.github.com/user/orgs');
299
    }
300
301
    public function repositories($org){
302
        ///orgs/:org/repos
303
        return $this->request('https://api.github.com/orgs/'.$org.'/repos');
304
    }
305
    */
306
307
    public function setCommits($owner, $repo, $branch, $since = null)
308
    {
309
        ////repos/:owner/:repo/commits?sha=branchname
310
        $y = 0;
311
        for ($i = 1; $i > $y; ++$i) {
312
            $commits = $this->request('https://api.github.com/repos/'.$owner.DIRECTORY_SEPARATOR.$repo.'/commits?page='.$i.
313
            '&sha='.$branch.(is_null($since) ? '' : '&since='.$since));
314
            $branch = Branch::join('product_backlogs', 'branches.product_backlog_id', '=', 'repositories.id')
315
                            ->where('branches.name', $branch)
316
                            ->where('product_backlogs.name', $repo)
317
                            ->select('branches.id AS branch_id', 'repositories.id AS product_backlog_id')->first();
318
            $CommitRepository = new CommitRepository();
319
            foreach ($commits as $commit) {
320
                try {
321
                    $user = User::where('github_id', $commit->author->id)->first();
322
                    $userId = $user->id;
323
                } catch (\Exception $e) {
324
                    $userId = 0;
325
                }
326
                try {
327
                    if (isset($commit->sha)) {
328
                        $data = [
329
                            'product_backlog_id' => $branch->product_backlog_id,
330
                            'branch_id' => $branch->branch_id,
331
                            'user_id' => $userId,
332
                            'sha' => $commit->sha,
333
                            'url' => $commit->url,
334
                            'message' => $commit->commit->message,
335
                            'html_url' => $commit->html_url,
336
                            'date' => $commit->commit->author->date,
337
                            'tree_sha' => $commit->commit->tree->sha,
338
                            'tree_url' => $commit->commit->tree->url,
339
                        ];
340
                        $commitData = $CommitRepository->add($data);
341
                        $this->setCommitFiles($owner, $repo, $commitData->sha, $commitData);
342
                    }
343
                } catch (\Exception $e) {
344
                    dd($data, $commit);
345
                }
346
            }
347
            if (count($commits) < 30) {
348
                $y = $i + 2;
349
            }
350
        }
351
    }
352
353
    public function setCommitFiles($owner, $repo, $sha, $objCommit)
354
    {
355
        // /repos/:owner/:repo/commits/:sha
356
        $commits = $this->request('https://api.github.com/repos/'.$owner.DIRECTORY_SEPARATOR.$repo.'/commits/'.$sha);
357
        $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...
358
        $CommitRepository = new CommitRepository();
359
        foreach ($commits->files as $commit) {
360
            try {
361
                $contents = $this->request($commit->contents_url);
362
                $fileRaw = file_get_contents($contents->download_url);
363
                $data = [
364
                    'commit_id' => $objCommit->id,
365
                    'sha' => $commit->sha,
366
                    'filename' => $commit->filename,
367
                    'status' => $commit->status,
368
                    'additions' => $commit->additions,
369
                    'deletions' => $commit->deletions,
370
                    'changes' => $commit->changes,
371
                    'raw_url' => $commit->raw_url,
372
                    'raw' => $fileRaw,
373
                    'patch' => (isset($commit->patch) ? $commit->patch : ''),
374
                ];
375
                $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...
376
                //$Phpcs->init($fileRaw, $commitData->id);
377
            } catch (\Exception $e) {
378
                echo 'erro files ... ';
379
            }
380
        }
381
    }
382
383
    public function getCommit($owner, $repo, $sha)
384
    {
385
        // /repos/:owner/:repo/commits/:sha
386
        $commits = $this->request('https://api.github.com/repos/'.$owner.DIRECTORY_SEPARATOR.$repo.'/commits/'.$sha);
387
        dd($commits);
388
        /*
389
        foreach ($commits as $commit) {
390
            $data = [
391
                'commit_id'=>$objCommit->id,
392
                'sha'=>,
393
                'filename'=>,
394
                'status'=>,
395
                'additions'=>,
396
                'deletetions'=>,
397
                'changes'=>,
398
                'raw_url'=>,
399
                'patch'=>
400
            ];
401
        }*/
402
    }
403
404
    public function setPullRequest($owner, $repo)
405
    {
406
        ///repos/:owner/:repo/pulls
407
        $pulls = $this->request('https://api.github.com/repos/'.$owner.DIRECTORY_SEPARATOR.$repo.'/pulls');
408
        $repository = Repository::where('name', $repo)->first();
409
        $PullRequestRepository = new PullRequestRepository();
410
        foreach ($pulls as $pull) {
411
            $branch = Branch::where('name', $pull->head->ref)->first();
412
            try {
413
                $user = User::where('github_id', $pull->user->id)->first();
414
                $userId = $user->id;
415
            } catch (\Exception $e) {
416
                $userId = 0;
417
            }
418
419
            try {
420
                $headBranchId = $branch->id;
421
            } 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...
422
                $headBranchId = 0;
423
            }
424
425
            try {
426
                $branch = Branch::where('name', $pull->base->ref)->first();
427
                $baseBranchId = $branch->id;
428
            } catch (\Exception $e) {
429
                $baseBranchId = 0;
430
            }
431
432
            $data = [
433
                'github_id' => $pull->id,
434
                'number' => $pull->number,
435
                'user_id' => $userId,
436
                'product_backlog_id' => $repository->id,
437
                'url' => $pull->url,
438
                'html_url' => $pull->html_url,
439
                'issue_url' => $pull->issue_url,
440
                'commits_url' => $pull->commits_url,
441
                'state' => $pull->state,
442
                'title' => $pull->title,
443
                'body' => $pull->body,
444
                'github_created_at' => $pull->created_at,
445
                'github_updated_at' => $pull->updated_at,
446
                'head_branch_id' => $headBranchId,
447
                'base_branch_id' => $baseBranchId,
448
            ];
449
450
            $pull = $PullRequestRepository->add($data);
451
452
            $commits = $this->request('https://api.github.com/repos/'.$owner.DIRECTORY_SEPARATOR.
453
                $repo.'/pulls/'.$pull->number.'/commits');
454
            foreach ($commits as $commit) {
455
                $c = Commit::where('sha', '=', $commit->sha)->first();
456
                $pull->commit()->sync([$c->id], false);
457
            }
458
        }
459
    }
460
461
    public function getStatsCommitActivity($owner, $repo)
462
    {
463
        ///repos/:owner/:repo/stats/contributors
464
        $stats = $this->request('https://api.github.com/repos/'.$owner.DIRECTORY_SEPARATOR.
465
            $repo.'/stats/commit_activity');
466
        $arr = [];
467
        foreach ($stats as $stat) {
468
            $arr[] = $stat->total;
469
        }
470
471
        return $arr;
472
    }
473
}
474