Skip to content

Commit

Permalink
merged branch ajessu/time_validator (PR #1254)
Browse files Browse the repository at this point in the history
# Commits

ca52a04 [Validator] Allow DateTime objects as valid Times

# Discussion

## [Validator] Allow DateTime objects as valid Times

Also added tests for `DateTime` objects as valid on `Date` and `Time` constraints.

I didn't include the test for the `DateTime` constraint, as it's already included in this PR:

#1085

---------------------------------------------------------------------------

## fabpot @ 2011/06/09 09:07:21 -0700

I don't think it makes sense to use a \DateTime instance to represent a Time.

---------------------------------------------------------------------------

## ajessu @ 2011/06/09 09:33:20 -0700

If I have an entity with a doctrine type `Time`:

    Time (DateTime instance where only H:i:s get persisted)

```php
<?php
    /**
     * @Orm\Column(type="time")
     * @Assert\Time()
     */
    protected $startTime;
```

and I create a form out of this Entity, a `DateTime` object is passed when the form is submitted.

This generates an `UnexpectedTypeException`.

I just made this change to match the `Date` validator with the doctrine type `Date`, which also shares this behavior:
https://github.com/symfony/symfony/blob/master/src/Symfony/Component/Validator/Constraints/DateValidator.php#L28

    Date (DateTime instance where only Y-m-d get persisted)
  • Loading branch information
fabpot committed Jun 14, 2011
2 parents 87ca9f3 + ca52a04 commit a7c1ff8
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 0 deletions.
4 changes: 4 additions & 0 deletions src/Symfony/Component/Validator/Constraints/TimeValidator.php
Expand Up @@ -25,6 +25,10 @@ public function isValid($value, Constraint $constraint)
return true;
}

if ($value instanceof \DateTime) {
return true;
}

if (!is_scalar($value) && !(is_object($value) && method_exists($value, '__toString'))) {
throw new UnexpectedTypeException($value, 'string');
}
Expand Down
Expand Up @@ -33,6 +33,11 @@ public function testEmptyStringIsValid()
$this->assertTrue($this->validator->isValid('', new Date()));
}

public function testDateTimeClassIsValid()
{
$this->validator->isValid(new \DateTime(), new Date());
}

public function testExpectsStringCompatibleType()
{
$this->setExpectedException('Symfony\Component\Validator\Exception\UnexpectedTypeException');
Expand Down
Expand Up @@ -33,6 +33,11 @@ public function testEmptyStringIsValid()
$this->assertTrue($this->validator->isValid('', new Time()));
}

public function testDateTimeClassIsValid()
{
$this->validator->isValid(new \DateTime(), new Time());
}

public function testExpectsStringCompatibleType()
{
$this->setExpectedException('Symfony\Component\Validator\Exception\UnexpectedTypeException');
Expand Down

0 comments on commit a7c1ff8

Please sign in to comment.