TodosController.php 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. <?php
  2. namespace Controllers;
  3. use Silex\Application;
  4. use Symfony\Component\HttpFoundation\Request;
  5. use Symfony\Component\HttpFoundation\Response;
  6. use Symfony\Component\HttpKernel\HttpKernelInterface;
  7. class TodosController {
  8. public function get(Application $app, $id) {
  9. /** @var \Model $model */
  10. $model = $app['model'];
  11. $todos = $model->load();
  12. $todo = $todos[$id] ?? NULL;
  13. return $app->json($todo);
  14. }
  15. public function put(Application $app, Request $request, int $id) {
  16. $sub = Request::create('/todos', 'POST', [], [], [], [], $request->getContent());
  17. return $app->handle($sub, HttpKernelInterface::SUB_REQUEST);
  18. }
  19. public function post(Application $app, Request $request) {
  20. /** @var \Model $model */
  21. $model = $app['model'];
  22. $data = json_decode($request->getContent(), true);
  23. $created = $model->save($data);
  24. return new Response('Saved', $created ? Response::HTTP_CREATED : Response::HTTP_OK);
  25. }
  26. public function delete(Application $app, int $id) {
  27. /** @var \Model $model */
  28. $model = $app['model'];
  29. $deleted = $model->delete($id);
  30. return new Response(
  31. $deleted ? 'Deleted' : 'It was not there anyway',
  32. Response::HTTP_OK
  33. );
  34. }
  35. }