gpt4 book ai didi

php - 如何将依赖于序列化组的属性从 API 平台公开到 react-admin?

转载 作者:可可西里 更新时间:2023-11-01 12:39:40 24 4
gpt4 key购买 nike

我使用 Changing the Serialization Context Dynamically在我的应用程序中,当用户是管理员时应用 admin:write 组。这样 admin 上的用户将能够更新此属性。

上下文构建器具有以下配置:

<?php

namespace App\Serializer;

use ApiPlatform\Core\Serializer\SerializerContextBuilderInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;

final class AdminContextBuilder implements SerializerContextBuilderInterface
{
private $decorated;
private $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_ADMIN') && false === $normalization) {
$context['groups'][] = 'admin:write';
}
if (isset($context['groups']) && $this->authorizationChecker->isGranted('ROLE_ADMIN') && true === $normalization) {
$context['groups'][] = 'admin:read';
}

return $context;
}
}

我想向管理员展示这个属性:

abstract class User implements UserInterface
{
/**
* @ORM\Column(name="account_status", type="string", length=8)
* @Groups({"read", "admin:write"})
*/
protected $accountStatus;
}

数据返回成功,在admin中的table view或item view上可以看到字符串。

但是 API-Platform 在 …/api/docs.jsonld 上生成的文档没有暴露这个属性:这个属性是不可写的:

{
"@type": "hydra:SupportedProperty",
"hydra:property": {
"@id": "#User/accountStatus",
"@type": "rdf:Property",
"rdfs:label": "accountStatus",
"domain": "#User",
"range": "xmls:string"
},
"hydra:title": "accountStatus",
"hydra:required": false,
"hydra:readable": true,
"hydra:writable": false
},

我认为它会阻止在管理中显示字段。

如何将此属性添加到文档中并最终添加到 react-admin?

我尝试了我能想到的任何配置:

abstract class User implements UserInterface
{
/**
* @ORM\Column(name="account_status", type="string", length=8)
* @Groups({"read", "admin:write"})
* @ApiProperty(writable=true)
*/
protected $accountStatus;
}

最佳答案

对我来说,当我完全使用注释执行此操作时,文档会按预期显示。

/**
* "admin_edit"={
* "method"="PUT", "path"="/api/users/{id}",
* "normalization_context"={"groups"={"admin:write"}},
* "access_control"="is_granted('ROLE_ADMIN')"
* }
*/

本质上,您是在为管理员添加一个新路由,但它比使用序列化机制更简单。

关于php - 如何将依赖于序列化组的属性从 API 平台公开到 react-admin?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53709568/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com