收集操作的额外数据 [英] Extra data on a collection operation

查看:35
本文介绍了收集操作的额外数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人知道如何在集合中添加额外数据吗?该文档对 如何添加说了很多项目上的额外数据,它转化为装饰 ItemNormalizer 服务,而且效果很好.

Does anybody know how to add extra data on a collection? The doc says much about how to add extra data on an item which translates into decorating the ItemNormalizer service, and it works pretty well.

但是当涉及到在实体集合上添加一些数据时,我正在努力找出要装饰的规范化器.额外的数据可以是任何东西:当前登录的用户、详细的寻呼机、一些调试参数,......与特定实体无关,而是与请求本身有关.

But I’m struggling in finding out which normalizer to decorate when it comes to add some data on a collection of entities. The extra data could be anything: the current user logged in, a detailed pager, some debug parameters, ... that are not related to a specific entity, but rather on the request itself.

目前唯一可行的解​​决方案是挂钩内核事件,但这绝对不是我喜欢编写的代码:

The only working solution for now is to hook on a Kernel event but that's definitely not the code I like to write:

use ApiPlatform\Core\EventListener\EventPriorities;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\GetResponseForControllerResultEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\Security\Core\Security;
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;

final class SerializeListener implements EventSubscriberInterface
{
    /**
     * @var Security
     */
    private $security;

    /**
     * @var NormalizerInterface
     */
    private $normalizer;

    public function __construct(
        Security $security,
        NormalizerInterface $normalizer
    ) {
        $this->security = $security;
        $this->normalizer = $normalizer;
    }

    public function addCurrentUser(GetResponseForControllerResultEvent $event)
    {
        $request = $event->getRequest();
        if ($request->attributes->has('_api_respond')) {
            $serialized = $event->getControllerResult();
            $data = json_decode($serialized, true);
            $data['hydra:user'] = $this->normalizer->normalize(
                $this->security->getUser(),
                $request->attributes->get('_format'),
                $request->attributes->get('_api_normalization_context')
            );
            $event->setControllerResult(json_encode($data));
        }
    }

    /**
     * @inheritDoc
     */
    public static function getSubscribedEvents()
    {
        return [
            KernelEvents::VIEW => [
                'addCurrentUser', 
                EventPriorities::POST_SERIALIZE,
            ],
        ];
    }

}

有什么想法吗?

谢谢,本

推荐答案

好吧,我终于做到了.

namespace App\Api;

use Symfony\Component\Serializer\Normalizer\NormalizerAwareInterface;
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;

final class ApiCollectionNormalizer implements NormalizerInterface, NormalizerAwareInterface
{
    /**
     * @var NormalizerInterface|NormalizerAwareInterface
     */
    private $decorated;

    public function __construct(NormalizerInterface $decorated)
    {
        if (!$decorated instanceof NormalizerAwareInterface) {
            throw new \InvalidArgumentException(
                sprintf('The decorated normalizer must implement the %s.', NormalizerAwareInterface::class)
            );
        }
        $this->decorated = $decorated;
    }

    /**
     * @inheritdoc
     */
    public function normalize($object, $format = null, array $context = [])
    {

        $data = $this->decorated->normalize($object, $format, $context);
        if ('collection' === $context['operation_type'] && 'get' === $context['collection_operation_name']) {
            $data['hydra:meta'] = ['foo' => 'bar'];
        }
        return $data;
    }

    /**
     * @inheritdoc
     */
    public function supportsNormalization($data, $format = null)
    {
        return $this->decorated->supportsNormalization($data, $format);
    }

    /**
     * @inheritdoc
     */
    public function setNormalizer(NormalizerInterface $normalizer)
    {
        $this->decorated->setNormalizer($normalizer);
    }

}

# config/services.yaml
services:
    App\Api\ApiCollectionNormalizer:
        decorates: 'api_platform.hydra.normalizer.collection'
        arguments: [ '@App\Api\ApiCollectionNormalizer.inner' ]

留作记录:)

这篇关于收集操作的额外数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