【问题标题】:Symfony RestBundle: @View annotation stopped working after v2 upgradeSymfony RestBundle:@View 注释在 v2 升级后停止工作
【发布时间】:2018-06-04 08:20:32
【问题描述】:

我认为 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;

【问题讨论】:

  • 没有错误/警告等? Symfony 认为一切都很棒?
  • 没有错误:只是空的 json 对象。

标签: php symfony fosrestbundle jmsserializerbundle symfony-3.4


【解决方案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();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-14
    • 2019-08-11
    • 2021-07-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多