aboutsummaryrefslogtreecommitdiffhomepage
path: root/application/api/controllers/HistoryController.php
blob: 9afcfa264430cd7af5910357bfcd07fbea797301 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
<?php


namespace Shaarli\Api\Controllers;

use Shaarli\Api\Exceptions\ApiBadParametersException;
use Slim\Http\Request;
use Slim\Http\Response;

/**
 * Class History
 *
 * REST API Controller: /history
 *
 * @package Shaarli\Api\Controllers
 */
class HistoryController extends ApiController
{
    /**
     * Service providing operation regarding Shaarli datastore and settings.
     *
     * @param Request  $request  Slim request.
     * @param Response $response Slim response.
     *
     * @return Response response.
     *
     * @throws ApiBadParametersException Invalid parameters.
     */
    public function getHistory($request, $response)
    {
        $history = $this->history->getHistory();

        // Return history operations from the {offset}th, starting from {since}.
        $since = \DateTime::createFromFormat(\DateTime::ATOM, $request->getParam('since'));
        $offset = $request->getParam('offset');
        if (empty($offset)) {
            $offset = 0;
        } elseif (ctype_digit($offset)) {
            $offset = (int) $offset;
        } else {
            throw new ApiBadParametersException('Invalid offset');
        }

        // limit parameter is either a number of links or 'all' for everything.
        $limit = $request->getParam('limit');
        if (empty($limit)) {
            $limit = count($history);
        } elseif (ctype_digit($limit)) {
            $limit = (int) $limit;
        } else {
            throw new ApiBadParametersException('Invalid limit');
        }

        $out = [];
        $i = 0;
        foreach ($history as $entry) {
            if ((! empty($since) && $entry['datetime'] <= $since) || count($out) >= $limit) {
                break;
            }
            if (++$i > $offset) {
                $out[$i] = $entry;
                $out[$i]['datetime'] = $out[$i]['datetime']->format(\DateTime::ATOM);
            }
        }
        $out = array_values($out);

        return $response->withJson($out, 200, $this->jsonStyle);
    }
}