8000 [Validator] String normalization options for string-based validators by renan-taranto · Pull Request #26484 · symfony/symfony · GitHub
[go: up one dir, main page]

Skip to content

[Validator] String normalization options for string-based validators #26484

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Mar 31, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
[Validator] String normalization options for string-based validators
  • Loading branch information
renan-taranto authored and nicolas-grekas committed Mar 13, 2019
commit 708d759b8dd1bc8a2fc1f18c49f510cc5069bb97
3 changes: 2 additions & 1 deletion src/Symfony/Component/Validator/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,8 @@ CHANGELOG
* added UATP cards support to `CardSchemeValidator`
* added option `allowNull` to NotBlank constraint
* added `Json` constraint

* added a new `normalizer` option to the string constraints and to the `NotBlank` constraint

4.2.0
-----

Expand Down
8 changes: 7 additions & 1 deletion src/Symfony/Component/Validator/Constraints/Email.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@

use Egulias\EmailValidator\EmailValidator as StrictEmailValidator;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\Exception\InvalidArgumentException;
use Symfony\Component\Validator\Exception\LogicException;

/**
Expand Down Expand Up @@ -73,6 +74,7 @@ class Email extends Constraint
*/
public $strict;
public $mode;
public $normalizer;

public function __construct($options = null)
{
Expand All @@ -89,7 +91,7 @@ public function __construct($options = null)
}

if (\is_array($options) && \array_key_exists('mode', $options) && !\in_array($options['mode'], self::$validationModes, true)) {
throw new \InvalidArgumentException('The "mode" parameter value is not valid.');
throw new InvalidArgumentException('The "mode" parameter value is not valid.');
}

parent::__construct($options);
Expand All @@ -98,5 +100,9 @@ public function __construct($options = null)
// throw new LogicException(sprintf('The "egulias/email-validator" component is required to use the "%s" constraint in strict mode.', __CLASS__));
@trigger_error(sprintf('Using the "%s" constraint in strict mode without the "egulias/email-validator" component installed is deprecated since Symfony 4.2.', __CLASS__), E_USER_DEPRECATED);
}

if (null !== $this->normalizer && !\is_callable($this->normalizer)) {
throw new InvalidArgumentException(sprintf('The "normalizer" option must be a valid callable ("%s" given).', \is_object($this->normalizer) ? \get_class($this->normalizer) : \gettype($this->normalizer)));
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,10 @@ public function validate($value, Constraint $constraint)

$value = (string) $value;

if (null !== $constraint->normalizer) {
$value = ($constraint->normalizer)($value);
}

if (null !== $constraint->strict) {
@trigger_error(sprintf('The %s::$strict property is deprecated since Symfony 4.1. Use %s::mode="%s" instead.', Email::class, Email::class, Email::VALIDATION_MODE_STRICT), E_USER_DEPRECATED);

Expand Down
7 changes: 7 additions & 0 deletions src/Symfony/Component/Validator/Constraints/Ip.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@

use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\Exception\ConstraintDefinitionException;
use Symfony\Component\Validator\Exception\InvalidArgumentException;

/**
* Validates that a value is a valid IP address.
Expand Down Expand Up @@ -72,6 +73,8 @@ class Ip extends Constraint

public $message = 'This is not a valid IP address.';

public $normalizer;

/**
* {@inheritdoc}
*/
Expand All @@ -82,5 +85,9 @@ public function __construct($options = null)
if (!\in_array($this->version, self::$versions)) {
throw new ConstraintDefinitionException(sprintf('The option "version" must be one of "%s"', implode('", "', self::$versions)));
}

if (null !== $this->normalizer && !\is_callable($this->normalizer)) {
throw new InvalidArgumentException(sprintf('The "normalizer" option must be a valid callable ("%s" given).', \is_object($this->normalizer) ? \get_class($this->normalizer) : \gettype($this->normalizer)));
}
}
}
4 changes: 4 additions & 0 deletions src/Symfony/Component/Validator/Constraints/IpValidator.php
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,10 @@ public function validate($value, Constraint $constraint)

$value = (string) $value;

if (null !== $constraint->normalizer) {
$value = ($constraint->normalizer)($value);
}

