A.L*_*A.L 7 php symfony api-platform.com symfony4 react-admin
我在我的应用程序中动态更改序列化上下文以admin:write
在用户是管理员时应用该组.这样管理员的用户就可以更新此属性.
上下文构建器具有以下配置:
<?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;
}
}
Run Code Online (Sandbox Code Playgroud)
我想向管理员显示此属性:
abstract class User implements UserInterface
{
/**
* @ORM\Column(name="account_status", type="string", length=8)
* @Groups({"read", "admin:write"})
*/
protected $accountStatus;
}
Run Code Online (Sandbox Code Playgroud)
数据成功返回,我可以在管理员的表视图或项目视图中看到该字符串.
但API-Platform on生成的文档…/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
},
Run Code Online (Sandbox Code Playgroud)
我认为它可以防止在管理中显示该字段.
如何将此属性添加到文档中并最终添加到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;
}
Run Code Online (Sandbox Code Playgroud)
对我来说,当我完全使用注释来完成此操作时,文档会按预期显示。
/**
* "admin_edit"={
* "method"="PUT", "path"="/api/users/{id}",
* "normalization_context"={"groups"={"admin:write"}},
* "access_control"="is_granted('ROLE_ADMIN')"
* }
*/
Run Code Online (Sandbox Code Playgroud)
本质上,您正在为管理员添加一条新路由,但这比使用序列化机制更简单。
归档时间: |
|
查看次数: |
405 次 |
最近记录: |