aboutsummaryrefslogtreecommitdiff
path: root/lib/classes/JsonApi/Routes/Forum/TopicUpdateSort.php
blob: 919d2a9581f1dff88f352d23b347e678ec1b9f41 (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
<?php
namespace JsonApi\Routes\Forum;

use CoreForum;
use JsonApi\Errors\RecordNotFoundException;
use Psr\Http\Message\ServerRequestInterface as Request;
use Psr\Http\Message\ResponseInterface as Response;
use JsonApi\Errors\AuthorizationFailedException;
use JsonApi\JsonApiController;
use JsonApi\Routes\ValidationTrait;
use Forum\Topic;

class TopicUpdateSort extends JsonApiController
{
    use ValidationTrait;

    public function __invoke(Request $request, Response $response, $args)
    {
        $json = $this->validate($request);
        $range_id = self::arrayGet($json, 'data.relationships.range.data.id');

        $range = get_object_by_range_id($range_id);
        if (!$range) {
            throw new RecordNotFoundException();
        }

        if (!CoreForum::isModerator($range->id)) {
            throw new AuthorizationFailedException();
        }

        $topic_ids = self::arrayGet($json, 'data.attributes.topic-ids');

        Topic::findEachBySQL(
            function (Topic $topic) use ($topic_ids) {
                $topic->position = (int) array_search($topic->topic_id, $topic_ids);
                $topic->store();
            },
            "topic_id IN (:topic_ids) AND range_id = :course_id",
            [
                "topic_ids" => $topic_ids,
                "course_id" => $range->id
            ]
        );

        return $this->getCodeResponse(204);
    }

    protected function validateResourceDocument($json, $data)
    {
        $required_keys = [
            'data.attributes.topic-ids' => 'Missing `data.attributes.topic-ids`',
            'data.relationships.range.data.id' => 'Missing `data.relationships.range.data.id`',
        ];

        foreach ($required_keys as $key => $error_message) {
            if (!self::arrayHas($json, $key)) {
                return $error_message;
            }
        }

        return null;
    }
}