Skip to content

Commit

Permalink
Add comments + some cosmetic changes
Browse files Browse the repository at this point in the history
  • Loading branch information
hectorj committed Jun 8, 2017
1 parent 0f456e7 commit d64ad3c
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 7 deletions.
18 changes: 12 additions & 6 deletions src/AbstractService.php
Original file line number Diff line number Diff line change
Expand Up @@ -66,24 +66,30 @@ protected function delete(string $endpoint, array $options = [], ApiKey $apiKey
);
}

protected function jsonDecode(string $json, $assoc = true, $depth = 512, $options = 0)
/**
* Does the same as json_decode(), but with proper error handling
* @see \json_decode()
*/
protected function jsonDecode(string $json, bool $assoc = true, int $depth = 512, int $options = 0)
{
if ($json === '' || $json === null) {
return null;
}

$data = \json_decode($json, $assoc, $depth, $options);

if (JSON_ERROR_NONE !== json_last_error()) {
$last = json_last_error();
$message = 'Unable to parse JSON data: '.json_last_error_msg();
throw new JsonDecodingError($message, $last);
$lastJsonError = json_last_error();
if (JSON_ERROR_NONE !== $lastJsonError) {
throw new JsonDecodingError(
'Unable to parse JSON data: '.json_last_error_msg(),
$lastJsonError
);
}

return $data;
}

private function addAuth(array $options, ?ApiKey $apiKey):array
private function addAuth(array $options, ?ApiKey $apiKey): array
{
if ($apiKey) {
$options['headers']['Authorization'] = 'token '.$apiKey->getKey();
Expand Down
3 changes: 2 additions & 1 deletion tests/AbstractServiceTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -19,13 +19,14 @@ class AbstractServiceTest extends TestCase
{
public function testInvalidJsonProcessing()
{
// Create a Guzzle client which will send back just one mocked response with malformed JSON.
$mock = new MockHandler([
new Response(200, [], '{"malformedJSON":[]]}'),
]);

$handler = HandlerStack::create($mock);
$client = new Client(['handler' => $handler]);

// We want a proper exception, not a fatal error nor a silent fail.
$this->expectException(JsonDecodingError::class);
(new TestService($client))->getTest();
}
Expand Down
3 changes: 3 additions & 0 deletions tests/TestService.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,9 @@

use Wizaplace\AbstractService;

/**
* Dummy service, here to test generic features not tied to any specific service
*/
class TestService extends AbstractService
{
public function getTest()
Expand Down

0 comments on commit d64ad3c

Please sign in to comment.