src/Helpers/DateTimeConverter.php line 54

Open in your IDE?
  1. <?php
  2. namespace App\Helpers;
  3. use Symfony\Component\OptionsResolver\OptionsResolver;
  4. use Twig\Environment;
  5. use Twig\Extension\CoreExtension;
  6. use Twig\TwigFilter;
  7. class DateTimeConverter
  8. {
  9.     /** @var Environment */
  10.     private $twig;
  11.     public function __constructEnvironment $twig null)
  12.     {
  13.         if (null === ($this->twig $twig)) {
  14.             throw new \Exception('You must have TwigBundle installed to use ' self::class);
  15.         }
  16.     }
  17.     public function normalize($value$outputFormat null)
  18.     {
  19.         if (null === $value) {
  20.             return $this->options['nullValue'];
  21.         } elseif (!$value instanceof \DateTimeInterface) {
  22.             $value = new \DateTime((string) $value);
  23.         }
  24.         $filters $this->twig->getExtension(CoreExtension::class)->getFilters();
  25.         $key array_search('date'array_map(function(TwigFilter $filter) { return $filter->getName(); }, $filters), true);
  26.         $dateFilter $filters[$key]->getCallable();
  27.         if (!empty($outputFormat)) {
  28.             $format $outputFormat;
  29.         } elseif (empty($this->options['format'])) {
  30.             $format null;
  31.         } else {
  32.             $format $this->options['format'];
  33.         }
  34.         return $dateFilter($this->twig$value$format);
  35.     }
  36.     public function convertFERecord( array &$event, \DateTime $date )
  37.     {
  38.         if ( key_exists('date',$event) ) {
  39.             $event['date'] = $this->normalize($date'd-m-Y');
  40.             $event['time'] = (('12.00 am' != $date->format('g.i a'))?$this->normalize($date'g.i a'):'');
  41.         }
  42.     }
  43.     protected function configureOptions(OptionsResolver $resolver)
  44.     {
  45.         parent::configureOptions($resolver);
  46.         $resolver
  47.             ->setDefaults([
  48.                 'format' => '',
  49.                 'nullValue' => '',
  50.             ])
  51.             ->setAllowedTypes('format''string')
  52.             ->setAllowedTypes('nullValue''string')
  53.         ;
  54.         return $this;
  55.     }
  56. }