ApiPlatform генерирует неверный IRI (без идентификатора) при использовании поставщика состояний.Php

Кемеровские программисты php общаются здесь
Ответить
Anonymous
 ApiPlatform генерирует неверный IRI (без идентификатора) при использовании поставщика состояний.

Сообщение Anonymous »

У меня есть сущность «Пользователь» на платформе API, и я создал специальную операцию для возврата информации о вошедшем в систему пользователе с использованием поставщика состояний.
Тег ApiResource:

Код: Выделить всё

#[ApiResource(
operations: [
new Get(
uriTemplate: '/user',
normalizationContext: ['groups' => ['user:read']],
security: self::SECURITY_GET,
provider: UserStateProvider::class
)
]
UserStateProvider:

Код: Выделить всё

class UserStateProvider implements ProviderInterface
{
public function __construct(
private readonly Security $security,
) {}

public function provide(Operation $operation, array $uriVariables = [], array $context = []): object|array|null
{
return $this->security->getUser();
}
}
Проблема: Эта конечная точка возвращает IRI без идентификатора, который выглядит следующим образом:

Код: Выделить всё

"@context": "/api/contexts/User",
"@id": "/api/user",
"@type": "User",
Я попытался получить пользователя из репозитория в UserStateProvider, но это не решило проблему:

Код: Выделить всё

$user = $this->security->getUser();
return $user ? $this->userRepository->find($user->getId()) : null;
Ресурс пользователя:

Код: Выделить всё

