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

namespace JsonApi\Routes\Courseware;

use Courseware\Unit;
use JsonApi\Errors\AuthorizationFailedException;
use JsonApi\Errors\BadRequestException;
use JsonApi\JsonApiController;
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;

/**
 * Update multiple Unit positions.
 *
 * @author  Ron Lucke <lucke@elan-ev.de>
 * @license GPL2 or any later version
 *
 * @since   Stud.IP 5.5
 */

class UnitsSort extends JsonApiController
{
    public function __invoke(Request $request, Response $response, $args)
    {
        $range = $this->getRange($args);
        $user = $this->getUser($request);

        if (!Authority::canSortUnit($user, $range)) {
            throw new AuthorizationFailedException();
        }
        $data = $request->getParsedBody()['data'];
        $positions = $data['positions'];
        $unitCount = Unit::getNewPosition($range->id);

        if (count($positions) !== $unitCount) {
            throw new BadRequestException('Fehler beim Sortieren der Lernmaterialien.');
        }

        Unit::updatePositions($range, $positions);

        $response = $response->withHeader('Content-Type', 'application/json');

        return $response;
    }

    private function getRange($args): ?\Range
    {
        try {
            return \RangeFactory::createRange(
                $this->getRangeType($args['type']),
                $args['id']
            );
        } catch (\Exception $e) {
            return null;
        }
    }
    
    private function getRangeType($type): ?string
    {
        $type_map = [
            'courses' => 'course',
            'users'   => 'user',
        ];

        return $type_map[$type] ?? null;
    }
}