I am trying to build an ecommerce site using API plateform.
Since I am using JWT authentication with LexikJWTAuthenticationBundle I am having a hard time to get the user with the token.
I would like to access the cart of the user.
I managed to add to the cart through a custom post operation.
<?php
namespace App\Controller;
use App\Entity\Article;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
class AddToCart extends AbstractController
{
private $em;
public function __construct(EntityManagerInterface $em)
{
$this->em = $em;
}
public function __invoke(Article $data)
{
$user = $this->getUser();
$user->addCart($data);
$this->em->flush();
return $user->getCart();
}
}
I am trying to use the same way but with a get request
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
class GetCart extends AbstractController
{
public function getCart()
{
$user = $this->getUser();
return $user->getCart();
}
}
<?php
namespace App\Entity;
use ApiPlatform\Core\Annotation\ApiResource;
use App\Repository\UserRepository;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Security\Core\User\UserInterface;
/**
* @ORM\Entity(repositoryClass=UserRepository::class)
* @ApiResource(
* itemOperations={
* "get",
* "put",
* "get_cart"={
* "method"="GET",
* "path"="/cart",
* "controller"=App\Controller\GetCart,
* },
* }
* )
*/
class User implements UserInterface
{
/**
* @ORM\Id
* @ORM\GeneratedValue
* @ORM\Column(type="integer")
*/
private $id;
/**
* @ORM\Column(type="string", length=180, unique=true)
*/
private $username;
/**
* @ORM\Column(type="json")
*/
private $roles = [];
/**
* @var string The hashed password
* @ORM\Column(type="string")
*/
private $password;
/**
* @ORM\Column(type="string", length=255)
*/
private $email;
/**
* @ORM\ManyToMany(targetEntity=Article::class)
*/
private $cart;
/**
* @return Collection|Article[]
*/
public function getCart(): Collection
{
return $this->cart;
}
public function addCart(Article $cart): self
{
if (!$this->cart->contains($cart)) {
$this->cart[] = $cart;
}
return $this;
}
public function removeCart(Article $cart): self
{
$this->cart->removeElement($cart);
return $this;
}
}
Any idea what I am doing wrong?