Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
49 changes: 49 additions & 0 deletions Tests/GithubObjectTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@

use Joomla\Github\Tests\Stub\GitHubTestCase;
use Joomla\Github\Tests\Stub\ObjectMock;
use Joomla\Http\Exception\UnexpectedResponseException;
use PHPUnit\Framework\Attributes\DataProvider;

/**
Expand Down Expand Up @@ -125,6 +126,42 @@ public function testFetchUrlBasicAuth()
);
}

/**
* Tests that processResponse() accepts one of several expected codes
*
* @return void
*/
public function testProcessResponseWithSeveralExpectedCodes()
{
$this->assertEquals(
json_decode($this->sampleString),
$this->processResponse($this->getResponseObject($this->sampleString, 202), [202, 205])
);
}

/**
* Tests that processResponse() returns null for an empty body
*
* @return void
*/
public function testProcessResponseWithEmptyBody()
{
$this->assertNull($this->processResponse($this->getResponseObject('', 204), 204));
}

/**
* Tests that processResponse() throws on a body that is not JSON
*
* @return void
*/
public function testProcessResponseWithInvalidJson()
{
$this->expectException(UnexpectedResponseException::class);
$this->expectExceptionMessage('Invalid JSON received from GitHub');

$this->processResponse($this->getResponseObject('<html>Maintenance</html>', 200));
}

/**
* Tests the fetchUrl method using an oAuth token.
*
Expand All @@ -142,4 +179,16 @@ public function testFetchUrlToken()
'URL is not as expected.'
);
}

/**
* Calls the protected processResponse() method of the object under test.
*
* @param mixed ...$arguments The arguments.
*
* @return mixed
*/
private function processResponse(...$arguments)
{
return (new \ReflectionMethod($this->object, 'processResponse'))->invoke($this->object, ...$arguments);
}
}
15 changes: 15 additions & 0 deletions Tests/Package/Activity/NotificationsTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,21 @@ public function testMarkRead()
);
}

/**
* Tests that markRead() accepts 202 Accepted (asynchronous processing)
*
* @return void
*/
public function testMarkReadAccepted()
{
$this->client->expects($this->once())
->method('put')
->with('/notifications', '{"unread":true,"read":true}', [], 0)
->willReturn($this->getResponseObject('{"message":"Marking notifications as read."}', 202));

$this->assertIsObject($this->object->markRead());
}

/**
* Test method.
*
Expand Down
18 changes: 18 additions & 0 deletions Tests/Package/AuthorizationsTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -565,6 +565,24 @@ public function testGetRateLimitFailure()
$this->object->getRateLimit();
}

/**
* Tests the getRateLimit method with an error response that is not JSON
*
* @return void
*/
public function testGetRateLimitFailureWithoutJson()
{
$this->expectException(\DomainException::class);
$this->expectExceptionMessage('Invalid response received from GitHub.');

$this->client->expects($this->once())
->method('get')
->with('/rate_limit')
->willReturn($this->getResponseObject('<html>Bad gateway</html>', 502));

$this->object->getRateLimit();
}

/**
* Tests the getAuthorizationLink method
*
Expand Down
18 changes: 18 additions & 0 deletions Tests/Package/Repositories/CollaboratorsTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -143,6 +143,24 @@ public function testAdd()
);
}

/**
* Tests that add() accepts 201 Created, which GitHub answers when it sends an invitation
*
* @return void
*/
public function testAddInvitation()
{
$this->client->expects($this->once())
->method('put')
->with('/repos/joomla/joomla-framework/collaborators/elkuku')
->willReturn($this->getResponseObject($this->sampleString, 201));

$this->assertThat(
$this->object->add('joomla', 'joomla-framework', 'elkuku'),
$this->equalTo(json_decode($this->sampleString))
);
}

