有关收集操作的额外数据

时间:2018-10-23 10:30:15

标签: api-platform.com

有人知道如何在集合上添加额外的数据吗? 该文档对how to add extra data on an item说了很多,转化为装饰ItemNormalizer服务,并且效果很好。

但是,我很难找到要在实体集合上添加一些数据的装饰器。多余的数据可以是任何东西:当前用户登录,详细的寻呼机,一些调试参数……与特定实体无关,而是与请求本身有关。

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

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,
            ],
        ];
    }

}

有什么想法吗?

谢谢你, 本

1 个答案:

答案 0 :(得分:1)

好吧,我终于做到了。

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' ]

保留记录:)