Skip to content

Commit 0753bed

Browse files
authored
Merge pull request #16 from inhere/master
fix: parse json5 codes always thorw JsonException
2 parents 7b4e50c + c07ac4d commit 0753bed

File tree

4 files changed

+25
-5
lines changed

4 files changed

+25
-5
lines changed

phpunit.xml.dist

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
<?xml version="1.0" encoding="UTF-8"?>
2-
<phpunit bootstrap="vendor/autoload.php"
2+
<phpunit bootstrap="test/bootstrap.php"
33
backupGlobals="false"
44
backupStaticAttributes="false"
55
colors="true"

src/Json5Decoder.php

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -73,9 +73,13 @@ public static function decode($source, $associative = false, $depth = 512, $opti
7373
// Try parsing with json_decode first, since that's much faster
7474
// We only attempt this on PHP 7+ because 5.x doesn't parse some edge cases correctly
7575
if (PHP_VERSION_ID >= 70000) {
76-
$result = \json_decode($source, $associative, $depth, $options);
77-
if (\json_last_error() === \JSON_ERROR_NONE) {
78-
return $result;
76+
try {
77+
$result = \json_decode($source, $associative, $depth, $options);
78+
if (\json_last_error() === \JSON_ERROR_NONE) {
79+
return $result;
80+
}
81+
} catch (\Throwable $e) {
82+
// ignore exception, continue parsing as JSON5
7983
}
8084
}
8185

@@ -135,7 +139,7 @@ private function next()
135139
}
136140

137141
$this->at++;
138-
142+
139143
return $this->currentByte = $this->getByte($this->at);
140144
}
141145

test/Functional/ParseTest.php

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -202,6 +202,18 @@ public function testFunctionAlias()
202202
$this->assertEquals(Json5Decoder::decode($json, true), json5_decode($json, true));
203203
}
204204

205+
/**
206+
* Regression: Parsing JSON5 always throws JsonException when JSON_THROW_ON_ERROR is set by the caller
207+
*
208+
* @see https://github.com/colinodell/json5/issues/15
209+
*/
210+
public function testExceptionShouldNotBeThrownOnValidJSON5()
211+
{
212+
$ret = Json5Decoder::decode('"foo" // simple string with a comment', false, 512, JSON_THROW_ON_ERROR);
213+
214+
$this->assertEquals('foo', $ret);
215+
}
216+
205217
private function getErrorSpec($file)
206218
{
207219
$errorSpec = str_replace('.txt', '.errorSpec', $file);

test/bootstrap.php

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
<?php
2+
3+
require_once __DIR__ . '/../vendor/autoload.php';
4+
require_once __DIR__ . '/../src/global.php';

0 commit comments

Comments
 (0)