我正在 Symfony 4 下使用 API Platform 构建 API,
我想隐藏文档中的一个实体,该实体只能由打击的 ROLE_ADMIN 访问,没有兴趣在文档中可见。
这是我要隐藏的实体:
<?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
Create 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
Add openapi_context
到您想要隐藏的每条路线
* @ApiResource(
* itemOperations={
* "get"={
* ...
* "openapi_context"={
* "summary"="hidden"
* }
* }
* }
* )
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)