File tree Expand file tree Collapse file tree 2 files changed +51
-0
lines changed Expand file tree Collapse file tree 2 files changed +51
-0
lines changed Original file line number Diff line number Diff line change 22
33namespace Art4 \JsonApiClient \Utils ;
44
5+ use Art4 \JsonApiClient \Exception \Exception ;
56use Art4 \JsonApiClient \Exception \ValidationException ;
67
78/**
@@ -32,6 +33,26 @@ public static function parse($json_string)
3233 );
3334 }
3435
36+ /**
37+ * Checks if a string is a valid JSON API
38+ *
39+ * @param string $json_string
40+ * @return bool true, if $json_string contains valid JSON API, else false
41+ */
42+ public static function isValid ($ json_string )
43+ {
44+ try
45+ {
46+ $ document = static ::parse ($ json_string );
47+ }
48+ catch ( Exception $ e )
49+ {
50+ return false ;
51+ }
52+
53+ return true ;
54+ }
55+
3556 /**
3657 * Decodes a json string
3758 *
Original file line number Diff line number Diff line change @@ -39,4 +39,34 @@ public function testParseWithInvalidJsonThrowsException()
3939
4040 $ output = Helper::parse ($ invalid_json );
4141 }
42+
43+ /**
44+ * @test isValid() with valid JSON API returns true
45+ */
46+ public function testIsValidWithValidJsonapi ()
47+ {
48+ $ jsonapi = '{"meta":{}} ' ;
49+
50+ $ this ->assertTrue (Helper::isValid ($ jsonapi ));
51+ }
52+
53+ /**
54+ * @test isValid() with invalid jsonapi
55+ */
56+ public function testIsValidWithInvalidJsonapi ()
57+ {
58+ $ invalid_jsonapi = '["This is valid JSON", "but invalid JSON API"] ' ;
59+
60+ $ this ->assertFalse (Helper::isValid ($ invalid_jsonapi ));
61+ }
62+
63+ /**
64+ * @test isValid() with invalid json
65+ */
66+ public function testIsValidWithInvalidJson ()
67+ {
68+ $ invalid_json = 'invalid_json_string ' ;
69+
70+ $ this ->assertFalse (Helper::isValid ($ invalid_json ));
71+ }
4272}
You can’t perform that action at this time.
0 commit comments