使用Symfony / API平台提供验证组上下文

问题描述 投票:2回答:1

正如我在标题中所说,我尝试提供Sf / Api平台的验证上下文。

更确切地说,我希望根据实体值使用不同的验证组。

如果我是带有UserROLE_PRO:那么我想要validate:prodefault作为验证组。

如果我是带有UserROLE_USER:那么我想要default作为验证组。

我尝试根据以下api平台事件创建事件,但找不到为验证组提供ExecutionContextInterface的方法

public static function getSubscribedEvents()
{
     return [
          KernelEvents::VIEW => ['addGroups', EventPriorities::PRE_VALIDATE],
     ];
}
symfony api-platform.com
1个回答
0
投票

您可以在api平台文档(https://api-platform.com/docs/core/serialization/#changing-the-serialization-context-dynamically)中看到,您可以使用服务动态地操作验证组。

首先,在api-platform配置中,您必须定义默认验证组:

App\Class\MyClass:
  properties:
    id:
      identifier: true
  attributes:
    input: false
    normalization_context:
      groups: ['default']

您需要定义一个实现SerializerContextBuilderInterface的新服务>

class ContextBuilder implements SerializerContextBuilderInterface
{
    private SerializerContextBuilderInterface $decorated;
    private AuthorizationCheckerInterface $authorizationChecker;

    public function __construct(SerializerContextBuilderInterface $decorated, AuthorizationCheckerInterface $authorizationChecker)
    {
        $this->decorated = $decorated;
        $this->authorizationChecker = $authorizationChecker;
    }

    public function createFromRequest(Request $request, bool $normalization, ?array $extractedAttributes = null): array
    {
        $context = $this->decorated->createFromRequest($request, $normalization, $extractedAttributes);

        if (isset($context['groups']) && $this->authorizationChecker->isGranted('ROLE_PRO') && true === $normalization) {
            $context['groups'][] = 'validate:pro';
        }
        return $context;
    }
}

此外,您需要使用装饰器配置新服务

App\Builder\ContextBuilder:
        decorates: 'api_platform.serializer.context_builder'
        arguments: [ '@App\Builder\ContextBuilder.inner' ]

这里正在发生的事情:

您正在重写ContextBuilder。首先,您从请求和配置中创建上下文(createFromRequest方法的第一行),然后,您将修改记录用户身份的上下文。

谢谢!

© www.soinside.com 2019 - 2024. All rights reserved.