Skip to content

Instantly share code, notes, and snippets.

@beberlei
Created August 15, 2011 17:53
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save beberlei/1147310 to your computer and use it in GitHub Desktop.
Save beberlei/1147310 to your computer and use it in GitHub Desktop.
DateTime converter
<?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