Skip to content

Commit c9107c3

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

File tree

2 files changed

+57
-1
lines changed

2 files changed

+57
-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: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
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(
19+
'rate limit exceeded',
20+
$result->parsedMessage()->error,
21+
);
22+
$this->assertEquals(88, $result->parsedMessage()->code);
23+
}
24+
25+
public function testParseMessageWithInvalidJson()
26+
{
27+
$plainString = 'This is not JSON';
28+
$result = new TwitterOAuthException($plainString);
29+
30+
$this->assertIsString($result->parsedMessage());
31+
$this->assertEquals('This is not JSON', $result->parsedMessage());
32+
}
33+
34+
public function testParseMessageWithEmptyString()
35+
{
36+
$emptyString = '';
37+
$result = new TwitterOAuthException($emptyString);
38+
39+
$this->assertIsString($result->parsedMessage());
40+
$this->assertEquals('', $result->parsedMessage());
41+
}
42+
}

0 commit comments

Comments
 (0)