如何从 API 平台文档中隐藏路由 [英] How to hide a route from API Platform documentation
本文介绍了如何从 API 平台文档中隐藏路由的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用 Symfony4 下的 API 平台构建 API,
I'm building an API with API Platform under Symfony4,
我想在文档中隐藏一个实体,该实体仅可由打击的 ROLE_ADMIN 访问,而无需在文档中可见.
I want to hide an entity in the doc which is accessible only to the ROLE_ADMIN of the blow no interest to be visible in the doc.
这是我想隐藏的实体:
<?php
namespace App\Entity;
use ApiPlatform\Core\Annotation\ApiResource;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Serializer\Annotation\Groups;
/**
* @ApiResource(
* attributes={"access_control"="is_granted('ROLE_ADMIN')"}
* )
* @ORM\Entity(repositoryClass="App\Repository\OrderStatusRepository")
*/
class OrderStatus
{
/**
* @ORM\Id()
* @ORM\GeneratedValue()
* @ORM\Column(type="integer")
*/
private $id;
/**
* @ORM\Column(type="string", length=255)
* @Groups("orderGET")
*/
private $label;
/**
* @return int|null
*/
public function getId(): ?int
{
return $this->id;
}
/**
* @return null|string
*/
public function getLabel(): ?string
{
return $this->label;
}
/**
* @param string $label
* @return OrderStatus
*/
public function setLabel(string $label): self
{
$this->label = $label;
return $this;
}
}
感谢您的帮助
推荐答案
Symfony允许装饰服务,这里我们需要装饰api_platform.openapi.factory
Symfony allows to decorate services, here we need to decorate api_platform.openapi.factory
使用以下内容创建 src/OpenApi/OpenApiFactory.php
:
<?php
namespace App\OpenApi;
use ApiPlatform\Core\OpenApi\Factory\OpenApiFactoryInterface;
use ApiPlatform\Core\OpenApi\Model\PathItem;
use ApiPlatform\Core\OpenApi\OpenApi;
class OpenApiFactory implements OpenApiFactoryInterface
{
/**
* @var OpenApiFactoryInterface
*/
private $decorated;
public function __construct(OpenApiFactoryInterface $decorated)
{
$this->decorated = $decorated;
}
public function __invoke(array $context = []): OpenApi
{
$openApi = $this->decorated->__invoke($context);
/** @var PathItem $path */
foreach ($openApi->getPaths()->getPaths() as $key => $path) {
if ($path->getGet() && $path->getGet()->getSummary() === 'hidden') {
$openApi->getPaths()->addPath($key, $path->withGet(null));
}
}
return $openApi;
}
}
注册
services:
App\OpenApi\OpenApiFactory:
decorates: 'api_platform.openapi.factory'
arguments: ['@App\OpenApi\OpenApiFactory.inner']
autoconfigure: false
将 openapi_context
添加到要隐藏的每个路由
Add openapi_context
to each route you want to hide
* @ApiResource(
* itemOperations={
* "get"={
* ...
* "openapi_context"={
* "summary"="hidden"
* }
* }
* }
* )
这篇关于如何从 API 平台文档中隐藏路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文