Advertisement
SanderCokart

TodoController.php

Mar 3rd, 2020
521
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 4.96 KB | None | 0 0
  1. <?php
  2.  
  3. namespace App\Controller;
  4.  
  5. use App\Entity\Todo;
  6. use App\Form\TodoType;
  7. use App\Repository\TodoRepository;
  8. use Doctrine\DBAL\Exception\UniqueConstraintViolationException;
  9. use Doctrine\ORM\EntityManagerInterface;
  10. use Exception;
  11. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  12. use Symfony\Component\HttpFoundation\JsonResponse;
  13. use Symfony\Component\HttpFoundation\Request;
  14. use Symfony\Component\Routing\Annotation\Route;
  15.  
  16. /**
  17.  * @Route("/api/todo", name="api_todo")
  18.  */
  19. class TodoController extends AbstractController
  20. {
  21.     private $entityManager;
  22.     private $todoRepository;
  23.  
  24.     public function __construct(EntityManagerInterface $entityManager, TodoRepository $todoRepository)
  25.     {
  26.         $this->entityManager = $entityManager;
  27.         $this->todoRepository = $todoRepository;
  28.     }
  29.  
  30.     /**
  31.      * @Route("/create", name="api_todo_create", methods={"POST"})
  32.      * @param Request $request
  33.      * @return JsonResponse
  34.      */
  35.     public function create(Request $request)
  36.     {
  37.         $content = json_decode($request->getContent());
  38.  
  39.         $form = $this->createForm(TodoType::class);
  40.         $form->submit((array)$content);
  41.  
  42.         if (!$form->isValid()) {
  43.             $errors = [];
  44.             foreach ($form->getErrors(true, true) as $error) {
  45.                 $propertyName = $error->getOrigin()->getName();
  46.                 $errors[$propertyName] = $error->getMessage();
  47.             }
  48.             return $this->json([
  49.                 'message' => ['text' => join("\n", $errors), 'level' => 'error'],
  50.             ]);
  51.  
  52.         }
  53.  
  54.  
  55.         $todo = new Todo();
  56.  
  57.         $todo->setTask($content->task);
  58.         $todo->setDescription($content->description);
  59.  
  60.         try {
  61.             $this->entityManager->persist($todo);
  62.             $this->entityManager->flush();
  63.         } catch (UniqueConstraintViolationException $exception) {
  64.             return $this->json([
  65.                 'message' => ['text' => 'Task has to be unique!', 'level' => 'error']
  66.             ]);
  67.  
  68.         }
  69.         return $this->json([
  70.             'todo'    => $todo->toArray(),
  71.             'message' => ['text' => 'To-Do has been created!', 'level' => 'success']
  72.         ]);
  73.     }
  74.  
  75.  
  76.     /**
  77.      * @Route("/read", name="api_todo_read", methods={"GET"})
  78.      */
  79.     public function read()
  80.     {
  81.         $todos = $this->todoRepository->findAll();
  82.  
  83.         $arrayOfTodos = [];
  84.         foreach ($todos as $todo) {
  85.             $arrayOfTodos[] = $todo->toArray();
  86.         }
  87.         return $this->json($arrayOfTodos);
  88.  
  89.     }
  90.  
  91.     /**
  92.      * @Route("/update/{id}", name="api_todo_update", methods={"PUT"})
  93.      * @param Request $request
  94.      * @param Todo $todo
  95.      * @return JsonResponse
  96.      */
  97.     public function update(Request $request, Todo $todo)
  98.     {
  99.         $content = json_decode($request->getContent());
  100.  
  101.         $form = $this->createForm(TodoType::class);
  102.         $nonObject = (array)$content;
  103.         unset($nonObject['id']);
  104.         $form->submit($nonObject);
  105.  
  106.  
  107.         if (!$form->isValid()) {
  108.             $errors = [];
  109.             foreach ($form->getErrors(true, true) as $error) {
  110.                 $propertyName = $error->getOrigin()->getName();
  111.                 $errors[$propertyName] = $error->getMessage();
  112.             }
  113.             return $this->json([
  114.                 'message' => ['text' => join("\n", $errors), 'level' => 'error'],
  115.             ]);
  116.  
  117.         }
  118.  
  119.         if ($todo->getTask() === $content->task && $todo->getDescription() === $content->description) {
  120.             return $this->json([
  121.                 'message' => ['text' => 'There was no change to the To-Do. Neither the task or the description was changed.', 'level' => 'error']
  122.             ]);
  123.         }
  124.  
  125.         $todo->setTask($content->task);
  126.         $todo->setDescription($content->description);
  127.  
  128.         try {
  129.             $this->entityManager->flush();
  130.         } catch (Exception $exception) {
  131.             return $this->json([
  132.                 'message' => ['text' => 'Could not reach database when attempting to update a To-Do.', 'level' => 'error']
  133.             ]);
  134.         }
  135.  
  136.         return $this->json([
  137.             'todo'    => $todo->toArray(),
  138.             'message' => ['text' => 'To-Do successfully updated!', 'level' => 'success']
  139.         ]);
  140.  
  141.     }
  142.  
  143.  
  144.     /**
  145.      * @Route("/delete/{id}", name="api_todo_delete", methods={"DELETE"})
  146.      * @param Todo $todo
  147.      * @return JsonResponse
  148.      */
  149.     public function delete(Todo $todo)
  150.     {
  151.         try {
  152.             $this->entityManager->remove($todo);
  153.             $this->entityManager->flush();
  154.         } catch (Exception $exception) {
  155.             return $this->json([
  156.                 'message' => ['text' => 'Could not reach database when attempting to delete a To-Do.', 'level' => 'error']
  157.             ]);
  158.  
  159.         }
  160.  
  161.         return $this->json([
  162.             'message' => ['text' => 'To-Do has successfully been deleted!', 'level' => 'success']
  163.         ]);
  164.  
  165.     }
  166.  
  167.  
  168. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement