Passed
Pull Request — 2.4 (#2495)
by Antoine
04:02
created

ContextBuilder::getResourceContext()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 2
dl 0
loc 3
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 IOContextBuilderInterface
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
        return $this->getResourceContextWithShortname($resourceClass, $referenceType, $this->resourceMetadataFactory->create($resourceClass)->getShortName());
0 ignored issues
show
Bug introduced by
It seems like $this->resourceMetadataF...eClass)->getShortName() can also be of type null; however, parameter $shortName of ApiPlatform\Core\JsonLd\...eContextWithShortname() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

90
        return $this->getResourceContextWithShortname($resourceClass, $referenceType, /** @scrutinizer ignore-type */ $this->resourceMetadataFactory->create($resourceClass)->getShortName());
Loading history...
91
    }
92
93
    /**
94
     * {@inheritdoc}
95
     */
96
    public function getResourceContextUri(string $resourceClass, int $referenceType = UrlGeneratorInterface::ABS_PATH): string
97
    {
98
        $resourceMetadata = $this->resourceMetadataFactory->create($resourceClass);
99
100
        return $this->urlGenerator->generate('api_jsonld_context', ['shortName' => $resourceMetadata->getShortName()], $referenceType);
101
    }
102
103
    /**
104
     * {@inheritdoc}
105
     */
106
    public function getIOResourceContext($object, array $context, int $referenceType = UrlGeneratorInterface::ABS_PATH): array
107
    {
108
        $id = $context['iri'] ?? '_:'.spl_object_id($object);
109
        $jsonLdContext = [
110
            '@context' => $this->getResourceContextWithShortname(\get_class($object), $referenceType, $id),
111
            '@id' => $id,
112
        ];
113
114
        if ($context['name'] ?? false) {
115
            $jsonLdContext['@type'] = $context['name'];
116
        }
117
118
        return $jsonLdContext;
119
    }
120
121
    private function getResourceContextWithShortname(string $resourceClass, int $referenceType = UrlGeneratorInterface::ABS_PATH, string $shortName)
122
    {
123
        $context = $this->getBaseContext($referenceType);
124
125
        foreach ($this->propertyNameCollectionFactory->create($resourceClass) as $propertyName) {
126
            $propertyMetadata = $this->propertyMetadataFactory->create($resourceClass, $propertyName);
127
128
            if ($propertyMetadata->isIdentifier() && true !== $propertyMetadata->isWritable()) {
129
                continue;
130
            }
131
132
            $convertedName = $this->nameConverter ? $this->nameConverter->normalize($propertyName) : $propertyName;
133
            $jsonldContext = $propertyMetadata->getAttributes()['jsonld_context'] ?? [];
134
135
            if (!$id = $propertyMetadata->getIri()) {
136
                $id = sprintf('%s/%s', $shortName, $convertedName);
137
            }
138
139
            if (true !== $propertyMetadata->isReadableLink()) {
140
                $jsonldContext += [
141
                    '@id' => $id,
142
                    '@type' => '@id',
143
                ];
144
            }
145
146
            if (empty($jsonldContext)) {
147
                $context[$convertedName] = $id;
148
            } else {
149
                $context[$convertedName] = $jsonldContext + [
150
                    '@id' => $id,
151
                ];
152
            }
153
        }
154
155
        return $context;
156
    }
157
}
158