aboutsummaryrefslogtreecommitdiff
path: root/lib/classes/JsonApi/Routes/Blubber/ThreadsCreate.php
blob: d503157b93516b55e4c7d93ba3c018e0e12bb2d1 (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
<?php

namespace JsonApi\Routes\Blubber;

use JsonApi\Errors\AuthorizationFailedException;
use JsonApi\Errors\BadRequestException;
use JsonApi\JsonApiController;
use JsonApi\Routes\ValidationTrait;
use JsonApi\Schemas\BlubberThread as Schema;
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;

/**
 * Create a new private blubber thread.
 */
class ThreadsCreate extends JsonApiController
{
    use ValidationTrait;

    /**
     * @SuppressWarnings(PHPMD.UnusedFormalParameter)
     */
    public function __invoke(Request $request, Response $response, $args)
    {
        $json = $this->validate($request);

        if (!Authority::canCreatePrivateBlubberThread($user = $this->getUser($request))) {
            throw new AuthorizationFailedException();
        }

        $contextType = self::arrayGet($json, 'data.attributes.context-type', '');
        if ('private' !== $contextType) {
            throw new BadRequestException('Only blubber threads of context-type=private can be created.');
        }

        $thread = \BlubberThread::create(
            [
                'context_type' => 'private',
                'context_id' => 'global',
                'user_id' => $user->id,
                'external_contact' => 0,
                'display_class' => null,
                'visible_in_stream' => 1,
                'commentable' => 1,
                'content' => '',
            ]
        );

        \BlubberMention::create(['thread_id' => $thread->id, 'user_id' => $user->id]);

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

    protected function validateResourceDocument($json)
    {
        if (Schema::TYPE !== self::arrayGet($json, 'data.type')) {
            return 'Missing or wrong type.';
        }

        if (!self::arrayHas($json, 'data.attributes.context-type')) {
            return 'Attribute \'context-type\' is required.';
        }
    }
}