Added Tests to DateInterval Type

parent 5b2a2dcf
......@@ -3,10 +3,54 @@
namespace Doctrine\DBAL\Types;
use Doctrine\DBAL\Platforms\AbstractPlatform;
/**
*
* Type that maps interval string to a PHP DateInterval Object.
*/
class DateIntervalType
class DateIntervalType extends Type
{
/**
* {@inheritdoc}
*/
public function getName()
{
return Type::DATEINTERVAL;
}
/**
* {@inheritdoc}
*/
public function getSQLDeclaration(array $fieldDeclaration, AbstractPlatform $platform)
{
return $platform->getVarcharTypeDeclarationSQL($fieldDeclaration);
}
/**
* {@inheritdoc}
*/
public function convertToDatabaseValue($value, AbstractPlatform $platform)
{
return ($value !== null)
? $value->format('P%yY%mM%dDT%hH%iM%sS') : null;
}
/**
* {@inheritdoc}
*/
public function convertToPHPValue($value, AbstractPlatform $platform)
{
if ($value === null || $value instanceof \DateInterval) {
return $value;
}
try {
$interval = new \DateInterval($value);
} catch (\Exception $e) {
throw ConversionException::conversionFailedFormat($value, $this->getName(), 'PxYxMxDTxHxMxS');
}
return $interval;
}
}
......@@ -52,6 +52,7 @@ abstract class Type
const BLOB = 'blob';
const FLOAT = 'float';
const GUID = 'guid';
const DATEINTERVAL = 'dateinterval';
/**
* Map of already instantiated type objects. One instance per type (flyweight).
......@@ -85,6 +86,7 @@ abstract class Type
self::BINARY => 'Doctrine\DBAL\Types\BinaryType',
self::BLOB => 'Doctrine\DBAL\Types\BlobType',
self::GUID => 'Doctrine\DBAL\Types\GuidType',
self::DATEINTERVAL => 'Doctrine\DBAL\Types\DateIntervalType',
);
/**
......
<?php
namespace Doctrine\Tests\DBAL\Types;
/**
*
*/
class DateIntervalTest
use Doctrine\DBAL\Types\Type;
use Doctrine\Tests\DBAL\Mocks\MockPlatform;
class DateIntervalTest extends \Doctrine\Tests\DbalTestCase
{
protected
$_platform,
$_type;
protected function setUp()
{
$this->_platform = new MockPlatform();
$this->_type = Type::getType('dateinterval');
}
public function testDateIntervalConvertsToDatabaseValue()
{
$interval = new \DateInterval('P1DT1H2M3S');
$expected = $interval->format('P%yY%mM%dDT%hH%iM%sS');
$actual = $this->_type->convertToDatabaseValue($interval, $this->_platform);
$this->assertEquals($expected, $actual);
}
public function testDateIntervalConvertsToPHPValue()
{
$date = $this->_type->convertToPHPValue('P1DT1H2M3S', $this->_platform);
$this->assertInstanceOf('DateInterval', $date);
$this->assertEquals('P0Y0M1DT1H2M3S', $date->format('P%yY%mM%dDT%hH%iM%sS'));
}
public function testInvalidDateIntervalFormatConversion()
{
$this->setExpectedException('Doctrine\DBAL\Types\ConversionException');
$this->_type->convertToPHPValue('abcdefg', $this->_platform);
}
public function testDateIntervalNullConversion()
{
$this->assertNull($this->_type->convertToPHPValue(null, $this->_platform));
}
}
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