switch ($constraint->version) {
case Ip::V4:
$flag = FILTER_FLAG_IPV4;
Expand Down
6 changes: 6 additions & 0 deletions src/Symfony/Component/Validator/Constraints/Length.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
namespace Symfony\Component\Validator\Constraints;

use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\Exception\InvalidArgumentException;
use Symfony\Component\Validator\Exception\MissingOptionsException;

/**
Expand Down Expand Up @@ -39,6 +40,7 @@ class Length extends Constraint
public $max;
public $min;
public $charset = 'UTF-8';
public $normalizer;

public function __construct($options = null)
{
Expand All @@ -54,5 +56,9 @@ public function __construct($options = null)
if (null === $this->min && null === $this->max) {
throw new MissingOptionsException(sprintf('Either option "min" or "max" must be given for constraint %s', __CLASS__), ['min', 'max']);
}

if (null !== $this->normalizer && !\is_callable($this->normalizer)) {
throw new InvalidArgumentException(sprintf('The "normalizer" option must be a valid callable ("%s" given).', \is_object($this->normalizer) ? \get_class($this->normalizer) : \gettype($this->normalizer)));
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,10 @@ public function validate($value, Constraint $constraint)

$stringValue = (string) $value;

if (null !== $constraint->normalizer) {
$stringValue = ($constraint->normalizer)($stringValue);
}

if (!$invalidCharset = !@mb_check_encoding($stringValue, $constraint->charset)) {
$length = mb_strlen($stringValue, $constraint->charset);
}
Expand Down
11 changes: 11 additions & 0 deletions src/Symfony/Component/Validator/Constraints/NotBlank.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
namespace Symfony\Component\Validator\Constraints;

use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\Exception\InvalidArgumentException;

/**
* @Annotation
Expand All @@ -30,4 +31,14 @@ class NotBlank extends Constraint

public $message = 'This value should not be blank.';
public $allowNull = false;
public $normalizer;

public function __construct($options = null)
{
parent::__construct($options);

if (null !== $this->normalizer && !\is_callable($this->normalizer)) {
throw new InvalidArgumentException(sprintf('The "normalizer" option must be a valid callable ("%s" given).', \is_object($this->normalizer) ? \get_class($this->normalizer) : \gettype($this->normalizer)));
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,10 @@ public function validate($value, Constraint $constraint)
return;
}

if (\is_string($value) && null !== $constraint->normalizer) {
$value = ($constraint->normalizer)($value);
}

if (false === $value || (empty($value) && '0' != $value)) {
$this->context->buildViolation($constraint->message)
->setParameter('{{ value }}', $this->formatValue($value))
Expand Down
11 changes: 11 additions & 0 deletions src/Symfony/Component/Validator/Constraints/Regex.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
namespace Symfony\Component\Validator\Constraints;

use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\Exception\InvalidArgumentException;

/**
* @Annotation
Expand All @@ -31,6 +32,16 @@ class Regex extends Constraint
public $pattern;
public $htmlPattern;
public $match = true;
public $normalizer;

public function __construct($options = null)
{
parent::__construct($options);

if (null !== $this->normalizer && !\is_callable($this->normalizer)) {
throw new InvalidArgumentException(sprintf('The "normalizer" option must be a valid callable ("%s" given).', \is_object($this->normalizer) ? \get_class($this->normalizer) : \gettype($this->normalizer)));
}
}

/**
* {@inheritdoc}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,10 @@ public function validate($value, Constraint $constraint)

$value = (string) $value;

if (null !== $constraint->normalizer) {
$value = ($constraint->normalizer)($value);
}

if ($constraint->match xor preg_match($constraint->pattern, $value)) {
$this->context->buildViolation($constraint->message)
->setParameter('{{ value }}', $this->formatValue($value))
Expand Down
6 changes: 6 additions & 0 deletions src/Symfony/Component/Validator/Constraints/Url.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
namespace Symfony\Component\Validator\Constraints;

use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\Exception\InvalidArgumentException;

/**
* @Annotation
Expand Down Expand Up @@ -105,6 +106,7 @@ class Url extends Constraint
*/
public $checkDNS = self::CHECK_DNS_TYPE_NONE;
public $relativeProtocol = false;
public $normalizer;

public function __construct($options = null)
{
Expand All @@ -118,5 +120,9 @@ public function __construct($options = null)
}

parent::__construct($options);

if (null !== $this->normalizer && !\is_callable($this->normalizer)) {
throw new InvalidArgumentException(sprintf('The "normalizer" option must be a valid callable ("%s" given).', \is_object($this->normalizer) ? \get_class($this->normalizer) : \gettype($this->normalizer)));
}
}
}
4 changes: 4 additions & 0 deletions src/Symfony/Component/Validator/Constraints/UrlValidator.php
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,10 @@ public function validate($value, Constraint $constraint)
return;
}

if (null !== $constraint->normalizer) {
$value = ($constraint->normalizer)($value);
}

