History.php 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. <?php
  2. namespace Shaarli\Api\Controllers;
  3. use Shaarli\Api\Exceptions\ApiBadParametersException;
  4. use Slim\Http\Request;
  5. use Slim\Http\Response;
  6. /**
  7. * Class History
  8. *
  9. * REST API Controller: /history
  10. *
  11. * @package Shaarli\Api\Controllers
  12. */
  13. class History extends ApiController
  14. {
  15. /**
  16. * Service providing operation regarding Shaarli datastore and settings.
  17. *
  18. * @param Request $request Slim request.
  19. * @param Response $response Slim response.
  20. *
  21. * @return Response response.
  22. *
  23. * @throws ApiBadParametersException Invalid parameters.
  24. */
  25. public function getHistory($request, $response)
  26. {
  27. $history = $this->history->getHistory();
  28. // Return history operations from the {offset}th, starting from {since}.
  29. $since = \DateTime::createFromFormat(\DateTime::ATOM, $request->getParam('since'));
  30. $offset = $request->getParam('offset');
  31. if (empty($offset)) {
  32. $offset = 0;
  33. } elseif (ctype_digit($offset)) {
  34. $offset = (int) $offset;
  35. } else {
  36. throw new ApiBadParametersException('Invalid offset');
  37. }
  38. // limit parameter is either a number of links or 'all' for everything.
  39. $limit = $request->getParam('limit');
  40. if (empty($limit)) {
  41. $limit = count($history);
  42. } elseif (ctype_digit($limit)) {
  43. $limit = (int) $limit;
  44. } else {
  45. throw new ApiBadParametersException('Invalid limit');
  46. }
  47. $out = [];
  48. $i = 0;
  49. foreach ($history as $entry) {
  50. if ((! empty($since) && $entry['datetime'] <= $since) || count($out) >= $limit) {
  51. break;
  52. }
  53. if (++$i > $offset) {
  54. $out[$i] = $entry;
  55. $out[$i]['datetime'] = $out[$i]['datetime']->format(\DateTime::ATOM);
  56. }
  57. }
  58. $out = array_values($out);
  59. return $response->withJson($out, 200, $this->jsonStyle);
  60. }
  61. }