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

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 Studip\Markup;
use Forum\Posting;

class PostingUpdate extends JsonApiController
{
    use ValidationTrait;

    protected $allowedIncludePaths = [
        \JsonApi\Schemas\Forum\Posting::REL_DISCUSSION,
        \JsonApi\Schemas\Forum\Posting::REL_POSTING,
        \JsonApi\Schemas\Forum\Posting::REL_OPENGRAPH_URLS,
        \JsonApi\Schemas\Forum\Posting::REL_AUTHOR,
        \JsonApi\Schemas\Forum\Posting::REL_REACTIONS,
        \JsonApi\Schemas\Forum\Posting::REL_REACTIONS_USER
    ];

    public function __invoke(Request $request, Response $response, $args)
    {
        $posting = Posting::find($args['posting_id']);
        if (!$posting) {
            throw new RecordNotFoundException();
        }

        if (
            !Authority::canEditPost($this->getUser($request), $posting, (bool) $posting->discussion->closed_at)
        ) {
            throw new AuthorizationFailedException();
        }

        $json = $this->validate($request);
        $posting->content = Markup::purifyHtml(Markup::markAsHtml(self::arrayGet($json, 'data.attributes.content')));
        $posting->anonymous = (self::arrayGet($json, 'data.attributes.anonymous') && \Config::get()->FORUM_ANONYMOUS_POSTINGS);
        $posting->store();

        return $this->getCreatedResponse($posting);
    }

    protected function validateResourceDocument($json, $data)
    {
        $required_keys = [
            'data.attributes.content' => 'Missing `data.attributes.content`',
            'data.attributes.anonymous' => 'Missing `data.attributes.anonymous`',
        ];

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

        return null;
    }
}