FOSRestBundle: partial response in function of attributes asked in the request
My implementation based on Igor's answer:
ExlusionStrategy:
use JMS\Serializer\Exclusion\ExclusionStrategyInterface;use JMS\Serializer\Metadata\ClassMetadata;use JMS\Serializer\Metadata\PropertyMetadata;use JMS\Serializer\Context;class FieldsExclusionStrategy implements ExclusionStrategyInterface { private $fields = array(); public function __construct(array $fields) { $this->fields = $fields; } public function shouldSkipClass(ClassMetadata $metadata, Context $navigatorContext) { return false; } public function shouldSkipProperty(PropertyMetadata $property, Context $navigatorContext) { if (empty($this->fields)) { return false; } if (in_array($property->name, $this->fields)) { return false; } return true; }}
Controller:
/** * @View * @QueryParam(name="fields") * * GET /users/{id} * * @param integer $user (uses ParamConverter) */public function getUserAction(User $user, $fields) { $context = new SerializationContext(); $context->addExclusionStrategy(new FieldsExclusionStrategy($fields ? explode(',', $fields) : array())); return $this->handleView($this->view($user)->setSerializationContext($context));}
Endpoint:
GET /users/{id}?fields=id,username,sex
You can do it like that through groups, as you've shown. Maybe a bit more elegant solution would be to implement your own ExclusionStrategy. @Groups and other are implementations of ExclusionStrategyInterface too.
So, say you called your strategy SelectFieldsStrategy. Once you implement it, you can add it to your serialization context very easy:
$context = new SerializationContext();$context->addExclusionStrategy(new SelectFieldsStrategy(['id', 'name', 'someotherfield']));