Skip to content

Commit

Permalink
Add DateInterval DBAL type
Browse files Browse the repository at this point in the history
  • Loading branch information
merk committed Aug 23, 2016
1 parent a3aaed0 commit ce5d573
Show file tree
Hide file tree
Showing 2 changed files with 117 additions and 0 deletions.
56 changes: 56 additions & 0 deletions Date/IntervalFormatter.php
@@ -0,0 +1,56 @@
<?php

/**
* This file is part of the InfiniteCommonBundle project.
*
* (c) Infinite Networks Pty Ltd <http://www.infinite.net.au>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Infinite\CommonBundle\Date;

class IntervalFormatter
{
/**
* Formats a DateInterval as an IntervalSpec
*
* @param \DateInterval $interval
* @return string
*/
public static function formatDateInterval(\DateInterval $interval)
{
$spec = 'P';

if ($interval->y) {
$spec .= $interval->y . 'Y';
}

if ($interval->m) {
$spec .= $interval->m . 'M';
}

if ($interval->d) {
$spec .= $interval->d . 'D';
}

if ($interval->h || $interval->i || $interval->s) {
$spec .= 'T';

if ($interval->h) {
$spec .= $interval->h . 'H';
}

if ($interval->i) {
$spec .= $interval->i . 'M';
}

if ($interval->s) {
$spec .= $interval->s . 'S';
}
}

return $spec;
}
}
61 changes: 61 additions & 0 deletions Doctrine/Type/DateIntervalType.php
@@ -0,0 +1,61 @@
<?php

/**
* This file is part of the InfiniteCommonBundle project.
*
* (c) Infinite Networks Pty Ltd <http://www.infinite.net.au>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Infinite\CommonBundle\Doctrine\Type;

use Doctrine\DBAL\Platforms\AbstractPlatform;
use Doctrine\DBAL\Types\ConversionException;
use Doctrine\DBAL\Types\StringType;
use Infinite\CommonBundle\Date\IntervalFormatter;

class DateIntervalType extends StringType
{
const DATEINTERVAL = 'dateinterval';

/**
* @param \DateInterval $value
* @param AbstractPlatform $platform
* @return string
*/
public function convertToDatabaseValue($value, AbstractPlatform $platform)
{
return $value ? IntervalFormatter::formatDateInterval($value) : null;
}

/**
* @param string $value
* @param AbstractPlatform $platform
* @return \DateInterval
* @throws ConversionException
*/
public function convertToPHPValue($value, AbstractPlatform $platform)
{
if (null !== $value) {
try {
return new \DateInterval($value);
} catch (\Exception $e) {
throw ConversionException::conversionFailedFormat(
$value,
$this->getName(),
'IntervalSpec'
);
}

}

return $value;
}

public function getName()
{
return self::DATEINTERVAL;
}
}

0 comments on commit ce5d573

Please sign in to comment.