aboutsummaryrefslogtreecommitdiff
path: root/lib/classes/JsonApi/Routes/News/AbstractNewsCreate.php
blob: 0fb66a47eff4e625ff5ab5846dc8c6ec61a9e7ca (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
68
69
70
71
72
73
74
75
76
<?php

namespace JsonApi\Routes\News;

use JsonApi\Errors\InternalServerError;
use JsonApi\JsonApiController;
use JsonApi\Routes\ValidationTrait;

abstract class AbstractNewsCreate extends JsonApiController
{
    use StudipNewsDatesHelper, ValidationTrait;

    protected function validateResourceDocument($json, $data)
    {
        if (!self::arrayHas($json, 'data.attributes.title')) {
            return 'News must have a `title`.';
        }

        if (!self::arrayHas($json, 'data.attributes.content')) {
            return 'News must have `content`.';
        }

        if (!self::arrayHas($json, 'data.attributes.comments-allowed')) {
            return 'You should allow or not allow comments in your news.';
        }

        if ($error = $this->checkNewsDates($json)) {
            return $error;
        }
    }

    protected function createNewsFromJSON(\User $user, $range, array $json)
    {
        if (!(
                $range instanceof \Course ||
                $range instanceof \User ||
                'studip' === $range
            )) {
            throw new InternalServerError('`$range` has wrong type.');
        }

        $getField = function ($key, $default = null) use ($json) {
            return self::arrayGet($json, 'data.attributes.'.$key, $default);
        };

        $title = $getField('title');
        $content = $getField('content');
        if (method_exists(\Studip\Markup::class, 'purifyHtml')) {
            $content = \Studip\Markup::purifyHtml($content);
        }
        $commentsAllowed = (bool) $getField('comments-allowed');
        list($date, $expire) = self::convertTimestampsToDateExpire($getField('publication-start'), $getField('publication-end'));

        $news = \StudipNews::create(
            [
                'user_id' => $user->id,
                'topic' => $title,
                'body' => $content,
                'allow_comments' => $commentsAllowed,
                'date' => $date,
                'expire' => $expire,
            ]
        );

        if ($news) {
            $news->addRange(
                is_callable([$range, 'getId'])
                ? $range->getId()
                : $range
            );
            $news->store();
        }

        return $news;
    }
}