Symfony RestBundle:@View注释在v2升级后停止工作

时间:2018-06-04 08:20:32

标签: php symfony fosrestbundle jmsserializerbundle symfony-3.4

我认为JMS序列化程序和FOSRestBundle之间存在冲突:我得到一个空的json对象而不是id和accessToken。 我错过了一些v2文档吗?

config.yml

fos_rest:
    routing_loader:
        default_format: json
        include_format: false
    format_listener: true
    view:
        view_response_listener: 'force'
        formats:
            json: true
        templating_formats:
            html: false
            json: false
    body_converter:
        enabled: true

控制器

class SecurityController extends FOSRestController
{
     *
     * @View(serializerGroups={"login"})
     *
     */
    public function postLoginAction(Request $request)
    {
            // $user = MyOAuthUserResponse extends AbstractUserResponse

           // before upgrade I just use: return $this->view($user);

            $view = $this->view($user);

            $context = new Context();
            $context->addGroup('login');

            $view->setContext($context);

            return $this->handleView($view);
    }

实体

/**
 * @Serializer\ExclusionPolicy("All")
 */
class User extends BaseUser
{

    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     * @Serializer\Expose()
     */
    protected $id;

    /**
     * @var \DateTime
     *
     * @ORM\Column(name="created", type="datetime")
     * @Gedmo\Timestampable(on="create")
     */
    private $created;

    /**
     * @var string
     * @ORM\Column(type="string", nullable=true)
     * @Serializer\Expose()
     */
    private $accessToken;

1 个答案:

答案 0 :(得分:1)

它找到了问题!

vendor/jms/serializer/src/JMS/Serializer/GraphNavigator.php:209

$exclusionStrategy = $context->getExclusionStrategy(); // Returns NULL

这似乎在(升级之前)工作正常:

return $this->view($user);

但是,自$ exclusionStrategy升级后返回:

JMS\Serializer\Exclusion\GroupsExclusionStrategy Object
(
    [groups:JMS\Serializer\Exclusion\GroupsExclusionStrategy:private] => Array
        (
            [login] => 1
        )

    [nestedGroups:JMS\Serializer\Exclusion\GroupsExclusionStrategy:private] => 

为了解决这个问题,我删除了传递给视图的上下文代码,并将view传递给handleview,如:

return $this->handleView($this->view($user));

我被这个upgrade doc弄错了:

use FOS\RestBundle\Context\Context;

$view = new View();

$context = new Context();
$view->setContext($context);

$context = $view->getContext();