diff --git a/Tests/GithubObjectTest.php b/Tests/GithubObjectTest.php index de9d5129..2e01d27c 100755 --- a/Tests/GithubObjectTest.php +++ b/Tests/GithubObjectTest.php @@ -7,8 +7,12 @@ namespace Joomla\Github\Tests; +use Joomla\Github\Github; use Joomla\Github\Tests\Stub\GitHubTestCase; use Joomla\Github\Tests\Stub\ObjectMock; +use Joomla\Github\Tests\Stub\RecordingTransport; +use Joomla\Http\Http; +use Joomla\Registry\Registry; use PHPUnit\Framework\Attributes\DataProvider; /** @@ -105,11 +109,9 @@ public function testFetchUrl($apiUrl, $path, $page, $limit, $expected) } /** - * Tests the fetchUrl method with basic authentication data + * Tests that fetchUrl() does not put Basic auth credentials into the URL * * @return void - * - * @since 1.0 */ public function testFetchUrlBasicAuth() { @@ -119,12 +121,24 @@ public function testFetchUrlBasicAuth() $this->options->set('api.password', 'MyTestPass'); $this->assertThat( - $this->object->fetchUrl('/gists', 0, 0), - $this->equalTo('https://MyTestUser:MyTestPass@api.github.com/gists'), + (string) $this->object->fetchUrl('/gists', 0, 0), + $this->equalTo('https://api.github.com/gists'), 'URL is not as expected.' ); } + /** + * Tests that fetchUrl() uses api.github.com when the api.url option is not set + * + * @return void + */ + public function testFetchUrlDefaultApiUrl() + { + $object = new ObjectMock(new Registry(), $this->client); + + $this->assertSame('https://api.github.com/user', (string) $object->fetchUrl('/user')); + } + /** * Tests the fetchUrl method using an oAuth token. * @@ -142,4 +156,179 @@ public function testFetchUrlToken() 'URL is not as expected.' ); } + + /** + * Tests that the token is sent with each request and read again for every request + * + * @return void + */ + public function testTokenIsSentPerRequestAndCanBeRotated() + { + $transport = new RecordingTransport(); + $object = new ObjectMock($this->options, new Http([], $transport)); + + $this->options->set('gh.token', 'AAA'); + $object->request('/user'); + + $this->options->set('gh.token', 'BBB'); + $object->request('/user'); + + $this->assertSame('token AAA', $transport->requests[0]['headers']['Authorization']); + $this->assertSame('token BBB', $transport->requests[1]['headers']['Authorization']); + } + + /** + * Tests that the GitHub headers are not left on a shared HTTP client + * + * @return void + */ + public function testHeadersAreNotStoredOnTheClient() + { + $transport = new RecordingTransport(); + $client = new Http([], $transport); + $object = new ObjectMock($this->options, $client); + + $this->options->set('gh.token', 'MyTestToken'); + $object->request('/user'); + + $this->assertNull($client->getOption('headers')); + + // Another request through the same client, e.g. to a different host, does not carry the token + $client->get('https://example.com/'); + + $this->assertSame('token MyTestToken', $transport->requests[0]['headers']['Authorization']); + $this->assertArrayNotHasKey('Authorization', $transport->requests[1]['headers']); + } + + /** + * Tests that the GitHub headers are not written into an options registry the client was built from + * + * @return void + */ + public function testHeadersAreNotStoredInTheOptions() + { + $transport = new RecordingTransport(); + $object = new ObjectMock($this->options, new Http($this->options, $transport)); + + $this->options->set('gh.token', 'MyTestToken'); + $object->request('/user'); + + $this->assertSame('token MyTestToken', $transport->requests[0]['headers']['Authorization']); + $this->assertNull($this->options->get('headers')); + } + + /** + * Tests the default media type and API version headers and the api.version and gh.token_scheme options + * + * @return void + */ + public function testDefaultHeadersAndOptions() + { + $transport = new RecordingTransport(); + $object = new ObjectMock($this->options, new Http([], $transport)); + + $object->request('/zen'); + + $this->options->set('api.version', '2026-03-10'); + $this->options->set('gh.token', 'MyTestToken'); + $this->options->set('gh.token_scheme', 'Bearer'); + $object->request('/zen'); + + $this->assertSame( + ['Accept' => 'application/vnd.github+json', 'X-GitHub-Api-Version' => '2022-11-28'], + $transport->requests[0]['headers'] + ); + $this->assertSame( + [ + 'Accept' => 'application/vnd.github+json', + 'X-GitHub-Api-Version' => '2026-03-10', + 'Authorization' => 'Bearer MyTestToken', + ], + $transport->requests[1]['headers'] + ); + } + + /** + * Tests that headers set on the client take precedence and are left as they were + * + * @return void + */ + public function testClientHeadersTakePrecedence() + { + $transport = new RecordingTransport(); + $client = new Http( + ['headers' => ['authorization' => 'token Custom', 'Accept' => 'application/vnd.github.raw+json']], + $transport + ); + $object = new ObjectMock($this->options, $client); + + $this->options->set('gh.token', 'MyTestToken'); + $object->request('/user'); + + $headers = $transport->requests[0]['headers']; + + $this->assertSame('token Custom', $headers['authorization']); + $this->assertArrayNotHasKey('Authorization', $headers); + $this->assertSame('application/vnd.github.raw+json', $headers['Accept']); + $this->assertSame( + ['authorization' => 'token Custom', 'Accept' => 'application/vnd.github.raw+json'], + $client->getOption('headers') + ); + } + + /** + * Tests that Basic auth credentials are sent in the Authorization header, not in the URL + * + * @return void + */ + public function testBasicAuthIsSentAsHeader() + { + $transport = new RecordingTransport(); + $object = new ObjectMock($this->options, new Http([], $transport)); + + $this->options->set('api.url', 'https://api.github.com'); + $this->options->set('api.username', 'bob'); + $this->options->set('api.password', 'p@ss:w/rd'); + $object->request('/user'); + + $this->assertSame('https://api.github.com/user', $transport->requests[0]['uri']); + $this->assertSame('Basic ' . base64_encode('bob:p@ss:w/rd'), $transport->requests[0]['headers']['Authorization']); + } + + /** + * Tests that sub-packages send the headers once + * + * @return void + */ + public function testSubPackagesSendTheHeaders() + { + $transport = new RecordingTransport(); + $options = new Registry(); + $options->set('gh.token', 'MyTestToken'); + + $github = new Github($options, new Http([], $transport)); + $github->repositories->forks->getList('joomla', 'joomla-framework'); + + $this->assertSame('https://api.github.com/repos/joomla/joomla-framework/forks', $transport->requests[0]['uri']); + $this->assertSame('token MyTestToken', $transport->requests[0]['headers']['Authorization']); + } + + /** + * Tests that a JSON body is sent as application/json, and a form body keeps the transport's content type + * + * @return void + */ + public function testJsonBodyContentType() + { + $transport = new RecordingTransport(); + $client = new Http([], $transport); + $github = new Github($this->options, $client); + + $github->markdown->render('Hello'); + $github->authorization->requestToken('{id}', '{secret}', '{code}', '', 'json'); + + $this->assertSame('application/json', $transport->requests[0]['headers']['Content-Type']); + $this->assertArrayNotHasKey('Content-Type', $transport->requests[1]['headers']); + $this->assertNull($client->getOption('headers')); + } } diff --git a/Tests/Package/AuthorizationsTest.php b/Tests/Package/AuthorizationsTest.php index f5746fc5..93d4c19b 100644 --- a/Tests/Package/AuthorizationsTest.php +++ b/Tests/Package/AuthorizationsTest.php @@ -9,6 +9,7 @@ use Joomla\Github\Package\Authorization; use Joomla\Github\Tests\Stub\GitHubTestCase; +use PHPUnit\Framework\Attributes\IgnoreDeprecations; /** * Test class for Authorization. @@ -430,8 +431,11 @@ public function testGetGrantFailure() * * @since 1.0 */ + #[IgnoreDeprecations] public function testGetList() { + $this->expectUserDeprecationMessageMatches('/' . preg_quote('Joomla\Github\Package\Authorization::getList() is deprecated and will be removed in 5.0', '/') . '/'); + $this->client->expects($this->once()) ->method('get') ->with('/authorizations') diff --git a/Tests/Package/Repositories/DownloadsTest.php b/Tests/Package/Repositories/DownloadsTest.php index 189a7c5d..ae60def3 100644 --- a/Tests/Package/Repositories/DownloadsTest.php +++ b/Tests/Package/Repositories/DownloadsTest.php @@ -9,6 +9,7 @@ use Joomla\Github\Package\Repositories\Downloads; use Joomla\Github\Tests\Stub\GitHubTestCase; +use PHPUnit\Framework\Attributes\IgnoreDeprecations; /** * Test class for Downloads. @@ -42,8 +43,11 @@ protected function setUp(): void * * @return void */ + #[IgnoreDeprecations] public function testGetList() { + $this->expectUserDeprecationMessageMatches('/' . preg_quote('Joomla\Github\Package\Repositories\Downloads::getList() is deprecated and will be removed in 5.0', '/') . '/'); + $this->client->expects($this->once()) ->method('get') ->with('/repos/joomla/joomla-platform/downloads') diff --git a/Tests/Stub/GitHubTestCase.php b/Tests/Stub/GitHubTestCase.php index e0eba3de..e25ce04b 100644 --- a/Tests/Stub/GitHubTestCase.php +++ b/Tests/Stub/GitHubTestCase.php @@ -62,6 +62,9 @@ protected function setUp(): void $this->options = new Registry(); + // An empty API URL keeps the request paths relative, so the tests can assert on the path alone. + $this->options->set('api.url', ''); + $this->client = $this->createMock(Http::class); $this->response = $this->getResponseObject($this->sampleString); diff --git a/Tests/Stub/ObjectMock.php b/Tests/Stub/ObjectMock.php index fe40373e..ead50961 100644 --- a/Tests/Stub/ObjectMock.php +++ b/Tests/Stub/ObjectMock.php @@ -33,5 +33,17 @@ public function fetchUrl($path, $page = 0, $limit = 0) { return parent::fetchUrl($path, $page, $limit); } + + /** + * Send a GET request for the given path. + * + * @param string $path The API path. + * + * @return mixed + */ + public function request($path) + { + return $this->processResponse($this->client->get($this->fetchUrl($path))); + } // @codingStandardsIgnoreEnd } diff --git a/Tests/Stub/RecordingTransport.php b/Tests/Stub/RecordingTransport.php new file mode 100644 index 00000000..4a4122c4 --- /dev/null +++ b/Tests/Stub/RecordingTransport.php @@ -0,0 +1,42 @@ +requests[] = [ + 'method' => $method, + 'uri' => (string) $uri, + 'data' => $data, + 'headers' => $headers, + ]; + + return new Response('data://text/plain,[]', 200, []); + } + + public static function isSupported() + { + return true; + } +} diff --git a/composer.json b/composer.json index 49ad2e0a..d44c9b57 100644 --- a/composer.json +++ b/composer.json @@ -9,7 +9,8 @@ "php": "^8.3.0", "joomla/http": "^4.0", "joomla/registry": "^4.0", - "joomla/uri": "^4.0" + "joomla/uri": "^4.0", + "symfony/deprecation-contracts": "^2|^3" }, "require-dev": { "phpunit/phpunit": "^12.2.7", diff --git a/docs/overview.md b/docs/overview.md index cfd53634..ff208c00 100644 --- a/docs/overview.md +++ b/docs/overview.md @@ -1,3 +1,42 @@ # Github API package TODO + +## Authentication and request headers + +The options are read on every request, so a changed token is used from the next request on. The headers are added +to each request only; they are not stored on the HTTP client, so a client shared with other code never sends the +GitHub credentials elsewhere. + +| Option | Default | Meaning | +|---|---|---| +| `api.url` | `https://api.github.com` | API root; for GitHub Enterprise Server `https:///api/v3` | +| `api.version` | `2022-11-28` | Sent as `X-GitHub-Api-Version` | +| `gh.token` | | Token sent as `Authorization: token ` | +| `gh.token_scheme` | `token` | Scheme of the `Authorization` header, e.g. `Bearer` for GitHub App tokens | +| `api.username`, `api.password` | | Sent as `Authorization: Basic` when no token is set (GitHub Enterprise Server only) | + +```php +$options = new Registry(); +$options->set('gh.token', getenv('GITHUB_TOKEN')); +$options->set('gh.token_scheme', 'Bearer'); + +$github = new Github($options); +``` + +Every request also sends `Accept: application/vnd.github+json`, and a JSON request body is sent with +`Content-Type: application/json`. A header set on the HTTP client (its `headers` option) or passed with a request +takes precedence over these defaults. + +GitHub removed password authentication for the API in November 2020; `api.username` and `api.password` only work +against GitHub Enterprise Server instances that still accept it. They are sent in the `Authorization` header, not in +the URL. + +## Deprecated endpoints + +GitHub has removed some of the endpoints this package wraps. Calling these methods triggers a deprecation notice; +they will be removed in 5.0. + +* `Authorization`: everything except `getRateLimit()`, `getAuthorizationLink()` and `requestToken()` (the OAuth + Authorizations API). Use a token (`gh.token`) instead. +* `Repositories\Downloads`: the whole class. Use `Repositories\Releases` and its assets instead. diff --git a/src/AbstractGithubObject.php b/src/AbstractGithubObject.php index 70fdbaa6..c2ab186e 100644 --- a/src/AbstractGithubObject.php +++ b/src/AbstractGithubObject.php @@ -93,6 +93,9 @@ public function __construct(Registry $options = null, BaseHttp $client = null) $this->options = $options ?: new Registry(); $this->client = $client ?: (new HttpFactory())->getHttp($this->options); + // Add the GitHub headers per request instead of storing them on the (possibly shared) client. + $this->client = new RequestHeadersHttp($this->client, fn (): array => $this->getRequestHeaders()); + $this->package = \get_class($this); $this->package = substr($this->package, strrpos($this->package, '\\') + 1); } @@ -102,6 +105,8 @@ public function __construct(Registry $options = null, BaseHttp $client = null) * add appropriate pagination details if necessary and also prepend the API url * to have a complete URL for the request. * + * When the `api.url` option is not set, `https://api.github.com` is used. + * * @param string $path URL to inflect * @param integer $page Page to request * @param integer $limit Number of results to return per page @@ -113,26 +118,8 @@ public function __construct(Registry $options = null, BaseHttp $client = null) protected function fetchUrl($path, $page = 0, $limit = 0) { // Get a new Uri object focusing the api url and given path. - $uri = new Uri($this->options->get('api.url') . $path); - - if ($this->options->get('gh.token', false)) { - // Use oAuth authentication - $headers = $this->client->getOption('headers', []); - - if (!isset($headers['Authorization'])) { - $headers['Authorization'] = 'token ' . $this->options->get('gh.token'); - $this->client->setOption('headers', $headers); - } - } else { - // Use basic authentication - if ($this->options->get('api.username', false)) { - $uri->setUser($this->options->get('api.username')); - } - - if ($this->options->get('api.password', false)) { - $uri->setPass($this->options->get('api.password')); - } - } + $apiUrl = $this->options->exists('api.url') ? $this->options->get('api.url', '') : 'https://api.github.com'; + $uri = new Uri($apiUrl . $path); // If we have a defined page number add it to the JUri object. if ($page > 0) { @@ -147,6 +134,40 @@ protected function fetchUrl($path, $page = 0, $limit = 0) return $uri; } + /** + * Get the headers to send with each request. + * + * The options are read on every request, so a changed token is used on the next request. The headers are added + * to the request only; headers set on the HTTP client or passed with a request take precedence. + * + * - `Accept: application/vnd.github+json` + * - `X-GitHub-Api-Version`, set with the `api.version` option (default `2022-11-28`) + * - `Authorization: token `; the scheme can be changed with the `gh.token_scheme` option, e.g. to `Bearer` + * - Without a token, `Authorization: Basic` from the `api.username` and `api.password` options. GitHub removed + * password authentication for the API in November 2020; it is kept only for GitHub Enterprise Server. + * + * @return array + * + * @since __DEPLOY_VERSION__ + */ + protected function getRequestHeaders(): array + { + $headers = [ + 'Accept' => 'application/vnd.github+json', + 'X-GitHub-Api-Version' => (string) $this->options->get('api.version', '2022-11-28'), + ]; + + if ($this->options->get('gh.token', false)) { + $headers['Authorization'] = $this->options->get('gh.token_scheme', 'token') . ' ' . $this->options->get('gh.token'); + } elseif ($this->options->get('api.username', false)) { + $headers['Authorization'] = 'Basic ' . base64_encode( + $this->options->get('api.username') . ':' . $this->options->get('api.password', '') + ); + } + + return $headers; + } + /** * Process the response and decode it. * diff --git a/src/Package/Authorization.php b/src/Package/Authorization.php index bf3317e4..7c98341a 100644 --- a/src/Package/Authorization.php +++ b/src/Package/Authorization.php @@ -19,7 +19,8 @@ * @documentation http://developer.github.com/v3/oauth/ * @documentation http://developer.github.com/v3/oauth_authorizations/ * - * @note The methods in this class are only accessible with Basic Authentication + * @note GitHub has removed the OAuth Authorizations API and password authentication for the API. Only + * getRateLimit(), getAuthorizationLink() and requestToken() still work; the other methods are deprecated. * @since 1.0 */ class Authorization extends AbstractPackage @@ -35,9 +36,17 @@ class Authorization extends AbstractPackage * * @since 1.0 * @throws \DomainException + * @deprecated 5.0 GitHub has removed the OAuth Authorizations API. Use a token (gh.token) instead. */ public function create(array $scopes = [], $note = '', $url = '') { + trigger_deprecation( + 'joomla/github', + '__DEPLOY_VERSION__', + '%s() is deprecated and will be removed in 5.0, GitHub has removed the OAuth Authorizations API. Use a token (gh.token) instead.', + __METHOD__ + ); + // Build the request path. $path = '/authorizations'; @@ -58,9 +67,17 @@ public function create(array $scopes = [], $note = '', $url = '') * * @since 1.0 * @throws \DomainException + * @deprecated 5.0 GitHub has removed the OAuth Authorizations API. Use a token (gh.token) instead. */ public function delete($id) { + trigger_deprecation( + 'joomla/github', + '__DEPLOY_VERSION__', + '%s() is deprecated and will be removed in 5.0, GitHub has removed the OAuth Authorizations API. Use a token (gh.token) instead.', + __METHOD__ + ); + // Build the request path. $path = '/authorizations/' . $id; @@ -79,9 +96,17 @@ public function delete($id) * * @since 1.5.0 * @throws \DomainException + * @deprecated 5.0 GitHub has removed the OAuth Authorizations API. Use a token (gh.token) instead. */ public function deleteGrant($id) { + trigger_deprecation( + 'joomla/github', + '__DEPLOY_VERSION__', + '%s() is deprecated and will be removed in 5.0, GitHub has removed the OAuth Authorizations API. Use a token (gh.token) instead.', + __METHOD__ + ); + // Build the request path. $path = '/authorizations/grants/' . $id; @@ -104,9 +129,17 @@ public function deleteGrant($id) * @since 1.0 * @throws \DomainException * @throws \RuntimeException + * @deprecated 5.0 GitHub has removed the OAuth Authorizations API. Use a token (gh.token) instead. */ public function edit($id, array $scopes = [], array $addScopes = [], array $removeScopes = [], $note = '', $url = '') { + trigger_deprecation( + 'joomla/github', + '__DEPLOY_VERSION__', + '%s() is deprecated and will be removed in 5.0, GitHub has removed the OAuth Authorizations API. Use a token (gh.token) instead.', + __METHOD__ + ); + // Check if more than one scopes array contains data $scopesCount = 0; $scope = ''; @@ -159,9 +192,17 @@ public function edit($id, array $scopes = [], array $addScopes = [], array $remo * * @since 1.0 * @throws \DomainException + * @deprecated 5.0 GitHub has removed the OAuth Authorizations API. Use a token (gh.token) instead. */ public function get($id) { + trigger_deprecation( + 'joomla/github', + '__DEPLOY_VERSION__', + '%s() is deprecated and will be removed in 5.0, GitHub has removed the OAuth Authorizations API. Use a token (gh.token) instead.', + __METHOD__ + ); + // Build the request path. $path = '/authorizations/' . $id; @@ -178,9 +219,17 @@ public function get($id) * * @since 1.5.0 * @throws \DomainException + * @deprecated 5.0 GitHub has removed the OAuth Authorizations API. Use a token (gh.token) instead. */ public function getGrant($id) { + trigger_deprecation( + 'joomla/github', + '__DEPLOY_VERSION__', + '%s() is deprecated and will be removed in 5.0, GitHub has removed the OAuth Authorizations API. Use a token (gh.token) instead.', + __METHOD__ + ); + // Build the request path. $path = '/authorizations/grants/' . $id; @@ -195,9 +244,17 @@ public function getGrant($id) * * @since 1.0 * @throws \DomainException + * @deprecated 5.0 GitHub has removed the OAuth Authorizations API. Use a token (gh.token) instead. */ public function getList() { + trigger_deprecation( + 'joomla/github', + '__DEPLOY_VERSION__', + '%s() is deprecated and will be removed in 5.0, GitHub has removed the OAuth Authorizations API. Use a token (gh.token) instead.', + __METHOD__ + ); + // Build the request path. $path = '/authorizations'; @@ -214,9 +271,17 @@ public function getList() * * @since 1.5.0 * @throws \DomainException + * @deprecated 5.0 GitHub has removed the OAuth Authorizations API. Use a token (gh.token) instead. */ public function getListGrants() { + trigger_deprecation( + 'joomla/github', + '__DEPLOY_VERSION__', + '%s() is deprecated and will be removed in 5.0, GitHub has removed the OAuth Authorizations API. Use a token (gh.token) instead.', + __METHOD__ + ); + // Build the request path. $path = '/authorizations/grants'; @@ -358,9 +423,17 @@ public function requestToken($clientId, $clientSecret, $code, $redirectUri = '', * * @since 1.5.0 * @throws \DomainException + * @deprecated 5.0 GitHub has removed this endpoint. Use DELETE /applications/{client_id}/grant instead. */ public function revokeGrantForApplication($clientId, $accessToken) { + trigger_deprecation( + 'joomla/github', + '__DEPLOY_VERSION__', + '%s() is deprecated and will be removed in 5.0, GitHub has removed this endpoint. Use DELETE /applications/{client_id}/grant instead.', + __METHOD__ + ); + // Build the request path. $path = "/applications/$clientId/grants/$accessToken"; diff --git a/src/Package/Repositories/Downloads.php b/src/Package/Repositories/Downloads.php index 4e23ea1a..c522e59e 100644 --- a/src/Package/Repositories/Downloads.php +++ b/src/Package/Repositories/Downloads.php @@ -21,7 +21,7 @@ * @documentation https://developer.github.com/v3/repos/downloads * * @since 1.0 - * @deprecated The Releases API should be used instead + * @deprecated 5.0 GitHub has removed the Downloads API. Use the Releases API instead. */ class Downloads extends AbstractPackage { @@ -34,10 +34,17 @@ class Downloads extends AbstractPackage * @return object * * @since 1.0 - * @deprecated The Releases API should be used instead + * @deprecated 5.0 GitHub has removed the Downloads API. Use the Releases API instead. */ public function getList($owner, $repo) { + trigger_deprecation( + 'joomla/github', + '__DEPLOY_VERSION__', + '%s() is deprecated and will be removed in 5.0, GitHub has removed the Downloads API. Use the Releases API instead.', + __METHOD__ + ); + // Build the request path. $path = '/repos/' . $owner . '/' . $repo . '/downloads'; @@ -57,10 +64,17 @@ public function getList($owner, $repo) * @return object * * @since 1.0 - * @deprecated The Releases API should be used instead + * @deprecated 5.0 GitHub has removed the Downloads API. Use the Releases API instead. */ public function get($owner, $repo, $id) { + trigger_deprecation( + 'joomla/github', + '__DEPLOY_VERSION__', + '%s() is deprecated and will be removed in 5.0, GitHub has removed the Downloads API. Use the Releases API instead.', + __METHOD__ + ); + // Build the request path. $path = '/repos/' . $owner . '/' . $repo . '/downloads/' . $id; @@ -87,10 +101,17 @@ public function get($owner, $repo, $id) * @note This API endpoint no longer exists at GitHub * @since 1.0 * @throws \RuntimeException - * @deprecated The Releases API should be used instead + * @deprecated 5.0 GitHub has removed the Downloads API. Use the Releases API instead. */ public function create($owner, $repo, $name, $size, $description = '', $contentType = '') { + trigger_deprecation( + 'joomla/github', + '__DEPLOY_VERSION__', + '%s() is deprecated and will be removed in 5.0, GitHub has removed the Downloads API. Use the Releases API instead.', + __METHOD__ + ); + throw new \RuntimeException('The GitHub API no longer supports creating downloads. The Releases API should be used instead.'); } @@ -137,10 +158,17 @@ public function create($owner, $repo, $name, $size, $description = '', $contentT * @note This API endpoint no longer exists at GitHub * @since 1.0 * @throws \RuntimeException - * @deprecated The Releases API should be used instead + * @deprecated 5.0 GitHub has removed the Downloads API. Use the Releases API instead. */ public function upload($key, $acl, $successActionStatus, $filename, $awsAccessKeyId, $policy, $signature, $contentType, $file) { + trigger_deprecation( + 'joomla/github', + '__DEPLOY_VERSION__', + '%s() is deprecated and will be removed in 5.0, GitHub has removed the Downloads API. Use the Releases API instead.', + __METHOD__ + ); + throw new \RuntimeException('The GitHub API no longer supports creating downloads. The Releases API should be used instead.'); } @@ -154,10 +182,17 @@ public function upload($key, $acl, $successActionStatus, $filename, $awsAccessKe * @return object * * @since 1.0 - * @deprecated The Releases API should be used instead + * @deprecated 5.0 GitHub has removed the Downloads API. Use the Releases API instead. */ public function delete($owner, $repo, $id) { + trigger_deprecation( + 'joomla/github', + '__DEPLOY_VERSION__', + '%s() is deprecated and will be removed in 5.0, GitHub has removed the Downloads API. Use the Releases API instead.', + __METHOD__ + ); + // Build the request path. $path = '/repos/' . $owner . '/' . $repo . '/downloads/' . (int) $id; diff --git a/src/RequestHeadersHttp.php b/src/RequestHeadersHttp.php new file mode 100644 index 00000000..2d7cb4c3 --- /dev/null +++ b/src/RequestHeadersHttp.php @@ -0,0 +1,220 @@ +getClient(); + } + + $this->client = $client; + $this->headers = $headers; + } + + /** + * Get the wrapped HTTP client. + * + * @return Http + * + * @since __DEPLOY_VERSION__ + */ + public function getClient(): Http + { + return $this->client; + } + + /** + * Get an option from the wrapped HTTP client. + * + * @param string $key The name of the option to get. + * @param mixed $default The default value if the option is not set. + * + * @return mixed The option value. + * + * @since __DEPLOY_VERSION__ + */ + public function getOption($key, $default = null) + { + return $this->client->getOption($key, $default); + } + + /** + * Set an option on the wrapped HTTP client. + * + * @param string $key The name of the option to set. + * @param mixed $value The option value to set. + * + * @return $this + * + * @since __DEPLOY_VERSION__ + */ + public function setOption($key, $value) + { + $this->client->setOption($key, $value); + + return $this; + } + + /** + * {@inheritdoc} + */ + public function options($url, array $headers = [], $timeout = null) + { + return $this->withHeaders(fn () => $this->client->options($url, $headers, $timeout)); + } + + /** + * {@inheritdoc} + */ + public function head($url, array $headers = [], $timeout = null) + { + return $this->withHeaders(fn () => $this->client->head($url, $headers, $timeout)); + } + + /** + * {@inheritdoc} + */ + public function get($url, array $headers = [], $timeout = null) + { + return $this->withHeaders(fn () => $this->client->get($url, $headers, $timeout)); + } + + /** + * {@inheritdoc} + */ + public function post($url, $data, array $headers = [], $timeout = null) + { + return $this->withHeaders(fn () => $this->client->post($url, $data, $headers, $timeout), $data); + } + + /** + * {@inheritdoc} + */ + public function put($url, $data, array $headers = [], $timeout = null) + { + return $this->withHeaders(fn () => $this->client->put($url, $data, $headers, $timeout), $data); + } + + /** + * {@inheritdoc} + */ + public function delete($url, array $headers = [], $timeout = null, $data = null) + { + return $this->withHeaders(fn () => $this->client->delete($url, $headers, $timeout, $data), $data); + } + + /** + * {@inheritdoc} + */ + public function trace($url, array $headers = [], $timeout = null) + { + return $this->withHeaders(fn () => $this->client->trace($url, $headers, $timeout)); + } + + /** + * {@inheritdoc} + */ + public function patch($url, $data, array $headers = [], $timeout = null) + { + return $this->withHeaders(fn () => $this->client->patch($url, $data, $headers, $timeout), $data); + } + + /** + * {@inheritdoc} + */ + public function sendRequest(RequestInterface $request): ResponseInterface + { + return $this->withHeaders(fn () => $this->client->sendRequest($request)); + } + + /** + * Run a request with the GitHub headers added to the wrapped client, and restore its headers afterwards. + * + * The headers are put on the client's options rather than passed with the request, so that request headers + * passed by the caller keep precedence, as they do for the client's own headers. A string body is sent as JSON + * unless a content type is given. + * + * @param callable $request Callback sending the request. + * @param mixed $data The request body. + * + * @return mixed The response. + * + * @since __DEPLOY_VERSION__ + */ + private function withHeaders(callable $request, $data = null) + { + $original = $this->client->getOption('headers'); + $headers = (array) ($original ?? []); + $existing = array_change_key_case($headers, \CASE_LOWER); + $added = ($this->headers)(); + + if (\is_string($data)) { + $added['Content-Type'] = 'application/json'; + } + + foreach ($added as $name => $value) { + if (!isset($existing[strtolower($name)])) { + $headers[$name] = $value; + } + } + + $this->client->setOption('headers', $headers); + + try { + return $request(); + } finally { + $this->client->setOption('headers', $original); + } + } +}