Skip to content

Instantly share code, notes, and snippets.

@xphere
Created October 16, 2013 08:29
Show Gist options
  • Save xphere/7004483 to your computer and use it in GitHub Desktop.
Save xphere/7004483 to your computer and use it in GitHub Desktop.
Makes data in `$request->request` accessible for other ParamConverters like `DoctrineParamConverter`. Just use the `from` option in your annotations, like in the example.
use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter;
class ExampleController
{
/**
* @ParamConverter("user", {"from" = "id"})
*/
public function exampleAction(User $user)
{
// …
}
}
<?php
use Sensio\Bundle\FrameworkExtraBundle\Configuration\ConfigurationInterface;
use Sensio\Bundle\FrameworkExtraBundle\Configuration as Annotation;
use Sensio\Bundle\FrameworkExtraBundle\Request\ParamConverter\ParamConverterInterface;
use Symfony\Component\HttpFoundation\Request;
class PostParamConverter implements ParamConverterInterface
{
public function apply(Request $request, ConfigurationInterface $configuration)
{
if (!$this->supports($configuration) || !$this->supportsRequest($request)) {
return;
}
$options = $this->getOptions($configuration);
$name = $configuration->getName();
if (null === $request->attributes->get($name, false)) {
$configuration->setIsOptional(true);
}
$value = $request->request->get($options['from'], null);
if ($value === null && !$configuration->isOptional()) {
throw new \LogicException('Unable to guess how to get a Post instance from the request information.');
}
$name = isset($options['id']) ? $options['id'] : $configuration->getName();
$request->attributes->set($name, $value);
}
public function supports(ConfigurationInterface $configuration)
{
return $configuration instanceof Annotation\ParamConverter && $this->supportOptions($configuration);
}
protected function supportOptions(Annotation\ParamConverter $configuration)
{
$options = $configuration->getOptions();
return isset($options['from']);
}
protected function supportsRequest(Request $request)
{
return 'GET' !== $request->getMethod();
}
protected function getOptions(Annotation\ParamConverter $configuration)
{
return $configuration->getOptions();
}
}
service.param_converter.post:
class: PostParamConverter
tags:
- { name: request.param_converter, priority: 10 } # Higher priority than DoctrineParamConverter
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment