aboutsummaryrefslogtreecommitdiff
path: root/lib/classes/JsonApi/Schemas/StudipComment.php
blob: 0232c15024a41cab9cd7a0e97a202b202faf0801 (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
<?php

namespace JsonApi\Schemas;

use Neomerx\JsonApi\Contracts\Schema\ContextInterface;
use Neomerx\JsonApi\Schema\Link;

class StudipComment extends SchemaProvider
{
    const TYPE = 'comments';
    const REL_AUTHOR = 'author';
    const REL_NEWS = 'news';

    public function getId($comment): ?string
    {
        return $comment->comment_id;
    }

    public function getAttributes($comment, ContextInterface $context): iterable
    {
        return [
            'content' => $comment->content,
            'mkdate' => date('c', $comment->mkdate),
            'chdate' => date('c', $comment->chdate),
        ];
    }

    public function getRelationships($comment, ContextInterface $context): iterable
    {
        $isPrimary = $context->getPosition()->getLevel() === 0;

        $relationships = [];

        if ($isPrimary) {
            if ($author = \User::find($comment->user_id)) {
                $relationships[self::REL_AUTHOR] = [
                    self::RELATIONSHIP_LINKS => [
                        Link::RELATED => $this->createLinkToResource($author),
                    ],
                    self::RELATIONSHIP_DATA => $author,
                ];
            }

            if ($news = \StudipNews::find($comment->object_id)) {
                $relationships[self::REL_NEWS] = [
                    self::RELATIONSHIP_LINKS => [
                        Link::RELATED => $this->createLinkToResource($news),
                    ],
                    self::RELATIONSHIP_DATA => $news,
                ];
            }
        }

        return $relationships;
    }
}