TodosController.php 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  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 index(Application $app) {
  9. /** @var \Model $model */
  10. $model = $app['model'];
  11. $todos = $model->load();
  12. return $app->json(array_values($todos));
  13. }
  14. public function getLevel1(Application $app, $id) {
  15. /** @var \Model $model */
  16. $model = $app['model'];
  17. $todos = $model->load();
  18. $todo = $todos[$id] ?? NULL;
  19. return $app->json($todo);
  20. }
  21. public function getLevel2(Application $app, $id) {
  22. /** @var \Model $model */
  23. $model = $app['model'];
  24. $todos = $model->load();
  25. $todo = $todos[$id]
  26. ? ['todo' => $todos[$id]]
  27. : NULL;
  28. if ($todo) {
  29. $todo['todo']['desc'] = $todo['todo']['description'];
  30. unset($todo['todo']['description']);
  31. }
  32. return $app->json($todo);
  33. }
  34. public function putLevel1(Application $app, Request $request, int $id) {
  35. $sub = Request::create('/todos', 'POST', [], [], [], [], $request->getContent());
  36. return $app->handle($sub, HttpKernelInterface::SUB_REQUEST);
  37. }
  38. public function putLevel2(Application $app, Request $request, int $id) {
  39. $sub = Request::create('/todos', 'POST', [], [], [], [], $request->getContent());
  40. return $app->handle($sub, HttpKernelInterface::SUB_REQUEST);
  41. }
  42. public function post(Application $app, Request $request) {
  43. /** @var \Model $model */
  44. $model = $app['model'];
  45. $data = json_decode($request->getContent(), true);
  46. $data = $data['todo'];
  47. $created = $model->save($data);
  48. return new Response('Saved', $created ? Response::HTTP_CREATED : Response::HTTP_OK);
  49. }
  50. public function delete(Application $app, int $id) {
  51. /** @var \Model $model */
  52. $model = $app['model'];
  53. $deleted = $model->delete($id);
  54. return new Response(
  55. $deleted ? 'Deleted' : 'It was not there anyway',
  56. Response::HTTP_OK
  57. );
  58. }
  59. }