File tree Expand file tree Collapse file tree 2 files changed +54
-1
lines changed Expand file tree Collapse file tree 2 files changed +54
-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 ('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+ }
You can’t perform that action at this time.
0 commit comments