Skip to content

Commit 7d5e431

Browse files
committed
Add TwitterOAuthException#parsedMessage
1 parent 99f2e5d commit 7d5e431

File tree

2 files changed

+54
-1
lines changed

2 files changed

+54
-1
lines changed

src/TwitterOAuthException.php

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,5 +9,19 @@
99
*/
1010
class TwitterOAuthException extends \Exception
1111
{
12-
// force phpcbf and prettier to format the same way
12+
/**
13+
* Attempts to parse message as JSON. If parsing fails, returns message directly.
14+
*
15+
* @return array|object|string
16+
*/
17+
public function parsedMessage()
18+
{
19+
$decoded = json_decode($this->message, false);
20+
21+
if (json_last_error() === JSON_ERROR_NONE) {
22+
return $decoded;
23+
}
24+
25+
return $this->message;
26+
}
1327
}
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
namespace Abraham\TwitterOAuth\Test;
6+
7+
use PHPUnit\Framework\TestCase;
8+
use Abraham\TwitterOAuth\TwitterOAuthException;
9+
10+
class TwitterOAuthExceptionTest extends TestCase
11+
{
12+
public function testParseMessageWithValidJson()
13+
{
14+
$jsonString = '{"error":"rate limit exceeded","code":88}';
15+
$result = new TwitterOAuthException($jsonString);
16+
17+
$this->assertIsObject($result->parsedMessage());
18+
$this->assertEquals('rate limit exceeded', $result->parsedMessage()->error);
19+
$this->assertEquals(88, $result->parsedMessage()->code);
20+
}
21+
22+
public function testParseMessageWithInvalidJson()
23+
{
24+
$plainString = 'This is not JSON';
25+
$result = new TwitterOAuthException($plainString);
26+
27+
$this->assertIsString($result->parsedMessage());
28+
$this->assertEquals('This is not JSON', $result->parsedMessage());
29+
}
30+
31+
public function testParseMessageWithEmptyString()
32+
{
33+
$emptyString = '';
34+
$result = new TwitterOAuthException($emptyString);
35+
36+
$this->assertIsString($result->parsedMessage());
37+
$this->assertEquals('', $result->parsedMessage());
38+
}
39+
}

0 commit comments

Comments
 (0)