Unverified Commit ff369310 authored by Luis Galeas's avatar Luis Galeas Committed by Sergei Morozov

DateIntervalType (negative support) resolves doctrine/dbal#2578

parent 16937314
......@@ -9,6 +9,8 @@ use Doctrine\DBAL\Platforms\AbstractPlatform;
*/
class DateIntervalType extends Type
{
const FORMAT = '%RP%YY%MM%DDT%HH%IM%SS';
/**
* {@inheritdoc}
*/
......@@ -38,7 +40,7 @@ class DateIntervalType extends Type
}
if ($value instanceof \DateInterval) {
return $value->format('P%YY%MM%DDT%HH%IM%SS');
return $value->format(self::FORMAT);
}
throw ConversionException::conversionFailedInvalidType($value, $this->getName(), ['null', 'DateInterval']);
......@@ -54,9 +56,15 @@ class DateIntervalType extends Type
}
try {
return new \DateInterval($value);
$interval = new \DateInterval(substr($value, 1));
if (substr($value, 0, 1) === '-') {
$interval->invert = 1;
}
return $interval;
} catch (\Exception $exception) {
throw ConversionException::conversionFailedFormat($value, $this->getName(), 'P%YY%MM%DDT%HH%IM%SS', $exception);
throw ConversionException::conversionFailedFormat($value, $this->getName(), self::FORMAT, $exception);
}
}
......
......@@ -32,7 +32,7 @@ class DateIntervalTest extends \Doctrine\Tests\DbalTestCase
{
$interval = new \DateInterval('P2Y1DT1H2M3S');
$expected = 'P02Y00M01DT01H02M03S';
$expected = '+P02Y00M01DT01H02M03S';
$actual = $this->type->convertToDatabaseValue($interval, $this->platform);
self::assertEquals($expected, $actual);
......@@ -40,9 +40,29 @@ class DateIntervalTest extends \Doctrine\Tests\DbalTestCase
public function testDateIntervalConvertsToPHPValue()
{
$date = $this->type->convertToPHPValue('P02Y00M01DT01H02M03S', $this->platform);
self::assertInstanceOf('DateInterval', $date);
self::assertEquals('P02Y00M01DT01H02M03S', $date->format('P%YY%MM%DDT%HH%IM%SS'));
$interval = $this->type->convertToPHPValue('+P02Y00M01DT01H02M03S', $this->platform);
self::assertInstanceOf('DateInterval', $interval);
self::assertEquals('+P02Y00M01DT01H02M03S', $interval->format('%RP%YY%MM%DDT%HH%IM%SS'));
}
public function testNegativeDateIntervalConvertsToDatabaseValue()
{
$interval = new \DateInterval('P2Y1DT1H2M3S');
$interval->invert = 1;
$expected = '-P02Y00M01DT01H02M03S';
$actual = $this->type->convertToDatabaseValue($interval, $this->platform);
self::assertEquals($expected, $actual);
}
public function testNegativeDateIntervalConvertsToPHPValue()
{
$interval = $this->type->convertToPHPValue('-P02Y00M01DT01H02M03S', $this->platform);
self::assertInstanceOf('DateInterval', $interval);
self::assertEquals('-P02Y00M01DT01H02M03S', $interval->format('%RP%YY%MM%DDT%HH%IM%SS'));
}
public function testInvalidDateIntervalFormatConversion()
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment