Skip to content

Commit 615247c

Browse files
partikusnorberttech
authored andcommitted
#58 Added error message if JSON decode failed for both pattern and value (#85)
1 parent 55456e2 commit 615247c

File tree

2 files changed

+44
-0
lines changed

2 files changed

+44
-0
lines changed

src/Matcher/JsonMatcher.php

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,12 @@ public function match($value, $pattern)
2929
}
3030

3131
if (!Json::isValid($value)) {
32+
$this->error = sprintf("Invalid given JSON of value. %s", $this->getErrorMessage());
33+
return false;
34+
}
35+
36+
if (!Json::isValidPattern($pattern) ) {
37+
$this->error = sprintf("Invalid given JSON of pattern. %s", $this->getErrorMessage());
3238
return false;
3339
}
3440

@@ -49,4 +55,22 @@ public function canMatch($pattern)
4955
{
5056
return Json::isValidPattern($pattern);
5157
}
58+
59+
private function getErrorMessage()
60+
{
61+
switch(json_last_error()) {
62+
case JSON_ERROR_DEPTH:
63+
return 'Maximum stack depth exceeded';
64+
case JSON_ERROR_STATE_MISMATCH:
65+
return 'Underflow or the modes mismatch';
66+
case JSON_ERROR_CTRL_CHAR:
67+
return 'Unexpected control character found';
68+
case JSON_ERROR_SYNTAX:
69+
return 'Syntax error, malformed JSON';
70+
case JSON_ERROR_UTF8:
71+
return 'Malformed UTF-8 characters, possibly incorrectly encoded';
72+
default:
73+
return 'Unknown error';
74+
}
75+
}
5276
}

tests/Matcher/JsonMatcherTest.php

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -113,6 +113,26 @@ public function test_error_when_path_in_nested_value_does_not_exist()
113113
$this->assertEquals($this->matcher->getError(), 'There is no element under path [foo][bar][faz] in value.');
114114
}
115115

116+
public function test_error_when_json_pattern_is_invalid()
117+
{
118+
$value = '{"test": "value"}';
119+
$pattern = '{"test": "@string@",}';
120+
121+
$this->assertFalse($this->matcher->match($value, $pattern));
122+
123+
$this->assertEquals($this->matcher->getError(), 'Invalid given JSON of pattern. Syntax error, malformed JSON');
124+
}
125+
126+
public function test_error_when_json_value_is_invalid()
127+
{
128+
$value = '{"test": "value",}';
129+
$pattern = '{"test": "@string@"}';
130+
131+
$this->assertFalse($this->matcher->match($value, $pattern));
132+
133+
$this->assertEquals($this->matcher->getError(), 'Invalid given JSON of value. Syntax error, malformed JSON');
134+
}
135+
116136
public static function positivePatterns()
117137
{
118138
return array(

0 commit comments

Comments
 (0)