File tree Expand file tree Collapse file tree 2 files changed +57
-1
lines changed Expand file tree Collapse file tree 2 files changed +57
-1
lines changed Original file line number Diff line number Diff line change 99 */
1010class 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}
Original file line number Diff line number Diff line change 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+ }
You can’t perform that action at this time.
0 commit comments