aboutsummaryrefslogtreecommitdiff
path: root/lib/classes/JsonApi/Routes/Courses/CoursesByModuleComponentsIndex.php
blob: e7eaee9e610331015e7aa1abdba65c859215639c (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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
<?php

namespace JsonApi\Routes\Courses;

use Modulteil;
use Course;
use JsonApi\Errors\BadRequestException;
use JsonApi\Errors\RecordNotFoundException;
use JsonApi\JsonApiController;
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Semester;

class CoursesByModuleComponentsIndex extends JsonApiController
{
    protected $allowedIncludePaths = [
        'blubber-threads',
        'end-semester',
        'events',
        'feedback-elements',
        'file-refs',
        'folders',
        'forum-categories',
        'institute',
        'memberships',
        'news',
        'participating-institutes',
        'sem-class',
        'sem-type',
        'start-semester',
        'status-groups',
        'wiki-pages',
    ];

    protected $allowedPagingParameters = ['offset', 'limit'];

    protected $allowedFilteringParameters = ['semester', 'df'];

    /**
     * @SuppressWarnings(PHPMD.UnusedFormalParameter)
     */
    public function __invoke(Request $request, Response $response, ?array $args): Response
    {
        $component = Modulteil::find($args['id']);
        if (!$component) {
            throw new RecordNotFoundException();
        }

        $filtering = $this->getQueryParameters()->getFilteringParameters() ?: [];

        $error = $this->validateFilters($filtering);
        if ($error) {
            throw new BadRequestException($error);
        }

        $courses = $this->findCoursesByComponent(
            $component,
            $filtering
        );
        [$offset, $limit] = $this->getOffsetAndLimit();

        return $this->getPaginatedContentResponse(
            array_slice($courses, $offset, $limit),
            count($courses)
        );
    }

    private function validateFilters(array $filtering): ?string
    {
        // semester
        if (
            isset($filtering['semester'])
            && !Semester::exists($filtering['semester'])
        ) {
            return 'Invalid "semester".';
        }

        // data fields
        if (isset($filtering['df']) && is_array($filtering['df'])) {
            $accepted_dfs = $this->getAcceptedDataFields();
            foreach (array_keys($filtering['df']) as $df) {
                if (!in_array($df, $accepted_dfs)) {
                    return 'Invalid data field as filtering parameter.';
                }
            }
        }
        return null;
    }

    /**
     * Get ids of accepted datafields for current user.
     * Only simple types of bool, textline, selectbox and radio with global
     * visibility for all users are accepted.
     *
     * @return array Accepted datafields
     */
    private function getAcceptedDataFields(): array
    {
        $data_fields = \DataField::findAndMapBySQL(
            fn(\DataField $data_field) => $data_field->id,
            "`object_type` = 'sem' AND `view_perms` = 'user'
                AND `type` IN('bool', 'textline', 'selectbox', 'radio')"
        );
        return $data_fields;
    }

    private function getSemesterFilter(array $filtering): ?Semester
    {
        if (!isset($filtering['semester'])) {
            return null;
        }
        return Semester::find($filtering['semester']);
    }


    /**
     * Finds visible courses by given module component.
     *
     * @param Modulteil $component
     * @param Semester|null $semester
     *
     * @return Course[] Visible courses assigned to module component
     */
    private function findCoursesByComponent(Modulteil $component, array $filtering): array
    {
        $course_ids = [];
        foreach ($component->lvgruppen as $lvgruppe) {
            $course_ids += $lvgruppe->courses->findBy('visible', '1')->pluck('id');
        }
        if (count($course_ids) === 0) {
            return [];
        }

        if (isset($filtering['df']) && is_array($filtering['df'])) {
            $df_course_ids = $course_ids;
            foreach ($filtering['df'] as $id => $value) {
                $df_course_ids = array_intersect($df_course_ids, \DatafieldEntryModel::findAndMapBySQL(
                    fn($df) => $df->range_id,
                    '`datafield_id` = ? AND `range_id` IN (?) AND `content` = ?',
                    [$id, $course_ids, $value]
                ));
            }

            $course_ids = array_merge_recursive($df_course_ids);
        }
        $courses = Course::findMany(
            $course_ids,
            'ORDER BY name'
        );

        $semester = $this->getSemesterFilter($filtering);
        if ($semester) {
            $courses = array_filter($courses, fn(\Course $course) => $course->isInSemester($semester));
        }

        return $courses;
    }
}