Completed
Push — master ( 7bb5f9...d11323 )
by Greg
08:31
created

HubphAPI::resultPager()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 0
1
<?php
2
3
namespace Hubph;
4
5
use Consolidation\Config\ConfigInterface;
6
use Hubph\Internal\EventLogger;
7
8
class HubphAPI
9
{
10
    protected $config;
11
    protected $token;
12
    protected $gitHubAPI;
13
    protected $eventLogger;
14
    protected $as = 'default';
15
16
    /**
17
     * HubphAPI constructor
18
     */
19
    public function __construct(ConfigInterface $config)
20
    {
21
        $this->config = $config;
22
    }
23
24
    public function startLogging($filename)
25
    {
26
        $this->stopLogging();
27
        $this->eventLogger = new EventLogger($filename);
28
        $this->eventLogger->start();
29
    }
30
31
    public function stopLogging()
32
    {
33
        if ($this->eventLogger) {
34
            $this->eventLogger->stop();
35
        }
36
        $this->eventLogger = null;
37
    }
38
39
    public function setAs($as)
40
    {
41
        if ($as != $this->as) {
42
            $this->as = $as;
43
            $this->token = false;
44
            $this->gitHubAPI = false;
45
        }
46
    }
47
48
    public function whoami()
49
    {
50
        $gitHubAPI = $this->gitHubAPI();
51
        $authenticated = $gitHubAPI->api('current_user')->show();
52
        return $authenticated;
53
    }
54
55
    public function prCreate($org, $project, $title, $body, $base, $head)
56
    {
57
        $params = [
58
            'title' => $title,
59
            'body' => $body,
60
            'base' => $base,
61
            'head' => $head,
62
        ];
63
        $response = $this->gitHubAPI()->api('pull_request')->create($org, $project, $params);
64
        $this->logEvent(__FUNCTION__, [$org, $project], $params, $response);
65
        return $this;
66
    }
67
68
    public function prClose($org, $project, PullRequests $prs)
69
    {
70
        foreach ($prs->prNumbers() as $n) {
71
            $gitHubAPI = $this->gitHubAPI();
72
            $gitHubAPI->api('pull_request')->update($org, $project, $n, ['state' => 'closed']);
73
        }
74
    }
75
76
    public function prMerge($org, $project, PullRequests $prs, $message, $mergeMethod = 'squash', $title = null)
77
    {
78
        // First, check to see if all of the pull requests can be merged,
79
        // and collect the sha hash of the head of the branch.
80
        $allClean = true;
0 ignored issues
show
Unused Code introduced by
$allClean 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...
81
        $shas = [];
82
        foreach ($prs->prNumbers() as $n) {
83
            $pullRequest = $this->gitHubAPI()->api('pull_request')->show($org, $project, $n);
84
            $is_clean = $pullRequest['mergeable'] && $pullRequest['mergeable_state'] == 'clean';
85
            if (!$is_clean) {
86
                return false;
87
            }
88
            $shas[$n] = $pullRequest['head']['sha'];
89
        }
90
91
        // Merge all of the pull requests
92
        foreach ($shas as $n => $sha) {
93
            $response = $this->gitHubAPI()->api('pull_request')->merge($org, $project, $n, $message, $sha, $mergeMethod, $title);
94
            $this->logEvent(__FUNCTION__, [$org, $project], [$n, $message, $sha, $mergeMethod, $title], $response);
95
        }
96
        return true;
97
    }
98
99
    /**
100
     * prCheck determines whether there are any open PRs that already exist
101
     * that satisfy any of the provided $vids.
102
     *
103
     * @param string $projectWithOrg org/project to check
104
     * @param VersionIdentifiers $vids
105
     * @return [int $status, PullRequests $prs] status of PRs, and a list of PR numbers
0 ignored issues
show
Documentation introduced by
The doc-type int">[int could not be parsed: Unknown type name "[" at position 0. [(view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
106
     *   - If $status is 0, then the caller should go ahead and create a new PR.
107
     *     The existing pull requests that would be superceded by the new PR are
108
     *     returned in the second parameter. These PRs could all be closed.
109
     *   - If $status is >0, then there is no need to create a new PR, as there
110
     *     are already existing PRs that are equivalent to the one that would
111
     *     be open. The equivalent PRs are returned in the second parameter.
112
     */
113
    public function prCheck($projectWithOrg, VersionIdentifiers $vids)
114
    {
115
        // Find all of the PRs that contain any vid
116
        $existingPRs = $this->existingPRs($projectWithOrg, $vids);
117
118
        // Check to see if there are PRs matching all of the vids/vvals.
119
        $titles = $existingPRs->titles();
120
        $status = $vids->allExist($titles);
121
122
        return [$status, $existingPRs];
123
    }
124
125
    public function prStatuses($projectWithOrg, $number)
126
    {
127
        list($org, $project) = explode('/', $projectWithOrg, 2);
128
        $pullRequestStatus = $this->gitHubAPI()->api('pull_request')->status($org, $project, $number);
129
130
        // Filter out the results based on 'target_url'
131
        $filteredResults = [];
132
        foreach (array_reverse($pullRequestStatus) as $id => $item) {
133
            $filteredResults[$item['target_url']] = $item;
134
        }
135
        $pullRequestStatus = [];
136
        foreach ($filteredResults as $target_url => $item) {
137
            $pullRequestStatus[$item['id']] = $item;
138
        }
139
140
        // Put the most recently updated statuses at the top of the list
141
        uasort(
142
143
            $pullRequestStatus,
144
            function ($lhs, $rhs) {
145
                return abs(strtotime($lhs['updated_at']) - strtotime($rhs['updated_at']));
146
            }
147
        );
148
149
        return $pullRequestStatus;
150
    }
151
152
    public function addTokenAuthentication($url)
153
    {
154
        $token = $this->gitHubToken();
155
        if (!$token) {
156
            return $url;
157
        }
158
        if (!preg_match('#github\.com[/:]#', $url)) {
159
            return $url;
160
        }
161
        $projectAndOrg = $this->projectAndOrgFromUrl($url);
162
        return "https://{$token}:[email protected]/{$projectAndOrg}.git";
163
    }
164
165 View Code Duplication
    protected function projectAndOrgFromUrl($remote)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
166
    {
167
        $remote = preg_replace('#^git@[^:]*:#', '', $remote);
168
        $remote = preg_replace('#^[^:]*://[^/]*/#', '', $remote);
169
        $remote = preg_replace('#\.git$#', '', $remote);
170
171
        return $remote;
172
    }
173
174
    protected function existingPRs($projectWithOrg, VersionIdentifiers $vids)
175
    {
176
        return $this->matchingPRs($projectWithOrg, $vids->getPreamble(), $vids->pattern());
177
    }
178
179
    public function matchingPRs($projectWithOrg, $preamble, $pattern = '')
180
    {
181
        $q = "repo:$projectWithOrg in:title is:pr state:open $preamble";
182
        $result = new PullRequests();
183
        $gitHubAPI = $this->gitHubAPI();
184
        $searchResults = $gitHubAPI->api('search')->issues($q);
185
        $result->addSearchResults($searchResults, $pattern);
186
187
        return $result;
188
    }
189
190
    public function allPRs($projectWithOrg)
191
    {
192
        $q = "repo:$projectWithOrg in:title is:pr state:open";
193
        $result = new PullRequests();
194
        $searchResults = $this->gitHubAPI()->api('search')->issues($q);
195
        $result->addSearchResults($searchResults);
196
197
        return $result;
198
    }
199
200
    /**
201
     * Pass an event of note to the event logger
202
     * @param string $event_name
203
     * @param array $args
204
     * @param array $params
205
     * @param array $response
206
     */
207
    protected function logEvent($event_name, $args, $params, $response)
208
    {
209
        if ($this->eventLogger) {
210
            $this->eventLogger->log($event_name, $args, $params, $response);
211
        }
212
    }
213
214
    /**
215
     * Authenticate and then return the gitHub API object.
216
     */
217
    public function gitHubAPI()
218
    {
219
        if (!$this->gitHubAPI) {
220
            $token = $this->gitHubToken();
221
222
            $this->gitHubAPI = new \Github\Client();
223
            $this->gitHubAPI->authenticate($token, null, \Github\Client::AUTH_HTTP_TOKEN);
224
        }
225
        return $this->gitHubAPI;
226
    }
227
228
    /**
229
     * Return a result pager object using our cached GitHub API client.
230
     */
231
    public function resultPager()
232
    {
233
        return new \Github\ResultPager($this->gitHubAPI());
234
    }
235
236
    /**
237
     * Look up the GitHub token set either via environment variable or in the
238
     * auth-token cache directory.
239
     */
240
    public function gitHubToken()
241
    {
242
        if (!$this->token) {
243
            $this->token = $this->getGitHubToken();
244
        }
245
        return $this->token;
246
    }
247
248
    protected function getGitHubToken()
249
    {
250
        $as = $this->as;
251
        $token = null;
252
        if ($as == 'default') {
253
            $as = $this->getConfig()->get("github.default-user");
254
        }
255
256
        // First preference: There is a 'path' component in preferences
257
        // pointing to a file containing the token.
258
        $github_token_cache = $this->getConfig()->get("github.personal-auth-token.$as.path");
259
        if (file_exists($github_token_cache)) {
260
            $token = trim(file_get_contents($github_token_cache));
261
        }
262
263
        // Second preference: There is an environment variable that begins
264
        // with an uppercased version of the 'as' string followed by '_TOKEN'
265
        if (!$token) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $token of type string|null is loosely compared to false; this is ambiguous if the string can be empty. You might want to explicitly use === null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
266
            $env_name = strtoupper(str_replace('-', '_', $as)) . '_TOKEN';
267
            $token = getenv($env_name);
268
        }
269
270
        // If we read in a token from one of the preferred locations, then
271
        // set the GITHUB_TOKEN environment variable and return it.
272
        if ($token) {
273
            putenv("GITHUB_TOKEN=$token");
274
            return $token;
275
        }
276
277
        // Fallback: authenticate to whatever 'GITHUB_TOKEN' is already set to.
278
        return getenv('GITHUB_TOKEN');
279
    }
280
281
    protected function getConfig()
282
    {
283
        return $this->config;
284
    }
285
}
286