Completed
Push — master ( 2ee5bc...295d99 )
by Greg
01:21
created

HubphAPI::prStatuses()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 26

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 26
rs 9.504
c 0
b 0
f 0
cc 3
nc 4
nop 2
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[$pullRequest['id']] = $pullRequest['head']['sha'];
89
        }
90
91
        // Merge all of the pull requests
92
        foreach ($shas as $id => $sha) {
93
            $response = $this->gitHubAPI()->api('pull_request')->merge($org, $project, $id, $message, $sha, $mergeMethod, $title);
94
            $this->logEvent(__FUNCTION__, [$org, $project], [$id, $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
        $projectAndOrg = $this->projectAndOrgFromUrl($url);
159
        return "https://{$token}:[email protected]/{$projectAndOrg}.git";
160
    }
161
162 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...
163
    {
164
        $remote = preg_replace('#^git@[^:]*:#', '', $remote);
165
        $remote = preg_replace('#^[^:]*://[^/]*/#', '', $remote);
166
        $remote = preg_replace('#\.git$#', '', $remote);
167
168
        return $remote;
169
    }
170
171
    protected function existingPRs($projectWithOrg, VersionIdentifiers $vids)
172
    {
173
        $preamble = $vids->getPreamble();
174
        $q = "repo:$projectWithOrg in:title is:pr state:open $preamble";
175
        $result = new PullRequests();
176
        $gitHubAPI = $this->gitHubAPI();
177
        $searchResults = $gitHubAPI->api('search')->issues($q);
178
        $result->addSearchResults($searchResults, $vids->pattern());
179
180
        return $result;
181
    }
182
183
    public function allPRs($projectWithOrg)
184
    {
185
        $q = "repo:$projectWithOrg in:title is:pr state:open";
186
        $result = new PullRequests();
187
        $searchResults = $this->gitHubAPI()->api('search')->issues($q);
188
        $result->addSearchResults($searchResults);
189
190
        return $result;
191
    }
192
193
    /**
194
     * Pass an event of note to the event logger
195
     * @param string $event_name
196
     * @param array $args
197
     * @param array $params
198
     * @param array $response
199
     */
200
    protected function logEvent($event_name, $args, $params, $response)
201
    {
202
        if ($this->eventLogger) {
203
            $this->eventLogger->log($event_name, $args, $params, $response);
204
        }
205
    }
206
207
    /**
208
     * Authenticate and then return the gitHub API object.
209
     */
210
    public function gitHubAPI()
211
    {
212
        if (!$this->gitHubAPI) {
213
            $token = $this->gitHubToken();
214
215
            $this->gitHubAPI = new \Github\Client();
216
            $this->gitHubAPI->authenticate($token, null, \Github\Client::AUTH_HTTP_TOKEN);
217
        }
218
        return $this->gitHubAPI;
219
    }
220
221
    /**
222
     * Look up the GitHub token set either via environment variable or in the
223
     * auth-token cache directory.
224
     */
225
    public function gitHubToken()
226
    {
227
        if (!$this->token) {
228
            $this->token = $this->getGitHubToken();
229
        }
230
        return $this->token;
231
    }
232
233
    protected function getGitHubToken()
234
    {
235
        $as = $this->as;
236
        $token = null;
237
        if ($as == 'default') {
238
            $as = $this->getConfig()->get("github.default-user");
239
        }
240
241
        // First preference: There is a 'path' component in preferences
242
        // pointing to a file containing the token.
243
        $github_token_cache = $this->getConfig()->get("github.personal-auth-token.$as.path");
244
        if (file_exists($github_token_cache)) {
245
            $token = trim(file_get_contents($github_token_cache));
246
        }
247
248
        // Second preference: There is an environment variable that begins
249
        // with an uppercased version of the 'as' string followed by '_TOKEN'
250
        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...
251
            $env_name = strtoupper(str_replace('-', '_', $as)) . '_TOKEN';
252
            $token = getenv($env_name);
253
        }
254
255
        // If we read in a token from one of the preferred locations, then
256
        // set the GITHUB_TOKEN environment variable and return it.
257
        if ($token) {
258
            putenv("GITHUB_TOKEN=$token");
259
            return $token;
260
        }
261
262
        // Fallback: authenticate to whatever 'GITHUB_TOKEN' is already set to.
263
        return getenv('GITHUB_TOKEN');
264
    }
265
266
    protected function getConfig()
267
    {
268
        return $this->config;
269
    }
270
}
271