Conditional SerializerGroup in FOSRESTBundle

I needed to conditionally add an entry to the list of active Serializer Group entries in a FOSRESTBundle controller action.

Here’s my attempt:

    /**
     * Get a single Widget.
     *
     * @Annotations\Get(path="/widget/{id}")
     *
     * @ApiDoc(
     *   output = "AppBundle\Entity\Widget",
     *   statusCodes = {
     *     200 = "Returned when successful",
     *     404 = "Returned when not found"
     *   }
     * )
     *
     * @param int         $id    the widget slug
     *
     * @Annotations\View(serializerGroups={
     *     "Default",
     *     "timestamps",
     *     "widgets_all",
     *     "feature_summary",
     *     "sprocket_summary"
     * })
     *
     * @return View
     */
    public function getAction(int $id, WidgetRepository $widgetRepository)
    {
        $widget = $widgetRepository->findOneById($id);

        if ($widget === null) {
            return new View(null, Response::HTTP_NOT_FOUND);
        }

        $view = $this->view($widget, Response::HTTP_OK);

        if ($this->isGranted(WidgetVoter::VIEW, $widget->getSprocket())) {
            $view->getContext()->addGroup('sprocket_all');
        }

        return $view;
    }

The idea behind this code is to that a Widget should show all of its information to all users.

It should show a summary of related features to all users.

It should show a summary of the related sprocket (one-to-one) to all users.

However, if you are logged in, you should see all the sprocket information, not just a summary.

It seems to work quite well in my use case. Gotta love them sprockets!