Skip to content

Reverse DateTimeToStringTransformer must use format #1183

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
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
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,12 @@ public function reverseTransform($value)
}

try {
$dateTime = new \DateTime(sprintf("%s %s", $value, $this->outputTimezone));
$dateTime = \DateTime::createFromFormat($this->format, $value, new \DateTimeZone($this->outputTimezone));
$errors = \DateTime::getLastErrors();
if ($errors['warning_count'] > 0 || $errors['error_count'] > 0) {
throw new \Exception('Date is invalid. List of warnings: "' . implode(', "',array_values($errors['warnings'])) . '" ' .
'List of errors: "' . implode(', "',array_values($errors['errors'])) . '"');
}

if ($this->inputTimezone !== $this->outputTimezone) {
$dateTime->setTimeZone(new \DateTimeZone($this->inputTimezone));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,18 @@ public function testTransformExpectsDateTime()

$transformer->transform('1234');
}

public function testTransformOtherFormat()
{
$transformer = new DateTimeToStringTransformer('UTC', 'UTC', 'd/m/Y H:i:s');

$input = new \DateTime('2010-02-03 04:05:06 UTC');
$output = clone $input;
$output->setTimezone(new \DateTimeZone('UTC'));
$output = $output->format('d/m/Y H:i:s');

$this->assertEquals($output, $transformer->transform($input));
}

public function testReverseTransform()
{
Expand Down Expand Up @@ -101,4 +113,23 @@ public function testReverseTransformExpectsValidDateString()

$reverseTransformer->reverseTransform('2010-2010-2010', null);
}

public function testReverseTransformOtherFormat()
{
$reverseTransformer = new DateTimeToStringTransformer('UTC', 'UTC', 'd/m/Y H:i:s');

$output = new \DateTime('2010-02-03 04:05:06 UTC');
$input = '03/02/2010 04:05:06';

$this->assertDateTimeEquals($output, $reverseTransformer->reverseTransform($input));
}

public function testReverseTransformExpectsDateExists()
{
$reverseTransformer = new DateTimeToStringTransformer('UTC', 'UTC', 'Y-m-d H:i:s');

$this->setExpectedException('Symfony\Component\Form\Exception\TransformationFailedException');

$reverseTransformer->reverseTransform('2011-02-29 04:05:06', null);
}
}