controllers.php 1.5 KB

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