|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
declare(strict_types=1); |
|
4
|
|
|
|
|
5
|
|
|
namespace ChangelogGenerator; |
|
6
|
|
|
|
|
7
|
|
|
use Psr\Http\Client\ClientInterface; |
|
8
|
|
|
use Psr\Http\Message\RequestFactoryInterface; |
|
9
|
|
|
use Psr\Http\Message\ResponseInterface; |
|
10
|
|
|
use RuntimeException; |
|
11
|
|
|
|
|
12
|
|
|
use function json_decode; |
|
13
|
|
|
use function preg_match; |
|
14
|
|
|
use function sprintf; |
|
15
|
|
|
|
|
16
|
|
|
class IssueClient |
|
17
|
|
|
{ |
|
18
|
|
|
private RequestFactoryInterface $messageFactory; |
|
19
|
|
|
|
|
20
|
|
|
private ClientInterface $client; |
|
21
|
|
|
|
|
22
|
4 |
|
public function __construct( |
|
23
|
|
|
RequestFactoryInterface $messageFactory, |
|
24
|
|
|
ClientInterface $client |
|
25
|
|
|
) { |
|
26
|
4 |
|
$this->messageFactory = $messageFactory; |
|
27
|
4 |
|
$this->client = $client; |
|
28
|
4 |
|
} |
|
29
|
|
|
|
|
30
|
4 |
|
public function execute( |
|
31
|
|
|
string $url, |
|
32
|
|
|
?GitHubCredentials $gitHubCredentials = null |
|
33
|
|
|
): IssueClientResponse { |
|
34
|
4 |
|
$request = $this->messageFactory |
|
35
|
4 |
|
->createRequest('GET', $url) |
|
36
|
4 |
|
->withAddedHeader('User-Agent', 'jwage/changelog-generator'); |
|
37
|
|
|
|
|
38
|
4 |
|
if ($gitHubCredentials !== null) { |
|
39
|
1 |
|
$request = $request->withAddedHeader( |
|
40
|
1 |
|
'Authorization', |
|
41
|
1 |
|
$gitHubCredentials->getAuthorizationHeader() |
|
42
|
|
|
); |
|
43
|
|
|
} |
|
44
|
|
|
|
|
45
|
4 |
|
$response = $this->client->sendRequest($request); |
|
46
|
|
|
|
|
47
|
|
|
$responseBody = $response |
|
48
|
4 |
|
->getBody() |
|
49
|
4 |
|
->__toString(); |
|
50
|
|
|
|
|
51
|
4 |
|
$body = json_decode($responseBody, true); |
|
52
|
|
|
|
|
53
|
4 |
|
$statusCode = $response->getStatusCode(); |
|
54
|
|
|
|
|
55
|
4 |
|
if ($statusCode !== 200) { |
|
56
|
1 |
|
throw new RuntimeException(sprintf( |
|
57
|
1 |
|
'API call to GitHub failed with status code %d%s', |
|
58
|
1 |
|
$statusCode, |
|
59
|
1 |
|
isset($body['message']) ? sprintf(' and message "%s"', $body['message']) : '' |
|
60
|
|
|
)); |
|
61
|
|
|
} |
|
62
|
|
|
|
|
63
|
3 |
|
return new IssueClientResponse($body, $this->getNextUrl($response)); |
|
64
|
|
|
} |
|
65
|
|
|
|
|
66
|
3 |
|
private function getNextUrl(ResponseInterface $response): ?string |
|
67
|
|
|
{ |
|
68
|
3 |
|
$links = $response->getHeader('Link'); |
|
69
|
|
|
|
|
70
|
3 |
|
foreach ($links as $link) { |
|
71
|
1 |
|
$matches = []; |
|
72
|
|
|
|
|
73
|
1 |
|
if (preg_match('#<(?P<url>.*)>; rel="next"#', $link, $matches) === 1) { |
|
74
|
1 |
|
return $matches['url']; |
|
75
|
|
|
} |
|
76
|
|
|
} |
|
77
|
|
|
|
|
78
|
2 |
|
return null; |
|
79
|
|
|
} |
|
80
|
|
|
} |
|
81
|
|
|
|