$pattern = $constraint->relativeProtocol ? str_replace('(%s):', '(?:(%s):)?', static::PATTERN) : static::PATTERN;
$pattern = sprintf($pattern, implode('|', $constraint->protocols));

Expand Down
12 changes: 12 additions & 0 deletions src/Symfony/Component/Validator/Constraints/Uuid.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
namespace Symfony\Component\Validator\Constraints;

use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\Exception\InvalidArgumentException;

/**
* @Annotation
Expand Down Expand Up @@ -74,4 +75,15 @@ class Uuid extends Constraint
self::V4_RANDOM,
self::V5_SHA1,
];

public $normalizer;

public function __construct($options = null)
{
parent::__construct($options);

if (null !== $this->normalizer && !\is_callable($this->normalizer)) {
throw new InvalidArgumentException(sprintf('The "normalizer" option must be a valid callable ("%s" given).', \is_object($this->normalizer) ? \get_class($this->normalizer) : \gettype($this->normalizer)));
}
}
}
4 changes: 4 additions & 0 deletions src/Symfony/Component/Validator/Constraints/UuidValidator.php
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,10 @@ public function validate($value, Constraint $constraint)

$value = (string) $value;

if (null !== $constraint->normalizer) {
$value = ($constraint->normalizer)($value);
}

if ($constraint->strict) {
$this->validateStrict($value, $constraint);

Expand Down
27 changes: 26 additions & 1 deletion src/Symfony/Component/Validator/Tests/Constraints/EmailTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -35,11 +35,36 @@ public function testConstructorStrict()
}

/**
* @expectedException \InvalidArgumentException
* @expectedException \Symfony\Component\Validator\Exception\InvalidArgumentException
* @expectedExceptionMessage The "mode" parameter value is not valid.
*/
public function testUnknownModesTriggerException()
{
new Email(['mode' => 'Unknown Mode']);
}

public function testNormalizerCanBeSet()
{
$email = new Email(['normalizer' => 'trim']);

$this->assertEquals('trim', $email->normalizer);
}

/**
* @expectedException \Symfony\Component\Validator\Exception\InvalidArgumentException
* @expectedExceptionMessage The "normalizer" option must be a valid callable ("string" given).
*/
public function testInvalidNormalizerThrowsException()
{
new Email(['normalizer' => 'Unknown Callable']);
}

/**
* @expectedException \Symfony\Component\Validator\Exception\InvalidArgumentException
* @expectedExceptionMessage The "normalizer" option must be a valid callable ("stdClass" given).
*/
public function testInvalidNormalizerObjectThrowsException()
{
new Email(['normalizer' => new \stdClass()]);
}
}
E89E
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,28 @@ public function getValidEmails()
];
}

/**
* @dataProvider getValidEmailsWithWhitespaces
*/
public function testValidNormalizedEmails($email)
{
$this->validator->validate($email, new Email(['normalizer' => 'trim']));

$this->assertNoViolation();
}

public function getValidEmailsWithWhitespaces()
{
return [
["\x20example@example.co.uk\x20"],
["\x09\x09example@example.co..uk\x09\x09"],
["\x0A{}~!@!@£$%%^&*().!@£$%^&*()\x0A"],
["\x0D\x0Dexample@example.co..uk\x0D\x0D"],
["\x00example@-example.com"],
["example@example.com\x0B\x0B"],
];
}

/**
* @dataProvider getValidEmailsHtml5
*/
Expand Down
46 changes: 46 additions & 0 deletions src/Symfony/Component/Validator/Tests/Constraints/IpTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
<?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 PHPUnit\Framework\TestCase;
use Symfony\Component\Validator\Constraints\Ip;

/**
* @author Renan Taranto <renantaranto@gmail.com>
*/
class IpTest extends TestCase
{
public function testNormalizerCanBeSet()
{
$ip = new Ip(['normalizer' => 'trim']);

$this->assertEquals('trim', $ip->normalizer);
}

/**
* @expectedException \Symfony\Component\Validator\Exception\InvalidArgumentException
* @expectedExceptionMessage The "normalizer" option must be a valid callable ("string" given).
*/
public function testInvalidNormalizerThrowsException()
{
new Ip(['normalizer' => 'Unknown Callable']);
}

/**
* @expectedException \Symfony\Component\Validator\Exception\InvalidArgumentException
* @expectedExceptionMessage The "normalizer" option must be a valid callable ("stdClass" given).
*/
public function testInvalidNormalizerObjectThrowsException()
{
new Ip(['normalizer' => new \stdClass()]);
}
}
Loading
0