aboutsummaryrefslogtreecommitdiff
path: root/lib/classes/JsonApi/Routes/Consultations/BlocksByRangeIndex.php
blob: 41474b763c5b79864fba2b766322c24525cdde56 (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
55
56
57
58
59
60
61
62
63
64
65
<?php
namespace JsonApi\Routes\Consultations;

use JsonApi\Errors\AuthorizationFailedException;
use JsonApi\Errors\RecordNotFoundException;
use JsonApi\JsonApiController;
use JsonApi\Schemas\ConsultationBlock;
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;

/**
 * Displays all consultation blocks of a range
 */
class BlocksByRangeIndex extends JsonApiController
{
    use FilterTrait;

    protected $allowedIncludePaths = [
        ConsultationBlock::REL_SLOTS,
        ConsultationBlock::REL_RANGE,
    ];
    protected $allowedPagingParameters = ['offset', 'limit'];
    protected $allowedFilteringParameters = ['current', 'expired'];

    public function __invoke(Request $request, Response $response, $args)
    {
        $this->validateFilters();

        $range_id = $args['id'];
        $range_type = substr($args['type'], 0, -1); // Strips trailing plural s

        $range = \RangeFactory::createRange($range_type, $range_id);
        if ($range->isNew()) {
            throw new RecordNotFoundException();
        }

        if (!Authority::canShowRange($this->getUser($request), $range)) {
            throw new AuthorizationFailedException();
        }

        [$offset, $limit] = $this->getOffsetAndLimit();

        $filters = $this->getFilters();
        $blocks = $this->getBlocks($range, $filters);

        return $this->getPaginatedContentResponse(
            $blocks->limit($offset, $limit)->getArrayCopy(),
            count($blocks)
        );
    }

    private function getBlocks(\Range $range, array $filters): \SimpleCollection
    {
        if (!$filters['current'] && !$filters['expired']) {
            return \SimpleCollection::createFromArray([]);
        }

        if ($filters['current'] && $filters['expired']) {
            return $range->consultation_blocks;
        }

        $blocks = \ConsultationBlock::findByRange($range, 'ORDER BY start', $filters['expired']);
        return \SimpleCollection::createFromArray($blocks);
    }
}