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
|
<?php
namespace JsonApi\Routes\Courseware;
use Courseware\StructuralElement;
use JsonApi\Errors\AuthorizationFailedException;
use JsonApi\Errors\RecordNotFoundException;
use JsonApi\JsonApiController;
use Neomerx\JsonApi\Contracts\Http\ResponsesInterface;
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
/**
* Displays all descendants of a structural element.
*/
class DescendantsOfStructuralElementsIndex extends JsonApiController
{
protected $allowedPagingParameters = ['offset', 'limit'];
protected $allowedIncludePaths = ['containers', 'course', 'editor', 'owner', 'parent'];
/**
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/
public function __invoke(Request $request, Response $response, $args)
{
/** @var ?StructuralElement $resource */
$resource = StructuralElement::find($args['id']);
if (!$resource) {
throw new RecordNotFoundException();
}
if (!Authority::canShowStructuralElement($user = $this->getUser($request), $resource)) {
throw new AuthorizationFailedException();
}
$descendants = $resource->findDescendants($user);
list($offset, $limit) = $this->getOffsetAndLimit();
$page = array_slice($descendants, $offset, $limit);
$total = count($descendants);
// compute ETag, compare it and short-cut this route if they match
$etag = $this->getETag($user, $resource, $descendants);
if ($request->hasHeader('If-None-Match')) {
$sentETag = $request->getHeaderLine('If-None-Match');
if ($etag === $sentETag) {
return $response->withStatus(304)->withHeader('Cache-Control', 'private, must-revalidate');
}
}
return $this->getPaginatedContentResponse(
$page,
$total,
ResponsesInterface::HTTP_OK,
[],
[],
[
'Cache-Control' => 'private, must-revalidate',
'ETag' => $etag,
]
);
}
private function getEtag(\User $user, StructuralElement $resource, array $elements): string
{
$ids = join(',', array_column($elements, 'id'));
$maxChdate = count($elements) ? max(array_column($elements, 'chdate')) : '';
$payload = [$user->id, $ids, $maxChdate];
return 'W/"' . md5(join(',', $payload)) . '"';
}
}
|