10000 [Validator] Fixed time constraint (support formats H, H:i and H:i:s) by bes89 · Pull Request #9163 · symfony/symfony · GitHub
[go: up one dir, main page]

Skip to content

[Validator] Fixed time constraint (support formats H, H:i and H:i:s) #9163

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

Closed
wants to merge 5 commits into from
Closed
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
16 changes: 16 additions & 0 deletions src/Symfony/Component/Validator/Constraints/Time.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\InvalidConfigurationException;

/**
* @Annotation
Expand All @@ -21,4 +22,19 @@
class Time extends Constraint
{
public $message = 'This value is not a valid time.';
public $withMinutes = true;
public $withSeconds = true;

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

if (isset($options['withMinutes']) && !isset($options['withSeconds']) && $options['withMinutes'] == false) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should be with_minutes.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

if (isset($options['with_minutes']) && !isset($options['with_minutes']) && !$options['with_minutes']) { 

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more 10000 .

@stloyd Correct! But if we do so then we must also rename the properties e.g. protected $with_minutes; and that's not want we want to do.
We need something that converts option names to camelcased strings. How is this handled in other components?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In overall php variables are camelCased, while array keys are written with underscore.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

take a look into the base constraint class how options are set:
https://github.com/symfony/symfony/blob/master/src/Symfony/Component/Validator/Constraint.php#L98

if you pass an option named "with_minutes" it's value is not set for the property "withMinutes".

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In https://github.com/symfony/symfony/blob/master/src/Symfony/Component/Validator/Constraints/Length.php
The options are first passed to the parents constructor, and then the properties are checked.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Camel casing is fine here.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

it should be === false rather than == false

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

my own comment is not fixed though

$this->withSeconds = false;
}

if ($this->withSeconds && !$this->withMinutes) {
throw new InvalidConfigurationException('You can not disable minutes if you have enabled seconds.');
}
}
}
31 changes: 28 additions & 3 deletions src/Symfony/Component/Validator/Constraints/TimeValidator.php
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,6 @@
*/
class TimeValidator extends ConstraintValidator
{
const PATTERN = '/^(0[0-9]|1[0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9])$/';

/**
* {@inheritDoc}
*/
Expand All @@ -39,8 +37,35 @@ public function validate($value, Constraint $constraint)

$value = (string) $value;

if (!preg_match(static::PATTERN, $value)) {
$pattern = $this->getPattern($constraint->withMinutes, $constraint->withSeconds);

if (!preg_match($pattern, $value)) {
$this->context->addViolation($constraint->message, array('{{ value }}' => $value));
}
}

/**
* Returns the regex pattern for validating
*
* @param Boolean $withMinutes
* @param Boolean $withSeconds
* @return string
*/
protected function getPattern($withMinutes, $withSeconds)
{
// pattern for hours
$pattern = "(0[0-9]|1[0-9]|2[0-3])";
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

([01][0-9]|2[0-3])

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

hm... single digit hour value like 5:00 is not valid? We could add an option "allow_single_digit"?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

(?:[01]?\d|2[0-3])


if ($withMinutes) {
// pattern for minutes
$pattern .= "(:([0-5][0-9]))";
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

(?::([0-5][0-9]))

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why do we need the question mark here?
With a colon it creates a non-capturing group but the colon must be present, so it must be (?::([0-5][0-9]))

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yup, mistype. :)

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Moreover, looking at how the regex is captured, I Think every capturing group should be not capturing...


if ($withSeconds) {
// because the pattern for seconds is the same as that for minutes, we repeat it twice
$pattern .= "{2}";
}
}

return "/^".$pattern."$/";
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
<?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\Exception;

class InvalidConfigurationException extends InvalidArgumentException
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is useless, there is already: InvalidOptionsException.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The InvalidOptionsException is thrown when you pass the names of non-existing options.

{
}
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@

use Symfony\Component\Validator\Constraints\Time;
use Symfony\Component\Validator\Constraints\TimeValidator;
use Symfony\Component\Validator\Tests\Fixtures\InvalidConstraint;

class TimeValidatorTest extends \PHPUnit_Framework_TestCase
{
Expand All @@ -32,6 +33,17 @@ protected function tearDown()
$this->validator = null;
}

/**
* @expectedException \Symfony\Component\Validator\Exception\InvalidConfigurationException
*/
public function testThrowsExceptionIfConfigurationIsInvalid()
{
new Time(array(
'withMinutes' => false,
'withSeconds' => true,
));
}

public function testNullIsValid()
{
$this->context->expects($this->never())
Expand Down Expand Up @@ -84,6 +96,50 @@ public function getValidTimes()
);
}

/**
* @dataProvider getValidTimesWithoutMinutes
*/
public function testValidTimesWithoutMinutes($time)
{
$this->context->expects($this->never())
->method('addViolation');

$this->validator->validate($time, new Time(array(
'withMinutes' => false,
)));
}

public function getValidTimesWithoutMinutes()
{
return array(
array('01'),
array('00'),
array('23'),
);
}

/**
* @dataProvider getValidTimesWithoutSeconds
*/
public function testValidTimesWithoutSeconds($time)
{
$this->context->expects($this->never())
->method('addViolation');

$this->validator->validate($time, new Time(array(
'withSeconds' => false,
)));
}

public function getValidTimesWithoutSeconds()
{
return array(
array('01:02'),
array('00:00'),
array('23:59'),
);
}

/**
* @dataProvider getInvalidTimes
*/
Expand Down Expand Up @@ -114,4 +170,65 @@ public function getInvalidTimes()
array('00:00:60'),
);
}

/**
* @dataProvider getInvalidTimesWithoutMinutes
*/
public function testInvalidTimesWithoutMinutes($time)
{
$constraint = new Time(array(
'message' => 'myMessage',
'withMinutes' => false,
));

$this->context->expects($this->once())
->method('addViolation')
->with('myMessage', array(
'{{ value }}' => $time,
));

$this->validator->validate($time, $constraint);
}

public function getInvalidTimesWithoutMinutes()
{
return array(
array('foobar'),
array('foobar 12'),
array('12 foobar'),
array('24'),
array('60'),
);
}

/**
* @dataProvider getInvalidTimesWithoutSeconds
*/
public function testInvalidTimesWithoutSeconds($time)
{
$constraint = new Time(array(
'message' => 'myMessage',
'withSeconds' => false,
));

$this->context->expects($this->once())
->method('addViolation')
->with('myMessage', array(
'{{ value }}' => $time,
));

$this->validator->validate($time, $constraint);
}

public function getInvalidTimesWithoutSeconds()
{
return array(
array('foobar'),
array('foobar 12:34'),
array('12:34 foobar'),
array('01:02:03'),
array('24:00'),
array('00:60'),
);
}
}
0