src/Controller/SecurityController.php
<?php
namespace App\Controller;
use App\Entity\Customer;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
use Symfony\Component\Serializer\SerializerInterface;
use Symfony\Component\Validator\Validator\ValidatorInterface;
/**
* @Route("/api")
* Controller for API
*/
class SecurityController extends AbstractController
{
/**
* @Route("/register", name="register", methods={"POST"})
*/
public function register(Request $request, UserPasswordEncoderInterface $passwordEncoder, EntityManagerInterface $entityManager, SerializerInterface $serializer, ValidatorInterface $validator)
{
$values = json_decode($request->getContent());
if(isset($values->username,$values->password)) {
$customer = new Customer();
$customer->setUsername($values->username);
$customer->setPassword($passwordEncoder->encodePassword($customer, $values->password));
$customer->setRoles($customer->getRoles());
$customer->setEmail($values->email);
$errors = $validator->validate($customer);
if(count($errors)) {
$errors = $serializer->serialize($errors, 'json');
return new Response($errors, 500, [
'Content-Type' => 'application/json'
]);
}
$entityManager->persist($customer);
$entityManager->flush();
$data = [
'status' => 201,
'message' => 'L\'utilisateur a été créé'
];
return new JsonResponse($data, 201);
}
$data = [
'status' => 500,
'message' => 'Vous devez renseigner les clés "username" , "password" et "email" '
];
return new JsonResponse($data, 500);
}
}