Skip to content

Commit cfa7f1d

Browse files
committed
Add Helper::isValid()
refs #15
1 parent f117679 commit cfa7f1d

File tree

2 files changed

+51
-0
lines changed

2 files changed

+51
-0
lines changed

src/Utils/Helper.php

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
namespace Art4\JsonApiClient\Utils;
44

5+
use Art4\JsonApiClient\Exception\Exception;
56
use 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
*

tests/unit/Utils/HelperTest.php

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff 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
}

0 commit comments

Comments
 (0)