diff --git a/README.md b/README.md index 11d634c..891408c 100644 --- a/README.md +++ b/README.md @@ -527,7 +527,9 @@ s('A102F')->isHexadecimal(); // true ##### isJson() -Returns true if the string is JSON, false otherwise. +Returns true if the string is JSON, false otherwise. Unlike json_decode +in PHP 5.x, this method is consistent with PHP 7 and other JSON parsers, +in that an empty string is not considered valid JSON. ```php s('{"foo":"bar"}')->isJson(); // true diff --git a/src/Stringy.php b/src/Stringy.php index 9473214..2710660 100644 --- a/src/Stringy.php +++ b/src/Stringy.php @@ -589,12 +589,18 @@ class Stringy implements \Countable, \IteratorAggregate, \ArrayAccess } /** - * Returns true if the string is JSON, false otherwise. + * Returns true if the string is JSON, false otherwise. Unlike json_decode + * in PHP 5.x, this method is consistent with PHP 7 and other JSON parsers, + * in that an empty string is not considered valid JSON. * * @return bool Whether or not $str is JSON */ public function isJson() { + if (!$this->length()) { + return false; + } + json_decode($this->str); return (json_last_error() === JSON_ERROR_NONE); diff --git a/tests/StringyTest.php b/tests/StringyTest.php index 03ef5fb..d51666d 100644 --- a/tests/StringyTest.php +++ b/tests/StringyTest.php @@ -2066,7 +2066,13 @@ class StringyTestCase extends PHPUnit_Framework_TestCase public function isJsonProvider() { return array( - array(true, ''), + array(false, ''), + array(false, ' '), + array(true, 'null'), + array(true, 'true'), + array(true, 'false'), + array(true, '[]'), + array(true, '{}'), array(true, '123'), array(true, '{"foo": "bar"}'), array(false, '{"foo":"bar",}'),