Passed
Pull Request — master (#2531)
by Antoine
03:26
created

ContextBuilder::getResourceContext()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 4
nc 2
nop 2
dl 0
loc 8
rs 10
c 0
b 0
f 0
1
<?php
2
3
/*
4
 * This file is part of the API Platform project.
5
 *
6
 * (c) Kévin Dunglas <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
declare(strict_types=1);
13
14
namespace ApiPlatform\Core\JsonLd;
15
16
use ApiPlatform\Core\Api\UrlGeneratorInterface;
17
use ApiPlatform\Core\Metadata\Property\Factory\PropertyMetadataFactoryInterface;
18
use ApiPlatform\Core\Metadata\Property\Factory\PropertyNameCollectionFactoryInterface;
19
use ApiPlatform\Core\Metadata\Resource\Factory\ResourceMetadataFactoryInterface;
20
use ApiPlatform\Core\Metadata\Resource\Factory\ResourceNameCollectionFactoryInterface;
21
use Symfony\Component\Serializer\NameConverter\NameConverterInterface;
22
23
/**
24
 * {@inheritdoc}
25
 *
26
 * @author Kévin Dunglas <[email protected]>
27
 */
28
final class ContextBuilder implements AnonymousContextBuilderInterface
29
{
30
    const FORMAT = 'jsonld';
31
32
    private $resourceNameCollectionFactory;
33
    private $resourceMetadataFactory;
34
    private $propertyNameCollectionFactory;
35
    private $propertyMetadataFactory;
36
    private $urlGenerator;
37
38
    /**
39
     * @var NameConverterInterface|null
40
     */
41
    private $nameConverter;
42
43
    public function __construct(ResourceNameCollectionFactoryInterface $resourceNameCollectionFactory, ResourceMetadataFactoryInterface $resourceMetadataFactory, PropertyNameCollectionFactoryInterface $propertyNameCollectionFactory, PropertyMetadataFactoryInterface $propertyMetadataFactory, UrlGeneratorInterface $urlGenerator, NameConverterInterface $nameConverter = null)
44
    {
45
        $this->resourceNameCollectionFactory = $resourceNameCollectionFactory;
46
        $this->resourceMetadataFactory = $resourceMetadataFactory;
47
        $this->propertyNameCollectionFactory = $propertyNameCollectionFactory;
48
        $this->propertyMetadataFactory = $propertyMetadataFactory;
49
        $this->urlGenerator = $urlGenerator;
50
        $this->nameConverter = $nameConverter;
51
    }
52
53
    /**
54
     * {@inheritdoc}
55
     */
56
    public function getBaseContext(int $referenceType = UrlGeneratorInterface::ABS_URL): array
57
    {
58
        return [
59
            '@vocab' => $this->urlGenerator->generate('api_doc', ['_format' => self::FORMAT], UrlGeneratorInterface::ABS_URL).'#',
60
            'hydra' => self::HYDRA_NS,
61
        ];
62
    }
63
64
    /**
65
     * {@inheritdoc}
66
     */
67
    public function getEntrypointContext(int $referenceType = UrlGeneratorInterface::ABS_PATH): array
68
    {
69
        $context = $this->getBaseContext($referenceType);
70
71
        foreach ($this->resourceNameCollectionFactory->create() as $resourceClass) {
72
            $resourceMetadata = $this->resourceMetadataFactory->create($resourceClass);
73
74
            $resourceName = lcfirst($resourceMetadata->getShortName());
75
76
            $context[$resourceName] = [
77
                '@id' => 'Entrypoint/'.$resourceName,
78
                '@type' => '@id',
79
            ];
80
        }
81
82
        return $context;
83
    }
84
85
    /**
86
     * {@inheritdoc}
87
     */
88
    public function getResourceContext(string $resourceClass, int $referenceType = UrlGeneratorInterface::ABS_PATH): array
89
    {
90
        $metadata = $this->resourceMetadataFactory->create($resourceClass);
91
        if (null === $shortName = $metadata->getShortName()) {
92
            return [];
93
        }
94
95
        return $this->getResourceContextWithShortname($resourceClass, $referenceType, $shortName);
96
    }
97
98
    /**
99
     * {@inheritdoc}
100
     */
101
    public function getResourceContextUri(string $resourceClass, int $referenceType = UrlGeneratorInterface::ABS_PATH): string
102
    {
103
        $resourceMetadata = $this->resourceMetadataFactory->create($resourceClass);
104
105
        return $this->urlGenerator->generate('api_jsonld_context', ['shortName' => $resourceMetadata->getShortName()], $referenceType);
106
    }
107
108
    /**
109
     * {@inheritdoc}
110
     */
111
    public function getAnonymousResourceContext($object, array $context, int $referenceType = UrlGeneratorInterface::ABS_PATH): array
112
    {
113
        $id = $context['iri'] ?? '_:'.(\function_exists('spl_object_id') ? spl_object_id($object) : spl_object_hash($object));
114
        $jsonLdContext = [
115
            '@context' => $this->getResourceContextWithShortname(\get_class($object), $referenceType, $id),
116
            '@id' => $id,
117
        ];
118
119
        if ($context['name'] ?? false) {
120
            $jsonLdContext['@type'] = $context['name'];
121
        }
122
123
        return $jsonLdContext;
124
    }
125
126
    private function getResourceContextWithShortname(string $resourceClass, int $referenceType = UrlGeneratorInterface::ABS_PATH, string $shortName)
127
    {
128
        $context = $this->getBaseContext($referenceType);
129
130
        foreach ($this->propertyNameCollectionFactory->create($resourceClass) as $propertyName) {
131
            $propertyMetadata = $this->propertyMetadataFactory->create($resourceClass, $propertyName);
132
133
            if ($propertyMetadata->isIdentifier() && true !== $propertyMetadata->isWritable()) {
134
                continue;
135
            }
136
137
            $convertedName = $this->nameConverter ? $this->nameConverter->normalize($propertyName) : $propertyName;
138
            $jsonldContext = $propertyMetadata->getAttributes()['jsonld_context'] ?? [];
139
140
            if (!$id = $propertyMetadata->getIri()) {
141
                $id = sprintf('%s/%s', $shortName, $convertedName);
142
            }
143
144
            if (true !== $propertyMetadata->isReadableLink()) {
145
                $jsonldContext += [
146
                    '@id' => $id,
147
                    '@type' => '@id',
148
                ];
149
            }
150
151
            if (empty($jsonldContext)) {
152
                $context[$convertedName] = $id;
153
            } else {
154
                $context[$convertedName] = $jsonldContext + [
155
                    '@id' => $id,
156
                ];
157
            }
158
        }
159
160
        return $context;
161
    }
162
}
163