API-Platform 将生成 Swagger/OpenAPI 路由文档,然后生成下面的模式文档(又名模型)(文档将它们显示为“模型”,但当前版本(例如 2.7)将它们显示为“模式”)。
生成的显示这些模式/模型的内容在哪里?有的怎么去掉呢?显示它们的功能是 Swagger-UI 的一部分,但 API-Platform 必须负责提供 JSON 配置,从而更改 API-Platform 而不是 Swagger-UI。请注意,这篇文章展示了如何添加架构,但没有展示如何删除架构。除了this之外,还有关于该主题的任何文档没有详细介绍吗?
从下面的输出中可以看出,我公开了
AbstractOrganization
,但是,该类由其他几个类扩展,并不意味着要公开,而只应公开具体类的模式。请注意,我的 AbstractOrganization
实体类未标记为 @ApiResource
,并且未显示在 Swagger/OpenAPI 路由文档中,而仅显示在架构/模型文档中。
谢谢你
我非常确定有更好的方法来实现这一点,但是,以下内容将会起作用,并且可能对其他人有帮助。
<?php
declare(strict_types=1);
namespace App\OpenApi;
use ApiPlatform\Core\OpenApi\Factory\OpenApiFactoryInterface;
use ApiPlatform\Core\OpenApi\OpenApi;
use ApiPlatform\Core\OpenApi\Model\Paths;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
class OpenApiRouteHider implements OpenApiFactoryInterface {
public function __construct(private OpenApiFactoryInterface $decorated, private TokenStorageInterface $tokenStorage)
{
}
public function __invoke(array $context = []): OpenApi
{
$openApi = $this->decorated->__invoke($context);
$removedPaths = $this->getRemovedPaths();
$paths = new Paths;
$pathArray = $openApi->getPaths()->getPaths();
foreach($openApi->getPaths()->getPaths() as $path=>$pathItem) {
if(!isset($removedPaths[$path])) {
// No restrictions
$paths->addPath($path, $pathItem);
}
elseif($removedPaths[$path]!=='*') {
// Remove one or more operation
foreach($removedPaths[$path] as $operation) {
$method = 'with'.ucFirst($operation);
$pathItem = $pathItem->$method(null);
}
$paths->addPath($path, $pathItem);
}
// else don't add this route to the documentation
}
$openApiTest = $openApi->withPaths($paths);
return $openApi->withPaths($paths);
}
private function getRemovedPaths():array
{
// Use $user to determine which ones to remove.
$user = $this->tokenStorage->getToken()->getUser();
return [
'/guids'=>'*', // Remove all operations
'/guids/{guid}'=>'*', // Remove all operations
'/tenants'=>['post', 'get'], // Remove only post and get operations
'/tenants/{uuid}'=>['delete'], // Remove only delete operation
'/chart_themes'=>'*',
'/chart_themes/{id}'=>['put', 'delete', 'patch'],
];
}
}
您可以通过注释参数指定要隐藏的模式,例如:
#[GetCollection(
openapiContext: [
'hide' => true,
],
)]