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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
|
<?php
namespace JsonApi\Routes\Blubber;
use JsonApi\Errors\AuthorizationFailedException;
use JsonApi\Errors\RecordNotFoundException;
use JsonApi\JsonApiController;
use JsonApi\Routes\TimestampTrait;
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
/**
* Displays all comments of a certain blubber thread.
*/
class CommentsByThreadIndex extends JsonApiController
{
use FilterTrait;
use SortTrait;
use TimestampTrait;
protected $allowedFilteringParameters = ['since', 'before', 'search'];
protected $allowedIncludePaths = ['author', 'mentions', 'thread', 'thread.author'];
protected $allowedPagingParameters = ['offset', 'limit'];
protected $allowedSortFields = ['mkdate'];
/**
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/
public function __invoke(Request $request, Response $response, $args)
{
$this->validateFilters();
if (!($thread = \BlubberThread::find($args['id']))) {
throw new RecordNotFoundException();
}
if (!Authority::canShowBlubberThread($this->getUser($request), $thread)) {
throw new AuthorizationFailedException();
}
$filters = $this->getFilters();
list($total, $comments) = $this->getComments($thread, $filters);
return $this->getPaginatedContentResponse($comments, $total);
}
private function getComments(\BlubberThread $thread, array $filters)
{
list($offset, $limit) = $this->getOffsetAndLimit();
$query = 'thread_id = :thread_id';
$params = ['thread_id' => $thread->id];
if (isset($filters['before'])) {
$query .= ' AND mkdate < :before';
$params['before'] = $filters['before'];
}
if (isset($filters['since'])) {
$query .= ' AND mkdate > :since';
$params['since'] = $filters['since'];
}
if (isset($filters['search'])) {
$query .= ' AND content LIKE :search';
$params['search'] = '%' . $filters['search'] . '%';
}
$sortParameters = $this->getSortParameters();
if (empty($sortParameters)) {
$query .= ' ORDER BY mkdate';
} elseif (array_key_exists('mkdate', $sortParameters)) {
$query .= ' ORDER BY mkdate ' . ($sortParameters['mkdate'] ? 'ASC' : 'DESC');
}
$query .= ' LIMIT :limit OFFSET :offset';
$params['limit'] = $limit + 1;
$params['offset'] = $offset;
$comments = \BlubberComment::findBySQL($query, $params);
return [count($comments) <= $limit ? count($comments) + $offset : null, array_slice($comments, 0, $limit)];
}
}
|