<?php
namespace App\Helpers;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Twig\Environment;
use Twig\Extension\CoreExtension;
use Twig\TwigFilter;
class DateTimeConverter
{
/** @var Environment */
private $twig;
public function __construct( Environment $twig = null)
{
if (null === ($this->twig = $twig)) {
throw new \Exception('You must have TwigBundle installed to use ' . self::class);
}
}
public function normalize($value, $outputFormat = null)
{
if (null === $value) {
return $this->options['nullValue'];
} elseif (!$value instanceof \DateTimeInterface) {
$value = new \DateTime((string) $value);
}
$filters = $this->twig->getExtension(CoreExtension::class)->getFilters();
$key = array_search('date', array_map(function(TwigFilter $filter) { return $filter->getName(); }, $filters), true);
$dateFilter = $filters[$key]->getCallable();
if (!empty($outputFormat)) {
$format = $outputFormat;
} elseif (empty($this->options['format'])) {
$format = null;
} else {
$format = $this->options['format'];
}
return $dateFilter($this->twig, $value, $format);
}
public function convertFERecord( array &$event, \DateTime $date )
{
if ( key_exists('date',$event) ) {
$event['date'] = $this->normalize($date, 'd-m-Y');
$event['time'] = (('12.00 am' != $date->format('g.i a'))?$this->normalize($date, 'g.i a'):'');
}
}
protected function configureOptions(OptionsResolver $resolver)
{
parent::configureOptions($resolver);
$resolver
->setDefaults([
'format' => '',
'nullValue' => '',
])
->setAllowedTypes('format', 'string')
->setAllowedTypes('nullValue', 'string')
;
return $this;
}
}