/**
* Tests the Remove method.
*
Expand Down
35 changes: 27 additions & 8 deletions Tests/Package/Repositories/ContentsTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@

use Joomla\Github\Package\Repositories\Contents;
use Joomla\Github\Tests\Stub\GitHubTestCase;
use Joomla\Http\Exception\UnexpectedResponseException;

/**
* Test class for Contents.
Expand Down Expand Up @@ -116,36 +117,54 @@ public function testGetRef()
*/
public function testGetArchiveLink()
{
$this->response = $this->getResponseObject($this->sampleString, 302);
$this->response = $this->getResponseObject('', 302, ['Location' => 'https://codeload.github.com/joomla/joomla-platform/legacy.zip/main']);

$this->client->expects($this->once())
->method('get')
->with('/repos/joomla/joomla-platform/zipball')
->willReturn($this->response);

$this->assertThat(
$this->object->getArchiveLink('joomla', 'joomla-platform'),
$this->equalTo(json_decode($this->sampleString))
$this->assertSame(
'https://codeload.github.com/joomla/joomla-platform/legacy.zip/main',
$this->object->getArchiveLink('joomla', 'joomla-platform')
);
}

/**
* Tests the GetArchiveLink method when the HTTP client followed the redirect.
*
* @return void
*/
public function testGetArchiveLinkRedirectFollowed()
{
$this->expectException(UnexpectedResponseException::class);
$this->expectExceptionMessage('follow_location');

$this->client->expects($this->once())
->method('get')
->with('/repos/joomla/joomla-platform/zipball')
->willReturn($this->getResponseObject('PK', 200));

$this->object->getArchiveLink('joomla', 'joomla-platform');
}

/**
* Tests the GetArchiveLinkRef method.
*
* @return void
*/
public function testGetArchiveLinkRef()
{
$this->response = $this->getResponseObject($this->sampleString, 302);
$this->response = $this->getResponseObject('', 302, ['Location' => 'https://codeload.github.com/joomla/joomla-platform/legacy.zip/123abc']);

$this->client->expects($this->once())
->method('get')
->with('/repos/joomla/joomla-platform/zipball?ref=123abc')
->willReturn($this->response);

$this->assertThat(
$this->object->getArchiveLink('joomla', 'joomla-platform', 'zipball', '123abc'),
$this->equalTo(json_decode($this->sampleString))
$this->assertSame(
'https://codeload.github.com/joomla/joomla-platform/legacy.zip/123abc',
$this->object->getArchiveLink('joomla', 'joomla-platform', 'zipball', '123abc')
);
}

Expand Down
9 changes: 2 additions & 7 deletions Tests/Package/RepositoriesTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -391,13 +391,8 @@ public function testDelete()
$this->client->expects($this->once())
->method('delete')
->with('/repos/joomla/joomla-cms', [], 0)
->willReturn($this->response);

$response = json_decode((string) $this->response->getBody());
->willReturn($this->getResponseObject('', 204));

$this->assertEquals(
$response,
$this->object->delete('joomla', 'joomla-cms')
);
$this->assertNull($this->object->delete('joomla', 'joomla-cms'));
}
}
3 changes: 1 addition & 2 deletions Tests/Package/UsersTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -198,8 +198,7 @@ public function testGetList()
"avatar_url": "https://github.com/images/error/octocat_happy.gif",
"gravatar_id": "somehexcode",
"url": "https://api.github.com/users/octocat"
}
],
},
{
"login": "elkuku",
"id": 33978,
Expand Down
16 changes: 16 additions & 0 deletions docs/overview.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,19 @@
# Github API package

TODO

## Responses and errors

The package methods decode the JSON body of GitHub's answer and return it. An answer with an empty body, such as
`204 No Content`, returns `null`. An unexpected status code, or a body that is not valid JSON (for example an HTML
error page of a proxy), raises a `Joomla\Http\Exception\UnexpectedResponseException`; its `getResponse()` gives
access to the response.

Some endpoints have more than one successful status code: `$github->activity->notifications->markRead()` and
`markReadRepository()` accept `202 Accepted` (GitHub marks the notifications asynchronously) as well as `205`, and
`$github->repositories->collaborators->add()` accepts `201` (an invitation was sent) as well as `204`.
`$github->repositories->delete()` expects `204`.

`$github->repositories->contents->getArchiveLink()` returns the archive URL from the `Location` header of GitHub's
redirect. This needs an HTTP transport that does not follow redirects (option `follow_location` set to `false`);
otherwise the transport downloads the archive and the method throws an `UnexpectedResponseException`.
26 changes: 21 additions & 5 deletions src/AbstractGithubObject.php
Original file line number Diff line number Diff line change
Expand Up @@ -150,25 +150,41 @@ protected function fetchUrl($path, $page = 0, $limit = 0)
/**
* Process the response and decode it.
*
* @param Response $response The response.
* @param integer $expectedCode The expected "good" code.
* @param Response $response The response.
* @param integer|int[] $expectedCode The expected "good" code, or a list of them.
*
* @return mixed
* @return mixed The decoded JSON body, or null if the body is empty (e.g. for 204 No Content).
*
* @since 1.0
* @since __DEPLOY_VERSION__ Accepts a list of expected codes and throws on a body that is not valid JSON.
* @throws UnexpectedResponseException
*/
protected function processResponse(Response $response, $expectedCode = 200)
{
// Validate the response code.
if ($response->getStatusCode() != $expectedCode) {
if (!\in_array($response->getStatusCode(), (array) $expectedCode)) {
// Decode the error response and throw an exception.
$error = json_decode((string) $response->getBody());
$message = isset($error->message) ? $error->message : 'Invalid response received from GitHub.';

throw new UnexpectedResponseException($response, $message, $response->getStatusCode());
}

return json_decode((string) $response->getBody());
$body = (string) $response->getBody();

if ($body === '') {
return null;
}

try {
return json_decode($body, false, 512, \JSON_THROW_ON_ERROR);
} catch (\JsonException $e) {
throw new UnexpectedResponseException(
$response,
'Invalid JSON received from GitHub: ' . $e->getMessage(),
$response->getStatusCode(),
$e
);
}
}
}
6 changes: 4 additions & 2 deletions src/Package/Activity/Notifications.php
Original file line number Diff line number Diff line change
Expand Up @@ -136,9 +136,10 @@ public function markRead($unread = true, $read = true, \DateTimeInterface $lastR
$data['last_read_at'] = $lastReadAt->format(\DateTime::RFC3339);
}

// GitHub answers 202 when it marks the notifications asynchronously.
return $this->processResponse(
$this->client->put($this->fetchUrl($path), json_encode($data)),
205
[202, 205]
);
}

