TodosController.php 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  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 get(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 put(Application $app, Request $request, int $id) {
  22. $sub = Request::create('/todos', 'POST', [], [], [], [], $request->getContent());
  23. return $app->handle($sub, HttpKernelInterface::SUB_REQUEST);
  24. }
  25. public function post(Application $app, Request $request) {
  26. /** @var \Model $model */
  27. $model = $app['model'];
  28. $data = json_decode($request->getContent(), true);
  29. $created = $model->save($data);
  30. return new Response('Saved', $created ? Response::HTTP_CREATED : Response::HTTP_OK);
  31. }
  32. public function delete(Application $app, int $id) {
  33. /** @var \Model $model */
  34. $model = $app['model'];
  35. $deleted = $model->delete($id);
  36. return new Response(
  37. $deleted ? 'Deleted' : 'It was not there anyway',
  38. Response::HTTP_OK
  39. );
  40. }
  41. }