Improvements on JSON rule

This commit is contained in:
Emmerson 2015-10-18 02:09:10 -03:00 committed by Henrique Moody
parent 6b85855311
commit dddad80f48
2 changed files with 33 additions and 45 deletions

View file

@ -15,11 +15,12 @@ class Json extends AbstractRule
{
public function validate($input)
{
if (is_string($input)
&& strtolower($input) == 'null') {
return true;
if (!is_string($input) || '' === $input) {
return false;
}
return (null !== json_decode($input));
json_decode($input);
return (json_last_error() === JSON_ERROR_NONE);
}
}

View file

@ -16,51 +16,38 @@ namespace Respect\Validation\Rules;
* @covers Respect\Validation\Rules\Json
* @covers Respect\Validation\Exceptions\JsonException
*/
class JsonTest extends \PHPUnit_Framework_TestCase
class JsonTest extends RuleTestCase
{
protected $json;
protected function setUp()
public function providerForValidInput()
{
$this->json = new Json();
}
$json = new Json();
/**
* @dataProvider providerForPass
*/
public function testValidJsonsShouldReturnTrue($input)
{
$this->assertTrue($this->json->__invoke($input));
$this->assertTrue($this->json->check($input));
$this->assertTrue($this->json->assert($input));
}
/**
* @expectedException Respect\Validation\Exceptions\JSonException
*/
public function testInvalidJsonsShouldThrowJsonException()
{
$this->assertFalse($this->json->__invoke('{foo:bar}'));
$this->assertFalse($this->json->assert('{foo:bar}'));
}
public function testInvalidJsonsNotBeValid()
{
$this->assertFalse($this->json->validate(''));
}
public function providerForPass()
{
return [
['2'],
['"abc"'],
['[1,2,3]'],
['["foo", "bar", "number", 1]'],
['{"foo": "bar", "number":1}'],
['[]'],
['{}'],
['false'],
['null'],
[$json, '2'],
[$json, '"abc"'],
[$json, '[1,2,3]'],
[$json, '["foo", "bar", "number", 1]'],
[$json, '{"foo": "bar", "number":1}'],
[$json, '[]'],
[$json, '{}'],
[$json, 'false'],
[$json, 'null'],
];
}
public function providerForInvalidInput()
{
$json = new Json();
return [
[$json, false],
[$json, new \stdClass()],
[$json, []],
[$json, ''],
[$json, 'a'],
[$json, 'xx'],
[$json, '{foo: bar}'],
[$json, '{foo: "baz"}'],
];
}
}