Created
August 15, 2011 17:53
-
-
Save beberlei/1147310 to your computer and use it in GitHub Desktop.
DateTime converter
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
use Sensio\Bundle\FrameworkExtraBundle\Request\ParamConverter\ParamConverterInterface; | |
use Sensio\Bundle\FrameworkExtraBundle\Configuration\ConfigurationInterface; | |
use Symfony\Component\HttpFoundation\Request; | |
/** | |
* Convert a date from the request to a DateTime instance. | |
* | |
* The semantics are controller semantics $varDate matches to a route parameter {var} | |
*/ | |
class DateTimeConverter implements ParamConverterInterface | |
{ | |
/** | |
* @param Request $request | |
* @param ConfigurationInterface $configuration | |
*/ | |
public function apply(Request $request, ConfigurationInterface $configuration) | |
{ | |
$varName = $configuration->getName(); | |
if ($request->attributes->has($varName) && !($value = $request->attributes->get($varName)) instanceof \DateTime) { | |
try { | |
$options = $configuration->getOptions(); | |
if (isset($options['format'])) { | |
$date = \DateTime::createFromFormat($options['format'], $value); | |
} else { | |
$date = new \DateTime($value); | |
} | |
} catch(\Exception $e) { | |
if (!$configuration->isOptional()) { | |
throw new \InvalidArgumentException("Invalid date given."); | |
} | |
$date = null; | |
} | |
$request->attributes->set($varName, $date); | |
} | |
} | |
/** | |
* @param ConfigurationInterface $configuration | |
* @return bool | |
*/ | |
public function supports(ConfigurationInterface $configuration) | |
{ | |
return $configuration->getClass() == 'DateTime'; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment