aboutsummaryrefslogtreecommitdiff
path: root/lib/classes/JsonApi/Schemas/Clipboard.php
blob: af90d73daf2f2195238359f5530632fbfbe0105f (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
79
80
81
<?php
namespace JsonApi\Schemas;

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

final class Clipboard extends SchemaProvider
{
    public const TYPE = 'clipboards';
    public const REL_USER = 'user';
    public const REL_ITEMS = 'clipboard-items';

    /**
     * @param \Clipboard $resource
     */
    public function getId($resource): ?string
    {
        return (string) $resource->id;
    }

    /**
     * @param \Clipboard $resource
     */
    public function getAttributes($resource, ContextInterface $context): iterable
    {
        return [
            'name'              => $resource->name,
            'handler'           => $resource->handler,
            'allows_item_class' => $resource->allowed_item_class,
            'mkdate'            => date('c', $resource->mkdate),
            'chdate'            => date('c', $resource->chdate),
        ];
    }

    /**
     * @param \Clipboard $resource
     */
    public function getRelationships($resource, ContextInterface $context): iterable
    {
        $relationships = [];

        $isPrimary = $context->getPosition()->getLevel() === 0;
        if ($isPrimary) {
            $relationships = $this->getUserRelationship($relationships, $resource, $this->shouldInclude($context, self::REL_USER));
            $relationships = $this->getItemsRelationship($relationships, $resource, $this->shouldInclude($context, self::REL_ITEMS));
        }


        return $relationships;
    }

    private function getUserRelationship(array $relationships, \Clipboard $clipboard, bool $includeData): array
    {
        $relationships[self::REL_USER] = [
            self::RELATIONSHIP_LINKS => [
                Link::RELATED => $this->createLinkToResource($clipboard->user),
            ],
            self::RELATIONSHIP_DATA => $includeData ? $clipboard->user : \User::build(['id' => $clipboard->user_id], false),
        ];

        return $relationships;
    }

    private function getItemsRelationship(array $relationships, \Clipboard $clipboard, bool $includeData): array
    {
        if ($includeData) {
            $relatedItems = $clipboard->items;
        } else {
            $relatedItems = $clipboard->items->map(fn($item) => \ClipboardItem::build(['id' => $item->id], false));
        }

        $relationships[self::REL_ITEMS] = [
            self::RELATIONSHIP_LINKS => [
                Link::RELATED => $this->getRelationshipRelatedLink($clipboard, self::REL_ITEMS),
            ],
            self::RELATIONSHIP_DATA => $relatedItems,
        ];

        return $relationships;
    }
}