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

namespace JsonApi\Schemas;

use JsonApi\Errors\InternalServerError;
use Neomerx\JsonApi\Contracts\Factories\FactoryInterface;
use Neomerx\JsonApi\Contracts\Schema\ContextInterface;
use Neomerx\JsonApi\Contracts\Schema\LinkInterface;
use Neomerx\JsonApi\Contracts\Schema\SchemaContainerInterface;
use Neomerx\JsonApi\Schema\BaseSchema;

abstract class SchemaProvider extends BaseSchema
{
    /** @var SchemaContainerInterface */
    protected $schemaContainer;

    /** @var ?\User */
    protected $currentUser;

    public function __construct(FactoryInterface $factory, SchemaContainerInterface $schemaContainer, ?\User $user)
    {
        $this->schemaContainer = $schemaContainer;
        $this->currentUser = $user;

        parent::__construct($factory);
    }

    const TYPE = '';

    public function getType(): string
    {
        return static::TYPE;
    }

    /**
     * @inheritdoc
     */
    public function isAddSelfLinkInRelationshipByDefault(string $relationshipName): bool
    {
        return false;
    }

    /**
     * @inheritdoc
     */
    public function isAddRelatedLinkInRelationshipByDefault(string $relationshipName): bool
    {
        return false;
    }

    /**
     * @param mixed $resource
     */
    public function createLinkToResource($resource): LinkInterface
    {
        if (!$this->schemaContainer->hasSchema($resource)) {
            throw new InternalServerError('Cannot create links to objects without schema.');
        }

        return $this->schemaContainer->getSchema($resource)->getSelfLink($resource);
    }

    /**
     * @param ContextInterface $context
     * @param string $key
     *
     * @return bool true, if the given relationship should be included in the response
     */
    public function shouldInclude(ContextInterface $context, string $key): bool
    {
        $path = $context->getPosition()->getLevel() ? $context->getPosition()->getPath() . '.' : '';

        return in_array($path . $key, $context->getIncludePaths());
    }
}