Expand Down Expand Up @@ -172,9 +173,10 @@ public function markReadRepository($owner, $repo, $unread, $read, \DateTimeInter
$data['last_read_at'] = $lastReadAt->format(\DateTime::RFC3339);
}

// GitHub answers 202 when it marks the notifications asynchronously.
return $this->processResponse(
$this->client->put($this->fetchUrl($path), json_encode($data)),
205
[202, 205]
);
}

Expand Down
4 changes: 3 additions & 1 deletion src/Package/Authorization.php
Original file line number Diff line number Diff line change
Expand Up @@ -251,7 +251,9 @@ public function getRateLimit()
// Decode the error response and throw an exception.
$error = json_decode((string) $response->getBody());

throw new UnexpectedResponseException($response, $error->message, $response->getStatusCode());
$message = $error->message ?? 'Invalid response received from GitHub.';

throw new UnexpectedResponseException($response, $message, $response->getStatusCode());
}

return json_decode((string) $response->getBody());
Expand Down
3 changes: 2 additions & 1 deletion src/Package/Repositories.php
Original file line number Diff line number Diff line change
Expand Up @@ -414,7 +414,8 @@ public function delete($owner, $repo)

// Send the request.
return $this->processResponse(
$this->client->delete($this->fetchUrl($path))
$this->client->delete($this->fetchUrl($path)),
204
);
}
}
3 changes: 2 additions & 1 deletion src/Package/Repositories/Collaborators.php
Original file line number Diff line number Diff line change
Expand Up @@ -91,9 +91,10 @@ public function add($owner, $repo, $user)
// Build the request path.
$path = '/repos/' . $owner . '/' . $repo . '/collaborators/' . $user;

// 201 when an invitation was created, 204 when the user already is a collaborator
return $this->processResponse(
$this->client->put($this->fetchUrl($path), ''),
204
[201, 204]
);
}

Expand Down
Loading
Loading