feature #28477 [Validator] Add new json Validator (zairigimad)

This PR was squashed before being merged into the 4.3-dev branch (closes #28477).

Discussion
----------

[Validator] Add new json Validator

| Q             | A
| ------------- | ---
| Branch?       | master
| Bug fix?      | no
| New feature?  | yes
| BC breaks?    | no
| Deprecations? | no
| Tests pass?   | yes
| License       | MIT
| Doc PR        | https://github.com/symfony/symfony-docs/pull/10351

Hi,

in so many cases we want to test if a value is a valid json or not, so I propose this new ~~NotJson~~  `Json` constraint for this need.

cordially,

Commits
-------

131febc7be [Validator] Add new json Validator
This commit is contained in:
Fabien Potencier 2019-02-13 08:35:29 +01:00
commit b951a0fce4
6 changed files with 169 additions and 1 deletions

View File

@ -7,7 +7,8 @@ CHANGELOG
* added options `iban` and `ibanPropertyPath` to Bic constraint
* added UATP cards support to `CardSchemeValidator`
* added option `allowNull` to NotBlank constraint
* added `Json` constraint
4.2.0
-----

View File

@ -0,0 +1,31 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\Validator\Constraints;
use Symfony\Component\Validator\Constraint;
/**
* @Annotation
* @Target({"PROPERTY", "METHOD", "ANNOTATION"})
*
* @author Imad ZAIRIG <imadzairig@gmail.com>
*/
class Json extends Constraint
{
const INVALID_JSON_ERROR = '0789c8ad-2d2b-49a4-8356-e2ce63998504';
protected static $errorNames = [
self::INVALID_JSON_ERROR => 'INVALID_JSON_ERROR',
];
public $message = 'This value should be valid JSON.';
}

View File

@ -0,0 +1,51 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\Validator\Constraints;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
use Symfony\Component\Validator\Exception\UnexpectedTypeException;
/**
* @author Imad ZAIRIG <imadzairig@gmail.com>
*/
class JsonValidator extends ConstraintValidator
{
/**
* {@inheritdoc}
*/
public function validate($value, Constraint $constraint)
{
if (!$constraint instanceof Json) {
throw new UnexpectedTypeException($constraint, Json::class);
}
if (null === $value || '' === $value) {
return;
}
if (!is_scalar($value) && !(\is_object($value) && method_exists($value, '__toString'))) {
throw new UnexpectedTypeException($value, 'string');
}
$value = (string) $value;
json_decode($value);
if (JSON_ERROR_NONE !== json_last_error()) {
$this->context->buildViolation($constraint->message)
->setParameter('{{ value }}', $this->formatValue($value))
->setCode(Json::INVALID_JSON_ERROR)
->addViolation();
}
}
}

View File

@ -330,6 +330,10 @@
<source>This Business Identifier Code (BIC) is not associated with IBAN {{ iban }}.</source>
<target>This Business Identifier Code (BIC) is not associated with IBAN {{ iban }}.</target>
</trans-unit>
<trans-unit id="85">
<source>This value should be valid JSON.</source>
<target>This value should be valid JSON.</target>
</trans-unit>
</body>
</file>
</xliff>

View File

@ -330,6 +330,10 @@
<source>This Business Identifier Code (BIC) is not associated with IBAN {{ iban }}.</source>
<target>Ce code d'identification d'entreprise (BIC) n'est pas associé à l'IBAN {{ iban }}.</target>
</trans-unit>
<trans-unit id="85">
<source>This value should be valid JSON.</source>
<target>Cette valeur doit être un JSON valide.</target>
</trans-unit>
</body>
</file>
</xliff>

View File

@ -0,0 +1,77 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\Validator\Tests\Constraints;
use Symfony\Component\Validator\Constraints\Json;
use Symfony\Component\Validator\Constraints\JsonValidator;
use Symfony\Component\Validator\Test\ConstraintValidatorTestCase;
class JsonValidatorTest extends ConstraintValidatorTestCase
{
protected function createValidator()
{
return new JsonValidator();
}
/**
* @dataProvider getValidValues
*/
public function testJsonIsValid($value)
{
$this->validator->validate($value, new Json());
$this->assertNoViolation();
}
/**
* @dataProvider getInvalidValues
*/
public function testInvalidValues($value)
{
$constraint = new Json([
'message' => 'myMessageTest',
]);
$this->validator->validate($value, $constraint);
$this->buildViolation('myMessageTest')
->setParameter('{{ value }}', '"'.$value.'"')
->setCode(Json::INVALID_JSON_ERROR)
->assertRaised();
}
public function getValidValues()
{
return [
['{"planet":"earth", "country": "Morocco","city": "Rabat" ,"postcode" : 10160, "is_great": true,
"img" : null, "area": 118.5, "foo": 15 }'],
[null],
[''],
['"null"'],
['null'],
['"string"'],
['1'],
['true'],
[1],
];
}
public function getInvalidValues()
{
return [
['{"foo": 3 "bar": 4}'],
['{"foo": 3 ,"bar": 4'],
['{foo": 3, "bar": 4}'],
['foo'],
];
}
}