aboutsummaryrefslogtreecommitdiff
path: root/lib/classes/JsonApi/Routes/Courseware/DescendantsOfPublicStructuralElementsIndex.php
blob: e01aa4afc2f370b7fa3f5cdda4bae25d1529512c (plain)
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
<?php

namespace JsonApi\Routes\Courseware;

use Courseware\StructuralElement;
use Courseware\PublicLink;
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 DescendantsOfPublicStructuralElementsIndex extends JsonApiController
{
    protected $allowedPagingParameters = ['offset', 'limit'];

    protected $allowedIncludePaths = ['containers', 'parent'];

    /**
     * @SuppressWarnings(PHPMD.UnusedFormalParameter)
     */
    public function __invoke(Request $request, Response $response, $args)
    {
        /** @var ?StructuralElement $resource */
        $resource = StructuralElement::find($args['id']);
        $publicLink = PublicLink::find($args['link_id']);

        if (!$publicLink) {
            throw new RecordNotFoundException();
        }
        if (!$resource) {
            throw new RecordNotFoundException();
        }

        if (!$publicLink->canVisitElement($resource)) {
            throw new AuthorizationFailedException();
        }

        $descendants = $resource->findDescendants();

        [$offset, $limit] = $this->getOffsetAndLimit();
        $page = array_slice($descendants, $offset, $limit);
        $total = count($descendants);

        return $this->getPaginatedContentResponse(
            $page,
            $total
        );
    }
}