Jelajahi Sumber

merged branch ajessu/time_validator (PR #1254)

# 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:

https://github.com/symfony/symfony/pull/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)
Fabien Potencier 14 tahun lalu
induk
melakukan
a7c1ff8558

+ 4 - 0
src/Symfony/Component/Validator/Constraints/TimeValidator.php

@@ -25,6 +25,10 @@ class TimeValidator extends ConstraintValidator
             return true;
         }
 
+        if ($value instanceof \DateTime) {
+            return true;
+        }
+
         if (!is_scalar($value) && !(is_object($value) && method_exists($value, '__toString'))) {
             throw new UnexpectedTypeException($value, 'string');
         }

+ 5 - 0
tests/Symfony/Tests/Component/Validator/Constraints/DateValidatorTest.php

@@ -33,6 +33,11 @@ class DateValidatorTest extends \PHPUnit_Framework_TestCase
         $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');

+ 5 - 0
tests/Symfony/Tests/Component/Validator/Constraints/TimeValidatorTest.php

@@ -33,6 +33,11 @@ class TimeValidatorTest extends \PHPUnit_Framework_TestCase
         $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');