aboutsummaryrefslogtreecommitdiff
path: root/lib/classes/JsonApi/Schemas/File.php
blob: df0263a5eaa0d902a246c17cef95a9b9c8b67146 (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
82
<?php

namespace JsonApi\Schemas;

use JsonApi\Routes\Files\Authority as FilesAuthority;
use Neomerx\JsonApi\Contracts\Schema\ContextInterface;
use Neomerx\JsonApi\Schema\Link;

class File extends SchemaProvider
{
    const TYPE = 'files';

    const REL_FILE_REFS = 'file-refs';
    const REL_OWNER = 'owner';

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

    public function getAttributes($resource, ContextInterface $context): iterable
    {
        $attributes = [
            'name' => $resource['name'],
            'mime-type' => $resource['mime_type'],
            'filesize' => (int) $resource['size'],

            'mkdate' => date('c', $resource['mkdate']),
            'chdate' => date('c', $resource['chdate']),
        ];

        if (!empty($resource['metadata']['url'])) {
            if (FilesAuthority::canUpdateFile($this->currentUser, $resource)) {
                $attributes['url'] = $resource['metadata']['url'];
            }
        }

        return $attributes;
    }

    /**
     * @SuppressWarnings(PHPMD.UnusedFormalParameter)
     */
    public function getRelationships($resource, ContextInterface $context): iterable
    {
        $isPrimary = $context->getPosition()->getLevel() === 0;

        $relationships = [];

        if ($isPrimary) {
            $relationships = $this->addOwnerRelationship($relationships, $resource);
            $relationships = $this->addFileRefsRelationship($relationships, $resource);
        }

        return $relationships;
    }

    private function addFileRefsRelationship(array $relationships, \File $resource)
    {
        $refs = $resource->refs;

        $relationships[self::REL_FILE_REFS] = [
            self::RELATIONSHIP_LINKS_SELF => true,
            self::RELATIONSHIP_DATA => $refs,
        ];

        return $relationships;
    }

    private function addOwnerRelationship(array $relationships, \File $resource)
    {
        if ($resource->user_id) {
            $relationships[self::REL_OWNER] = [
                self::RELATIONSHIP_LINKS => [
                    Link::RELATED => $this->createLinkToResource($resource->owner),
                ],
            ];
        }

        return $relationships;
    }
}