History.php 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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. }
  34. else if (ctype_digit($offset)) {
  35. $offset = (int) $offset;
  36. } else {
  37. throw new ApiBadParametersException('Invalid offset');
  38. }
  39. // limit parameter is either a number of links or 'all' for everything.
  40. $limit = $request->getParam('limit');
  41. if (empty($limit)) {
  42. $limit = count($history);
  43. } else if (ctype_digit($limit)) {
  44. $limit = (int) $limit;
  45. } else {
  46. throw new ApiBadParametersException('Invalid limit');
  47. }
  48. $out = [];
  49. $i = 0;
  50. foreach ($history as $entry) {
  51. if ((! empty($since) && $entry['datetime'] <= $since) || count($out) >= $limit) {
  52. break;
  53. }
  54. if (++$i > $offset) {
  55. $out[$i] = $entry;
  56. $out[$i]['datetime'] = $out[$i]['datetime']->format(\DateTime::ATOM);
  57. }
  58. }
  59. $out = array_values($out);
  60. return $response->withJson($out, 200, $this->jsonStyle);
  61. }
  62. }