I am building a web app using Symfony 4.0. I have created an authentication system using a JWT and I have an endpoint that returns a token when a username and password is matched in the database.
I created a function to get User details for the current user, which I created so I can use JavaScript to build the header in my web app (i.e. appropriate links according to the logged in user privileges).
However, when I make a call to /api/users/current this gives the following error:
Maximum function nesting level of '512' reached, aborting!
The endpoint seems to be returning all entities related to the user, but I have no idea why this is happening.
UserController:
<?php
namespace App\Controller\Api;
use App\Controller\BaseController;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\User\UserInterface;
class UserController extends BaseController
{
/**
* @Route("/api/users/current")
* @Method("GET")
* @param UserInterface $user
* @return Response
*/
public function getCurrentUser(UserInterface $user){
$response = $this->createApiResponse($user, 200);
return $response;
}
}
BaseController:
<?php
namespace App\Controller;
use JMS\Serializer\SerializationContext;
use JMS\Serializer\Serializer;
use JMS\Serializer\SerializerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
abstract class BaseController extends AbstractController
{
private $serializer;
public function __construct(SerializerInterface $serializer)
{
$this->serializer = $serializer;
}
/**
* @param $data
* @param int $statusCode
* @return Response
*/
protected function createApiResponse($data, $statusCode = 200)
{
$json = $this->serialize($data);
return new Response($json, $statusCode, array(
'Content-Type' => 'application/json'
));
}
/**
* @param Serializer $serializer
* @param $data
* @param string $format
* @return mixed
*/
protected function serialize($data, $format = 'json')
{
$context = new SerializationContext();
$context->setSerializeNull(true);
return $this->serializer->serialize($data, $format, $context);
}
}