1
0
mirror of https://github.com/danielstjules/Stringy.git synced 2025-08-09 06:46:40 +02:00

Fix: isJSON now returns false for empty strings

This commit is contained in:
Daniel St. Jules
2015-09-09 21:24:11 -07:00
parent c5f370c46d
commit 4673754054
3 changed files with 17 additions and 3 deletions

View File

@@ -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

View File

@@ -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);

View File

@@ -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",}'),