我在我的应用程序中使用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;
}
数据成功返回,我可以在管理员的表视图或项目视图中看到该字符串。
但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')"
* }
*/
实质上,您是为管理员添加新路由,但它比使用序列化机制更简单。