aboutsummaryrefslogtreecommitdiff
path: root/lib/classes/JsonApi/Routes/Courseware/CoursewareInstancesHelper.php
blob: aff2916aaf0df14fc683bb6b7cee673b6a8665c3 (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
<?php

namespace JsonApi\Routes\Courseware;

use Courseware\Instance;
use Courseware\StructuralElement;
use Courseware\Unit;
use JsonApi\Errors\BadRequestException;
use JsonApi\Errors\RecordNotFoundException;

trait CoursewareInstancesHelper
{
    private function findInstance(string $instanceId): Instance
    {
        [$rangeType, $rangeId] = explode('_', $instanceId);
        if (!is_string($rangeType) || !is_string($rangeId)) {
            throw new BadRequestException('Invalid instance id: "' . $instanceId . '".');
        }

        return $this->findInstanceWithRange($rangeType, $rangeId);
    }

    private function findInstanceWithRange(string $rangeType, string $rangeId): Instance
    {
        $methods = [
            'course' => 'getCoursewareCourse',
            'courses' => 'getCoursewareCourse',
            'user' => 'getCoursewareUser',
            'users' => 'getCoursewareUser',
            'sharedusers' => 'getSharedCoursewareUser',
        ];
        if (!($method = $methods[$rangeType])) {
            throw new BadRequestException('Invalid range type: "' . $rangeType . '".');
        }

        $root = null;
        if ($rangeType !== 'sharedusers') {
            $chunks = explode('_', $rangeId);
            $courseId = $chunks[0];
            $unitId = $chunks[1] ?? null;
            if ($unitId === '') {
                throw new BadRequestException('Unit id must not be empty.');
            }
            if ($unitId) {
                $unit = Unit::findOneBySQL('range_id = ? AND id = ?', [$courseId, $unitId]);
            } else {
                $unit = Unit::findOneBySQL('range_id = ?', [$courseId]);
            }
            if ($unit) {
                $root = $unit->structural_element;
            }
        } else {
            $root = StructuralElement::$method($rangeId);
        }
        if (!$root) {
            throw new RecordNotFoundException();
        }

        return new Instance($root);
    }
}