phpsymfonydoctrineuser-roles

Error A circular reference has been detected on symfony 3


i do this steps:

1.) I call my api endpoint: http://localhost:8000/api/addrole

2.) This is the controller called:

/**
 * @Rest\Post("/addrole")
 */
 public function addRoleAction(Request $request)
{
    $userid = $request->get('userid');
    $assignedRole = $request->get('role');
    $assignedRoleName = $request->get('role_name');

    // Obtain the User
    $em = $this->getDoctrine()->getManager();
    $user = $em->getRepository('AppBundle:User')
        ->find($userid);

  // If the user gives not exists, throw error
    if (!$user) {
        throw new HttpException (400,"No se ha encontrado el usuario solicitado: " .$userid);
     }

     // obtain present user roles
    $presentRoles = $user->getRoles();
    $role_length = count($presentRoles); 
    $role_list = array();
    for ($i=0; $i <$role_length ; $i++) { 
    array_push($role_list,$presentRoles[$i]->getRole());
    }

    if(!in_array($assignedRole,$role_list)){
        $role = $em->getRepository('AppBundle:Role')
            ->findOneBy(array('role' => $assignedRole));
        $user->addRole($role);
        $em->persist($user); // persisting only the user. 
        $em->flush();

            $data = array(
                'result' => 'Rol asignado',
                'user' => $user,
                'assignedRole' => $assignedRole
            );
        return $data;
    } else {
        throw new HttpException (400,"El usuario ya posee el rol solicitado");
    }

}

3.) The data on this step:

 $user->addRole($role);
 $em->persist($user); // persisting only the user. 
 $em->flush();

is saving the data on the DB.

4.) this is the response:

{
  "error": {
    "code": 500,
    "message": "Internal Server Error",
    "exception": [
      {
        "message": "A circular reference has been detected (configured limit: 1).",
        "class": "Symfony\\Component\\Serializer\\Exception\\CircularReferenceException",...

5.) if i comment this line:

 //$em->flush();

the data obviosly don't save, but the error is not throwed.

Any clue about this?


Solution

  • Finally i found the error.

    The problem is on this code:

    ...
    post $em->flush(); 
    this: $data = array('result' => 'Rol asignado', 'user' => $user, 'assignedRole' => $assignedRole ); 
    return $data;
    

    After the flush i called the $user object. This generate the problem.

    Thanks to all.