API Plateform custom get operation

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 AppController;

use AppEntityArticle;
use DoctrineORMEntityManagerInterface;
use SymfonyBundleFrameworkBundleControllerAbstractController;


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 AppController;


use SymfonyBundleFrameworkBundleControllerAbstractController;


class GetCart extends AbstractController
{
    public function getCart()
    {
        $user = $this->getUser();
        return $user->getCart();
    }
}

<?php

namespace AppEntity;

use ApiPlatformCoreAnnotationApiResource;
use AppRepositoryUserRepository;
use DoctrineCommonCollectionsArrayCollection;
use DoctrineCommonCollectionsCollection;
use DoctrineORMMapping as ORM;
use SymfonyComponentSecurityCoreUserUserInterface;

/**
 * @ORMEntity(repositoryClass=UserRepository::class)
 * @ApiResource(
 *     itemOperations={
 *          "get",
 *          "put",
 *          "get_cart"={
 *               "method"="GET",
 *               "path"="/cart",
 *               "controller"=AppControllerGetCart,
 *          },
 *     }
 * )
 */
class User implements UserInterface
{
    /**
     * @ORMId
     * @ORMGeneratedValue
     * @ORMColumn(type="integer")
     */
    private $id;

    /**
     * @ORMColumn(type="string", length=180, unique=true)
     */
    private $username;

    /**
     * @ORMColumn(type="json")
     */
    private $roles = [];

    /**
     * @var string The hashed password
     * @ORMColumn(type="string")
     */
    private $password;

    /**
     * @ORMColumn(type="string", length=255)
     */
    private $email;

    /**
     * @ORMManyToMany(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?

Answer

Instead using a controller, have you try to use custom DataProvider and inject Security ?

use SymfonyComponentSecurityCoreSecurity;
use ApiPlatformCoreDataProviderItemDataProviderInterface;
use ApiPlatformCoreDataProviderRestrictedDataProviderInterface;
use ApiPlatformCoreDataProviderSerializerAwareDataProviderInterface;
use ApiPlatformCoreDataProviderSerializerAwareDataProviderTrait;

class UserDataProvider implements ItemDataProviderInterface, RestrictedDataProviderInterface, SerializerAwareDataProviderInterface
{
    use SerializerAwareDataProviderTrait;
    public const OPERATION_NAME = "get_cart";
    private $security;

    public function __construct(Security $security)
    {
        $this->security = $security;
    }

    public function supports(string $resourceClass, string $operationName = null, array $context = []): bool
    {
        return User::class === $resourceClass && self::OPERATION_NAME === $operationName;
    }

    public function getItem(string $resourceClass, $id, string $operationName = null, array $context = []): ?TableDuplication
    {
        dump($this->security->getUser(), $this->security->getToken()); die();
        // Do what you need
    }
}

$this->security->getUser() will return your user and $this->security->getToken() will return all about your token

Here’s the documentation: https://api-platform.com/docs/core/data-providers/#custom-item-data-provider

Leave a Reply

Your email address will not be published. Required fields are marked *