您应该按照此处所述进行操作。
您还应该使用 Symfony 安全组件实现角色检查,以决定是否显示端点。
<?php
namespace App\OpenApi;
use ApiPlatform\Core\OpenApi\Factory\OpenApiFactoryInterface;
use ApiPlatform\Core\OpenApi\Model\PathItem;
use ApiPlatform\Core\OpenApi\OpenApi;
use Symfony\Component\Security\Core\Security;
class OpenApiFactory implements OpenApiFactoryInterface
{
public function __construct(
private readonly OpenApiFactoryInterface $decorated
private readonly Security $security
) {
}
public function __invoke(array $context = []): OpenApi
{
$openApi = $this->decorated->__invoke($context);
/** @var PathItem $path */
foreach ($openApi->getPaths()->getPaths() as $key => $path) {
if ($this->security->isGranted('ROLE_USER')) {
// Add logic to hide or modify the path for non-admin users
}
}
return $openApi;
}
}