Skip to content
This repository has been archived by the owner on Feb 4, 2023. It is now read-only.

Locale aware for datefilter #640

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Changes from 3 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
50 changes: 45 additions & 5 deletions Datatable/Filter/DateRangeFilter.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,10 @@

namespace Sg\DatatablesBundle\Datatable\Filter;

use Doctrine\ORM\QueryBuilder;
use Doctrine\ORM\Query\Expr\Andx;
use DateTime;
use Doctrine\ORM\Query\Expr\Andx;
use Doctrine\ORM\QueryBuilder;
use \IntlDateFormatter;
use Symfony\Component\OptionsResolver\OptionsResolver;

/**
Expand All @@ -23,6 +24,8 @@
*/
class DateRangeFilter extends AbstractFilter
{
protected $locale;

//-------------------------------------------------
// FilterInterface
//-------------------------------------------------
Expand All @@ -41,8 +44,8 @@ public function getTemplate()
public function addAndExpression(Andx $andExpr, QueryBuilder $qb, $searchField, $searchValue, &$parameterCounter)
{
list($_dateStart, $_dateEnd) = explode(' - ', $searchValue);
$dateStart = new DateTime($_dateStart);
$dateEnd = new DateTime($_dateEnd);
$dateStart = $this->getDateTime($_dateStart);
$dateEnd = $this->getDateTime($_dateEnd);
$dateEnd->setTime(23, 59, 59);

$andExpr = $this->getBetweenAndExpression($andExpr, $qb, $searchField, $dateStart->format('Y-m-d H:i:s'), $dateEnd->format('Y-m-d H:i:s'), $parameterCounter);
Expand All @@ -51,6 +54,41 @@ public function addAndExpression(Andx $andExpr, QueryBuilder $qb, $searchField,
return $andExpr;
}

/**
* @param string $date
* @return DateTime
*/
protected function getDateTime($date)
nicodmf marked this conversation as resolved.
Show resolved Hide resolved
{
$dateFormatter = IntlDateFormatter::create(
$this->locale,
IntlDateFormatter::SHORT,
IntlDateFormatter::NONE
);
$timestamp = $dateFormatter->parse($date);

return new \DateTime('@' . $timestamp);
}

/**
* @return string
*/
public function getLocale()
{
return $this->locale;
}

/**
* @param string $locale
* @return $this
*/
public function setLocale($locale)
{
$this->locale = $locale;

return $this;
}

//-------------------------------------------------
// Options
//-------------------------------------------------
Expand All @@ -65,7 +103,9 @@ public function addAndExpression(Andx $andExpr, QueryBuilder $qb, $searchField,
public function configureOptions(OptionsResolver $resolver)
{
parent::configureOptions($resolver);


$resolver->setDefault('locale', 'en');
$resolver->setAllowedTypes('locale', 'string');
$resolver->remove('search_type');

return $this;
Expand Down