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

namespace JsonApi\Routes\Courseware;

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

/**
* Copy an courseware unit into a course or users contents
*
* @author  Ron Lucke <lucke@elan-ev.de>
* @license GPL2 or any later version
*
* @since   Stud.IP 5.3
*/

class UnitsCopy extends NonJsonApiController
{
    public function __invoke(Request $request, Response $response, array $args)
    {
        $data = $request->getParsedBody()['data'];

        $sourceUnit = Unit::find($args['id']);
        $user = $this->getUser($request);
        $rangeId = $data['rangeId'];
        $rangeType = $data['rangeType'];
        $modified = $data['modified'];
        $duplicate = $data['duplicate'];

        try {
            $range = \RangeFactory::createRange($rangeType, $rangeId);
        } catch (\Exception $e) {
            throw new RecordNotFoundException('Range could not be found');
        }

        if (!Authority::canCreateUnit($user, $range)) {
            throw new AuthorizationFailedException();
        }

        $newUnit = $sourceUnit->copy($user, $rangeId, $rangeType, $modified, $duplicate);

        $response = $response->withHeader('Content-Type', 'application/json');
        $response->getBody()->write((string) json_encode($newUnit));

        return $response;
    }
}