#[ORM\Entity(repositoryClass: UserRepository::class)]
#[ORM\Table(name: '`users`')]
#[ApiResource(
operations: [
new Get(
uriTemplate: '/user',
normalizationContext: ['groups' => ['user:read']],
security: self::SECURITY_GET,
provider: UserStateProvider::class
),
new Get(
uriTemplate: '/user/data',
normalizationContext: ['groups' => ['user:read', 'userdata:read']],
security: self::SECURITY_GET,
provider: UserStateProvider::class
),
new Post(
uriTemplate: '/user/register/',
controller: RegisterController::class,
normalizationContext: ['groups' => ['user:read', 'userdata:read']],
),
],
denormalizationContext: [
'groups' => [ 'user:write' ]
]
)]
class User implements UserInterface, PasswordAuthenticatedUserInterface, SubscribeEntity
{
const SECURITY_GET = "is_granted('ROLE_USER')";

#[ORM\Id]
#[ORM\GeneratedValue]
#[ORM\Column]
#[ApiProperty(identifier: true)]
#[Groups(['user:read'])]
private ?int $id = null;

/**
* @var list  The user roles
*/
#[ORM\Column]
#[Groups(['user:read'])]
private array $roles = [];

/**
* @var string The hashed password
*/
#[ORM\Column]
#[Groups(['user:write'])]
private ?string $password = null;

#[ORM\Column(length: 255, unique: true)]
#[Groups(['user:read', 'user:write', 'channel:read', 'purchasedTicket:readUser'])]
private ?string $nickname = null;

#[ORM\Column]
#[Groups(['userdata:read'])]
private ?\DateTimeImmutable $createdAt = null;

#[ORM\Column]
private ?\DateTimeImmutable $updatedAt = null;

#[ORM\Column(length: 255, unique: true)]
#[Groups(['user:read', 'user:write', 'purchasedTicket:readUser'])]
#[Email]
private ?string $email = null;

#[ORM\OneToOne(mappedBy: 'user', cascade: ['persist', 'remove'])]
#[Groups(['userdata:read', 'user:write'])]
private ?UserData $userData = null;

/**
* @var Collection
*/
#[ORM\OneToMany(targetEntity: UserChange::class, mappedBy: 'user')]
private Collection $userChanges;

/**
* @var Collection
*/
#[ORM\OneToMany(targetEntity: Channel::class, mappedBy: 'user')]
private Collection $channels;

/**
* @var Collection
*/
#[ORM\ManyToMany(targetEntity: Channel::class, mappedBy: 'moderators')]
private Collection $moderateChannels;

/**
* @var Collection
*/
#[ORM\OneToMany(targetEntity: Comment::class, mappedBy: 'author')]
private Collection $comments;

/**
* @var Collection
*/
#[ORM\OneToMany(targetEntity: PurchasedTicket::class, mappedBy: 'user')]
private Collection $purchasedTickets;

/**
* @var Collection
*/
#[ORM\OneToMany(targetEntity: CartItem::class, mappedBy: 'user')]
private Collection $cartItems;

/**
* @var Collection
*/
#[ORM\OneToMany(targetEntity: Subscription::class, mappedBy: 'user')]
private Collection $subscriptions;

/**
* @var Collection
*/
#[ORM\OneToMany(targetEntity: PurchasedVideoContent::class, mappedBy: 'user')]
private Collection $purchasedVideoContents;

public function __construct()
{
$this->createdAt = new \DateTimeImmutable();
$this->updatedAt = new \DateTimeImmutable();
$this->userChanges = new ArrayCollection();
$this->channels = new ArrayCollection();
$this->moderateChannels = new ArrayCollection();
$this->comments = new ArrayCollection();
$this->purchasedTickets = new ArrayCollection();
$this->cartItems = new ArrayCollection();
$this->subscriptions = new ArrayCollection();
$this->purchasedVideoContents = new ArrayCollection();
}

public function getId(): ?int
{
return $this->id;
}

/**
* A visual identifier that represents this user.
*
* @see UserInterface
*/
public function getUserIdentifier(): string
{
return (string) $this->id;
}

/**
* @see UserInterface
*
* @return list
*/
public function getRoles(): array
{
$roles = $this->roles;
// guarantee every user at least has ROLE_USER
$roles[] = 'ROLE_USER';

return array_unique($roles);
}

/**
* @param list  $roles
*/
public function setRoles(array $roles): static
{
$this->roles = $roles;

return $this;
}

/**
* @see PasswordAuthenticatedUserInterface
*/
public function getPassword(): string
{
return $this->password;
}

public function setPassword(string $password): static
{
$this->password = $password;

return $this;
}

/**
* @see UserInterface
*/
public function eraseCredentials(): void
{
// If you store any temporary, sensitive data on the user, clear it here
// $this->plainPassword = null;
}

public function getNickname(): ?string
{
return $this->nickname;
}

public function setNickname(string $nickname): static
{
$this->nickname = $nickname;

return $this;
}

public function getCreatedAt(): ?\DateTimeImmutable
{
return $this->createdAt;
}

public function setCreatedAt(\DateTimeImmutable $createdAt): static
{
$this->createdAt = $createdAt;

return $this;
}

public function getUpdatedAt(): ?\DateTimeImmutable
{
return $this->updatedAt;
}

public function setUpdatedAt(\DateTimeImmutable $updatedAt): static
{
$this->updatedAt = $updatedAt;

return $this;
}

public function getEmail(): ?string
{
return $this->email;
}

public function setEmail(string $email): static
{
$this->email = $email;

return $this;
}

public function getUserData(): ?UserData
{
return $this->userData;
}

public function setUserData(UserData $userData): static
{
// set the owning side of the relation if necessary
if ($userData->getUser() !== $this) {
$userData->setUser($this);
}

$this->userData = $userData;

return $this;
}

/**
* @return Collection
*/
public function getUserChanges(): Collection
{
return $this->userChanges;
}

public function addUserChange(UserChange $userChange): static
{
if (!$this->userChanges->contains($userChange)) {
$this->userChanges->add($userChange);
$userChange->setUser($this);
}

return $this;
}

public function removeUserChange(UserChange $userChange): static
{
if ($this->userChanges->removeElement($userChange)) {
// set the owning side to null (unless already changed)
if ($userChange->getUser() === $this) {
$userChange->setUser(null);
}
}

return $this;
}

/**
* @return Collection
*/
public function getChannels(): Collection
{
return $this->channels;
}

public function addChannel(Channel $channel): static
{
if (!$this->channels->contains($channel)) {
$this->channels->add($channel);
$channel->setUser($this);
}

return $this;
}

public function removeChannel(Channel $channel): static
{
if ($this->channels->removeElement($channel)) {
// set the owning side to null (unless already changed)
if ($channel->getUser() === $this) {
$channel->setUser(null);
}
}

return $this;
}

/**
* @return Collection
*/
public function getModerateChannels(): Collection
{
return $this->moderateChannels;
}

public function addModerateChannel(Channel $moderateChannel): static
{
if (!$this->moderateChannels->contains($moderateChannel)) {
$this->moderateChannels->add($moderateChannel);
$moderateChannel->addModerator($this);
}

return $this;
}

public function removeModerateChannel(Channel $moderateChannel):  static
{
if ($this->moderateChannels->removeElement($moderateChannel)) {
$moderateChannel->removeModerator($this);
}

return $this;
}

/**
* @return Collection
*/
public function getComments(): Collection
{
return $this->comments;
}

public function addComment(Comment $comment): static
{
if (!$this->comments->contains($comment)) {
$this->comments->add($comment);
$comment->setAuthor($this);
}

return $this;
}

public function removeComment(Comment $comment): static
{
if ($this->comments->removeElement($comment)) {
// set the owning side to null (unless already changed)
if ($comment->getAuthor() === $this) {
$comment->setAuthor(null);
}
}

return $this;
}

/**
* @return Collection
*/
public function getPurchasedTickets(): Collection
{
return $this->purchasedTickets;
}

public function addPurchasedTicket(PurchasedTicket $purchasedTicket): static
{
if (!$this->purchasedTickets->contains($purchasedTicket)) {
$this->purchasedTickets->add($purchasedTicket);
$purchasedTicket->setUser($this);
}

return $this;
}

public function removePurchasedTicket(PurchasedTicket $purchasedTicket): static
{
if ($this->purchasedTickets->removeElement($purchasedTicket)) {
// set the owning side to null (unless already changed)
if ($purchasedTicket->getUser() === $this) {
$purchasedTicket->setUser(null);
}
}

return $this;
}

/**
* @return Collection
*/
public function getCartItems(): Collection
{
return $this->cartItems;
}

public function addCartItem(CartItem $cartItem): static
{
if (!$this->cartItems->contains($cartItem)) {
$this->cartItems->add($cartItem);
$cartItem->setUser($this);
}

return $this;
}

public function removeCartItem(CartItem $cartItem): static
{
if ($this->cartItems->removeElement($cartItem)) {
// set the owning side to null (unless already changed)
if ($cartItem->getUser() === $this) {
$cartItem->setUser(null);
}
}

return $this;
}

public function getName(): ?string
{
return $this->getNickname();
}

/**
* @return Collection
*/
public function getSubscriptions(): Collection
{
return $this->subscriptions;
}

public function addSubscription(Subscription $subscription): static
{
if (!$this->subscriptions->contains($subscription)) {
$this->subscriptions->add($subscription);
$subscription->setUser($this);
}

return $this;
}

public function removeSubscription(Subscription $subscription): static
{
if ($this->subscriptions->removeElement($subscription)) {
// set the owning side to null (unless already changed)
if ($subscription->getUser() === $this) {
$subscription->setUser(null);
}
}

return $this;
}

/**
* @return Collection
*/
public function getPurchasedVideoContents(): Collection
{
return $this->purchasedVideoContents;
}

public function addPurchasedVideoContent(PurchasedVideoContent $purchasedVideoContent): static
{
if (!$this->purchasedVideoContents->contains($purchasedVideoContent)) {
$this->purchasedVideoContents->add($purchasedVideoContent);
$purchasedVideoContent->setUser($this);
}

return $this;
}

public function removePurchasedVideoContent(PurchasedVideoContent $purchasedVideoContent):  static
{
if ($this->purchasedVideoContents->removeElement($purchasedVideoContent)) {
// set the owning side to null (unless already changed)
if ($purchasedVideoContent->getUser() === $this) {
$purchasedVideoContent->setUser(null);
}
}

return $this;
}
}



Подробнее здесь: https://stackoverflow.com/questions/791 ... e-provider
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «Php»