aboutsummaryrefslogtreecommitdiff
path: root/lib/classes/JsonApi/Schemas/Degree.php
blob: 05a308062b94efc3740d47d8edf5287dfe39529d (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
77
78
<?php

namespace JsonApi\Schemas;

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

class Degree extends SchemaProvider
{
    const TYPE = 'degrees';

    const REL_AUTHOR = 'author';
    const REL_EDITOR = 'editor';

    public function getId($resource): ?string
    {
        return $resource->id;
    }

    public function getAttributes($resource, ContextInterface $context): iterable
    {
        return [
            'name' => $resource->name,
            'shortname' => $resource->name_kurz,
            'description' => $resource->beschreibung,
            'mkdate' => date('c', $resource->mkdate),
            'chdate' => date('c', $resource->chdate)
        ];
    }

    public function getRelationships($resource, ContextInterface $context): iterable
    {
        $relationships = [];

        $relationships = $this->getAuthorRelationship($relationships, $resource, $this->shouldInclude($context, self::REL_AUTHOR));
        $relationships = $this->getEditorRelationship($relationships, $resource, $this->shouldInclude($context, self::REL_EDITOR));

        return $relationships;
    }

    private function getAuthorRelationship(array $relationships, \Degree $degree, $includeData)
    {
        $author = \User::find($degree->author_id);

        if ($author) {
            $relationships[self::REL_AUTHOR] = [
                self::RELATIONSHIP_LINKS => [
                    Link::RELATED => $this->createLinkToResource($author),
                ]
            ];

            if ($includeData) {
                $relationships[self::REL_AUTHOR][self::RELATIONSHIP_DATA] = $author;
            }
        }

        return $relationships;
    }

    private function getEditorRelationship(array $relationships, \Degree $degree, $includeData)
    {
        $editor = \User::find($degree->editor_id);

        if ($editor) {
            $relationships[self::REL_EDITOR] = [
                self::RELATIONSHIP_LINKS => [
                    Link::RELATED => $this->createLinkToResource($editor),
                ]
            ];

            if ($includeData) {
                $relationships[self::REL_EDITOR][self::RELATIONSHIP_DATA] = $editor;
            }
        }

        return $relationships;
    }
}