vendor/sensio/framework-extra-bundle/src/Request/ParamConverter/DateTimeParamConverter.php line 30

Open in your IDE?
  1. <?php
  2. /*
  3.  * This file is part of the Symfony package.
  4.  *
  5.  * (c) Fabien Potencier <fabien@symfony.com>
  6.  *
  7.  * For the full copyright and license information, please view the LICENSE
  8.  * file that was distributed with this source code.
  9.  */
  10. namespace Sensio\Bundle\FrameworkExtraBundle\Request\ParamConverter;
  11. use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter;
  12. use Symfony\Component\HttpFoundation\Request;
  13. use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
  14. /**
  15.  * Convert DateTime instances from request attribute variable.
  16.  *
  17.  * @author Benjamin Eberlei <kontakt@beberlei.de>
  18.  */
  19. class DateTimeParamConverter implements ParamConverterInterface
  20. {
  21.     /**
  22.      * {@inheritdoc}
  23.      *
  24.      * @throws NotFoundHttpException When invalid date given
  25.      */
  26.     public function apply(Request $requestParamConverter $configuration)
  27.     {
  28.         $param $configuration->getName();
  29.         if (!$request->attributes->has($param)) {
  30.             return false;
  31.         }
  32.         $options $configuration->getOptions();
  33.         $value $request->attributes->get($param);
  34.         if (!$value && $configuration->isOptional()) {
  35.             $request->attributes->set($paramnull);
  36.             return true;
  37.         }
  38.         $class $configuration->getClass();
  39.         if (isset($options['format'])) {
  40.             $date $class::createFromFormat($options['format'], $value);
  41.             if (< \DateTime::getLastErrors()['warning_count']) {
  42.                 $date false;
  43.             }
  44.             if (!$date) {
  45.                 throw new NotFoundHttpException(sprintf('Invalid date given for parameter "%s".'$param));
  46.             }
  47.         } else {
  48.             if (false === strtotime($value)) {
  49.                 throw new NotFoundHttpException(sprintf('Invalid date given for parameter "%s".'$param));
  50.             }
  51.             $date = new $class($value);
  52.         }
  53.         $request->attributes->set($param$date);
  54.         return true;
  55.     }
  56.     /**
  57.      * {@inheritdoc}
  58.      */
  59.     public function supports(ParamConverter $configuration)
  60.     {
  61.         if (null === $configuration->getClass()) {
  62.             return false;
  63.         }
  64.         return 'DateTime' === $configuration->getClass() || is_subclass_of($configuration->getClass(), \PHP_VERSION_ID 50500 'DateTime' 'DateTimeInterface');
  65.     }
  66. }