• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

api-platform / core / 13857636175

14 Mar 2025 01:29PM UTC coverage: 8.803% (+0.3%) from 8.515%
13857636175

Pull #7020

github

web-flow
Merge c3649d84d into 1e7076c65
Pull Request #7020: feat(laravel): stateOptions modelClass for eloquent

0 of 29 new or added lines in 7 files covered. (0.0%)

2656 existing lines in 185 files now uncovered.

10732 of 121908 relevant lines covered (8.8%)

7.84 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

69.09
/src/Hydra/Serializer/DocumentationNormalizer.php
1
<?php
2

3
/*
4
 * This file is part of the API Platform project.
5
 *
6
 * (c) Kévin Dunglas <dunglas@gmail.com>
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\Hydra\Serializer;
15

16
use ApiPlatform\Documentation\Documentation;
17
use ApiPlatform\JsonLd\ContextBuilder;
18
use ApiPlatform\JsonLd\ContextBuilderInterface;
19
use ApiPlatform\JsonLd\Serializer\HydraPrefixTrait;
20
use ApiPlatform\Metadata\ApiProperty;
21
use ApiPlatform\Metadata\ApiResource;
22
use ApiPlatform\Metadata\CollectionOperationInterface;
23
use ApiPlatform\Metadata\ErrorResource;
24
use ApiPlatform\Metadata\HttpOperation;
25
use ApiPlatform\Metadata\Operation;
26
use ApiPlatform\Metadata\Property\Factory\PropertyMetadataFactoryInterface;
27
use ApiPlatform\Metadata\Property\Factory\PropertyNameCollectionFactoryInterface;
28
use ApiPlatform\Metadata\Resource\Factory\ResourceMetadataCollectionFactoryInterface;
29
use ApiPlatform\Metadata\Resource\ResourceMetadataCollection;
30
use ApiPlatform\Metadata\ResourceClassResolverInterface;
31
use ApiPlatform\Metadata\UrlGeneratorInterface;
32
use Symfony\Component\PropertyInfo\Type;
33
use Symfony\Component\Serializer\NameConverter\NameConverterInterface;
34
use Symfony\Component\Serializer\Normalizer\AbstractNormalizer;
35
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
36

37
use const ApiPlatform\JsonLd\HYDRA_CONTEXT;
38

39
/**
40
 * Creates a machine readable Hydra API documentation.
41
 *
42
 * @author Kévin Dunglas <dunglas@gmail.com>
43
 */
44
final class DocumentationNormalizer implements NormalizerInterface
45
{
46
    use HydraPrefixTrait;
47
    public const FORMAT = 'jsonld';
48

49
    public function __construct(
50
        private readonly ResourceMetadataCollectionFactoryInterface $resourceMetadataFactory,
51
        private readonly PropertyNameCollectionFactoryInterface $propertyNameCollectionFactory,
52
        private readonly PropertyMetadataFactoryInterface $propertyMetadataFactory,
53
        private readonly ResourceClassResolverInterface $resourceClassResolver,
54
        private readonly UrlGeneratorInterface $urlGenerator,
55
        private readonly ?NameConverterInterface $nameConverter = null,
56
        private readonly ?array $defaultContext = [],
57
    ) {
58
    }
442✔
59

60
    /**
61
     * {@inheritdoc}
62
     */
63
    public function normalize(mixed $object, ?string $format = null, array $context = []): array|string|int|float|bool|\ArrayObject|null
64
    {
65
        $classes = [];
2✔
66
        $entrypointProperties = [];
2✔
67
        $hydraPrefix = $this->getHydraPrefix($context + $this->defaultContext);
2✔
68

69
        foreach ($object->getResourceNameCollection() as $resourceClass) {
2✔
70
            $resourceMetadataCollection = $this->resourceMetadataFactory->create($resourceClass);
2✔
71

72
            $resourceMetadata = $resourceMetadataCollection[0];
2✔
73
            if (true === $resourceMetadata->getHideHydraOperation()) {
2✔
74
                continue;
2✔
75
            }
76

77
            $shortName = $resourceMetadata->getShortName();
2✔
78
            $prefixedShortName = $resourceMetadata->getTypes()[0] ?? "#$shortName";
2✔
79

80
            $this->populateEntrypointProperties($resourceMetadata, $shortName, $prefixedShortName, $entrypointProperties, $hydraPrefix, $resourceMetadataCollection);
2✔
81
            $classes[] = $this->getClass($resourceClass, $resourceMetadata, $shortName, $prefixedShortName, $context, $hydraPrefix, $resourceMetadataCollection);
2✔
82
        }
83

84
        return $this->computeDoc($object, $this->getClasses($entrypointProperties, $classes, $hydraPrefix), $hydraPrefix);
2✔
85
    }
86

87
    /**
88
     * Populates entrypoint properties.
89
     */
90
    private function populateEntrypointProperties(ApiResource $resourceMetadata, string $shortName, string $prefixedShortName, array &$entrypointProperties, string $hydraPrefix, ?ResourceMetadataCollection $resourceMetadataCollection = null): void
91
    {
92
        $hydraCollectionOperations = $this->getHydraOperations(true, $resourceMetadataCollection, $hydraPrefix);
2✔
93
        if (empty($hydraCollectionOperations)) {
2✔
94
            return;
2✔
95
        }
96

UNCOV
97
        $entrypointProperty = [
×
UNCOV
98
            '@type' => $hydraPrefix.'SupportedProperty',
×
UNCOV
99
            $hydraPrefix.'property' => [
×
UNCOV
100
                '@id' => \sprintf('#Entrypoint/%s', lcfirst($shortName)),
×
UNCOV
101
                '@type' => $hydraPrefix.'Link',
×
UNCOV
102
                'domain' => '#Entrypoint',
×
UNCOV
103
                'owl:maxCardinality' => 1,
×
UNCOV
104
                'range' => [
×
UNCOV
105
                    ['@id' => $hydraPrefix.'Collection'],
×
UNCOV
106
                    [
×
UNCOV
107
                        'owl:equivalentClass' => [
×
UNCOV
108
                            'owl:onProperty' => ['@id' => $hydraPrefix.'member'],
×
UNCOV
109
                            'owl:allValuesFrom' => ['@id' => $prefixedShortName],
×
UNCOV
110
                        ],
×
UNCOV
111
                    ],
×
UNCOV
112
                ],
×
UNCOV
113
                $hydraPrefix.'supportedOperation' => $hydraCollectionOperations,
×
UNCOV
114
            ],
×
UNCOV
115
            $hydraPrefix.'title' => "get{$shortName}Collection",
×
UNCOV
116
            $hydraPrefix.'description' => "The collection of $shortName resources",
×
UNCOV
117
            $hydraPrefix.'readable' => true,
×
UNCOV
118
            $hydraPrefix.'writeable' => false,
×
UNCOV
119
        ];
×
120

UNCOV
121
        if ($resourceMetadata->getDeprecationReason()) {
×
UNCOV
122
            $entrypointProperty['owl:deprecated'] = true;
×
123
        }
124

UNCOV
125
        $entrypointProperties[] = $entrypointProperty;
×
126
    }
127

128
    /**
129
     * Gets a Hydra class.
130
     */
131
    private function getClass(string $resourceClass, ApiResource $resourceMetadata, string $shortName, string $prefixedShortName, array $context, string $hydraPrefix, ?ResourceMetadataCollection $resourceMetadataCollection = null): array
132
    {
133
        $description = $resourceMetadata->getDescription();
2✔
134
        $isDeprecated = $resourceMetadata->getDeprecationReason();
2✔
135

136
        $class = [
2✔
137
            '@id' => $prefixedShortName,
2✔
138
            '@type' => $hydraPrefix.'Class',
2✔
139
            $hydraPrefix.'title' => $shortName,
2✔
140
            $hydraPrefix.'supportedProperty' => $this->getHydraProperties($resourceClass, $resourceMetadata, $shortName, $prefixedShortName, $context, $hydraPrefix),
2✔
141
            $hydraPrefix.'supportedOperation' => $this->getHydraOperations(false, $resourceMetadataCollection, $hydraPrefix),
2✔
142
        ];
2✔
143

144
        if (null !== $description) {
2✔
145
            $class[$hydraPrefix.'description'] = $description;
2✔
146
        }
147

148
        if ($resourceMetadata instanceof ErrorResource) {
2✔
149
            $class['subClassOf'] = 'Error';
2✔
150
        }
151

152
        if ($isDeprecated) {
2✔
UNCOV
153
            $class['owl:deprecated'] = true;
×
154
        }
155

156
        return $class;
2✔
157
    }
158

159
    /**
160
     * Creates context for property metatata factories.
161
     */
162
    private function getPropertyMetadataFactoryContext(ApiResource $resourceMetadata): array
163
    {
164
        $normalizationGroups = $resourceMetadata->getNormalizationContext()[AbstractNormalizer::GROUPS] ?? null;
2✔
165
        $denormalizationGroups = $resourceMetadata->getDenormalizationContext()[AbstractNormalizer::GROUPS] ?? null;
2✔
166
        $propertyContext = [
2✔
167
            'normalization_groups' => $normalizationGroups,
2✔
168
            'denormalization_groups' => $denormalizationGroups,
2✔
169
        ];
2✔
170
        $propertyNameContext = [];
2✔
171

172
        if ($normalizationGroups) {
2✔
UNCOV
173
            $propertyNameContext['serializer_groups'] = $normalizationGroups;
×
174
        }
175

176
        if (!$denormalizationGroups) {
2✔
177
            return [$propertyNameContext, $propertyContext];
2✔
178
        }
179

UNCOV
180
        if (!isset($propertyNameContext['serializer_groups'])) {
×
181
            $propertyNameContext['serializer_groups'] = $denormalizationGroups;
×
182

183
            return [$propertyNameContext, $propertyContext];
×
184
        }
185

UNCOV
186
        foreach ($denormalizationGroups as $group) {
×
UNCOV
187
            $propertyNameContext['serializer_groups'][] = $group;
×
188
        }
189

UNCOV
190
        return [$propertyNameContext, $propertyContext];
×
191
    }
192

193
    /**
194
     * Gets Hydra properties.
195
     */
196
    private function getHydraProperties(string $resourceClass, ApiResource $resourceMetadata, string $shortName, string $prefixedShortName, array $context, string $hydraPrefix = ContextBuilder::HYDRA_PREFIX): array
197
    {
198
        $classes = [];
2✔
199

200
        $classes[$resourceClass] = true;
2✔
201
        foreach ($resourceMetadata->getOperations() as $operation) {
2✔
202
            /** @var Operation $operation */
203
            if (!$operation instanceof CollectionOperationInterface) {
2✔
204
                continue;
2✔
205
            }
206

207
            $inputMetadata = $operation->getInput();
2✔
208
            if (null !== $inputClass = $inputMetadata['class'] ?? null) {
2✔
UNCOV
209
                $classes[$inputClass] = true;
×
210
            }
211

212
            $outputMetadata = $operation->getOutput();
2✔
213
            if (null !== $outputClass = $outputMetadata['class'] ?? null) {
2✔
UNCOV
214
                $classes[$outputClass] = true;
×
215
            }
216
        }
217

218
        /** @var string[] $classes */
219
        $classes = array_keys($classes);
2✔
220
        $properties = [];
2✔
221
        [$propertyNameContext, $propertyContext] = $this->getPropertyMetadataFactoryContext($resourceMetadata);
2✔
222
        foreach ($classes as $class) {
2✔
223
            foreach ($this->propertyNameCollectionFactory->create($class, $propertyNameContext) as $propertyName) {
2✔
224
                $propertyMetadata = $this->propertyMetadataFactory->create($class, $propertyName, $propertyContext);
2✔
225

226
                if (true === $propertyMetadata->isIdentifier() && false === $propertyMetadata->isWritable()) {
2✔
227
                    continue;
2✔
228
                }
229

230
                if ($this->nameConverter) {
2✔
231
                    $propertyName = $this->nameConverter->normalize($propertyName, $class, self::FORMAT, $context);
2✔
232
                }
233

234
                if (false === $propertyMetadata->getHydra()) {
2✔
235
                    continue;
2✔
236
                }
237

238
                $properties[] = $this->getProperty($propertyMetadata, $propertyName, $prefixedShortName, $shortName, $hydraPrefix);
2✔
239
            }
240
        }
241

242
        return $properties;
2✔
243
    }
244

245
    /**
246
     * Gets Hydra operations.
247
     */
248
    private function getHydraOperations(bool $collection, ?ResourceMetadataCollection $resourceMetadataCollection = null, string $hydraPrefix = ContextBuilder::HYDRA_PREFIX): array
249
    {
250
        $hydraOperations = [];
2✔
251
        foreach ($resourceMetadataCollection as $resourceMetadata) {
2✔
252
            foreach ($resourceMetadata->getOperations() as $operation) {
2✔
253
                if (true === $operation->getHideHydraOperation()) {
2✔
254
                    continue;
2✔
255
                }
256

257
                if (('POST' === $operation->getMethod() || $operation instanceof CollectionOperationInterface) !== $collection) {
2✔
258
                    continue;
2✔
259
                }
260

261
                $hydraOperations[] = $this->getHydraOperation($operation, $operation->getShortName(), $hydraPrefix);
2✔
262
            }
263
        }
264

265
        return $hydraOperations;
2✔
266
    }
267

268
    /**
269
     * Gets and populates if applicable a Hydra operation.
270
     */
271
    private function getHydraOperation(HttpOperation $operation, string $prefixedShortName, string $hydraPrefix): array
272
    {
273
        $method = $operation->getMethod() ?: 'GET';
2✔
274

275
        $hydraOperation = $operation->getHydraContext() ?? [];
2✔
276
        if ($operation->getDeprecationReason()) {
2✔
UNCOV
277
            $hydraOperation['owl:deprecated'] = true;
×
278
        }
279

280
        $shortName = $operation->getShortName();
2✔
281
        $inputMetadata = $operation->getInput() ?? [];
2✔
282
        $outputMetadata = $operation->getOutput() ?? [];
2✔
283

284
        $inputClass = \array_key_exists('class', $inputMetadata) ? $inputMetadata['class'] : false;
2✔
285
        $outputClass = \array_key_exists('class', $outputMetadata) ? $outputMetadata['class'] : false;
2✔
286

287
        if ('GET' === $method && $operation instanceof CollectionOperationInterface) {
2✔
UNCOV
288
            $hydraOperation += [
×
UNCOV
289
                '@type' => [$hydraPrefix.'Operation', 'schema:FindAction'],
×
UNCOV
290
                $hydraPrefix.'description' => "Retrieves the collection of $shortName resources.",
×
UNCOV
291
                'returns' => null === $outputClass ? 'owl:Nothing' : $hydraPrefix.'Collection',
×
UNCOV
292
            ];
×
293
        } elseif ('GET' === $method) {
2✔
294
            $hydraOperation += [
2✔
295
                '@type' => [$hydraPrefix.'Operation', 'schema:FindAction'],
2✔
296
                $hydraPrefix.'description' => "Retrieves a $shortName resource.",
2✔
297
                'returns' => null === $outputClass ? 'owl:Nothing' : $prefixedShortName,
2✔
298
            ];
2✔
UNCOV
299
        } elseif ('PATCH' === $method) {
×
UNCOV
300
            $hydraOperation += [
×
UNCOV
301
                '@type' => $hydraPrefix.'Operation',
×
UNCOV
302
                $hydraPrefix.'description' => "Updates the $shortName resource.",
×
UNCOV
303
                'returns' => null === $outputClass ? 'owl:Nothing' : $prefixedShortName,
×
UNCOV
304
                'expects' => null === $inputClass ? 'owl:Nothing' : $prefixedShortName,
×
UNCOV
305
            ];
×
306

UNCOV
307
            if (null !== $inputClass) {
×
UNCOV
308
                $possibleValue = [];
×
UNCOV
309
                foreach ($operation->getInputFormats() as $mimeTypes) {
×
UNCOV
310
                    foreach ($mimeTypes as $mimeType) {
×
UNCOV
311
                        $possibleValue[] = $mimeType;
×
312
                    }
313
                }
314

UNCOV
315
                $hydraOperation['expectsHeader'] = [['headerName' => 'Content-Type', 'possibleValue' => $possibleValue]];
×
316
            }
UNCOV
317
        } elseif ('POST' === $method) {
×
UNCOV
318
            $hydraOperation += [
×
UNCOV
319
                '@type' => [$hydraPrefix.'Operation', 'schema:CreateAction'],
×
UNCOV
320
                $hydraPrefix.'description' => "Creates a $shortName resource.",
×
UNCOV
321
                'returns' => null === $outputClass ? 'owl:Nothing' : $prefixedShortName,
×
UNCOV
322
                'expects' => null === $inputClass ? 'owl:Nothing' : $prefixedShortName,
×
UNCOV
323
            ];
×
UNCOV
324
        } elseif ('PUT' === $method) {
×
UNCOV
325
            $hydraOperation += [
×
UNCOV
326
                '@type' => [$hydraPrefix.'Operation', 'schema:ReplaceAction'],
×
UNCOV
327
                $hydraPrefix.'description' => "Replaces the $shortName resource.",
×
UNCOV
328
                'returns' => null === $outputClass ? 'owl:Nothing' : $prefixedShortName,
×
UNCOV
329
                'expects' => null === $inputClass ? 'owl:Nothing' : $prefixedShortName,
×
UNCOV
330
            ];
×
UNCOV
331
        } elseif ('DELETE' === $method) {
×
UNCOV
332
            $hydraOperation += [
×
UNCOV
333
                '@type' => [$hydraPrefix.'Operation', 'schema:DeleteAction'],
×
UNCOV
334
                $hydraPrefix.'description' => "Deletes the $shortName resource.",
×
UNCOV
335
                'returns' => 'owl:Nothing',
×
UNCOV
336
            ];
×
337
        }
338

339
        $hydraOperation[$hydraPrefix.'method'] ??= $method;
2✔
340
        $hydraOperation[$hydraPrefix.'title'] ??= strtolower($method).$shortName.($operation instanceof CollectionOperationInterface ? 'Collection' : '');
2✔
341

342
        ksort($hydraOperation);
2✔
343

344
        return $hydraOperation;
2✔
345
    }
346

347
    /**
348
     * Gets the range of the property.
349
     */
350
    private function getRange(ApiProperty $propertyMetadata): array|string|null
351
    {
352
        $jsonldContext = $propertyMetadata->getJsonldContext();
2✔
353

354
        if (isset($jsonldContext['@type'])) {
2✔
355
            return $jsonldContext['@type'];
2✔
356
        }
357

358
        $builtInTypes = $propertyMetadata->getBuiltinTypes() ?? [];
2✔
359
        $types = [];
2✔
360

361
        foreach ($builtInTypes as $type) {
2✔
362
            if ($type->isCollection() && null !== $collectionType = $type->getCollectionValueTypes()[0] ?? null) {
2✔
UNCOV
363
                $type = $collectionType;
×
364
            }
365

366
            switch ($type->getBuiltinType()) {
2✔
367
                case Type::BUILTIN_TYPE_STRING:
368
                    if (!\in_array('xmls:string', $types, true)) {
2✔
369
                        $types[] = 'xmls:string';
2✔
370
                    }
371
                    break;
2✔
372
                case Type::BUILTIN_TYPE_INT:
373
                    if (!\in_array('xmls:integer', $types, true)) {
2✔
374
                        $types[] = 'xmls:integer';
2✔
375
                    }
376
                    break;
2✔
377
                case Type::BUILTIN_TYPE_FLOAT:
UNCOV
378
                    if (!\in_array('xmls:decimal', $types, true)) {
×
UNCOV
379
                        $types[] = 'xmls:decimal';
×
380
                    }
UNCOV
381
                    break;
×
382
                case Type::BUILTIN_TYPE_BOOL:
UNCOV
383
                    if (!\in_array('xmls:boolean', $types, true)) {
×
UNCOV
384
                        $types[] = 'xmls:boolean';
×
385
                    }
UNCOV
386
                    break;
×
387
                case Type::BUILTIN_TYPE_OBJECT:
388
                    if (null === $className = $type->getClassName()) {
2✔
389
                        continue 2;
×
390
                    }
391

392
                    if (is_a($className, \DateTimeInterface::class, true)) {
2✔
UNCOV
393
                        if (!\in_array('xmls:dateTime', $types, true)) {
×
UNCOV
394
                            $types[] = 'xmls:dateTime';
×
395
                        }
UNCOV
396
                        break;
×
397
                    }
398

399
                    if ($this->resourceClassResolver->isResourceClass($className)) {
2✔
UNCOV
400
                        $resourceMetadata = $this->resourceMetadataFactory->create($className);
×
UNCOV
401
                        $operation = $resourceMetadata->getOperation();
×
402

UNCOV
403
                        if (!$operation instanceof HttpOperation || !$operation->getTypes()) {
×
UNCOV
404
                            if (!\in_array("#{$operation->getShortName()}", $types, true)) {
×
UNCOV
405
                                $types[] = "#{$operation->getShortName()}";
×
406
                            }
UNCOV
407
                            break;
×
408
                        }
409

UNCOV
410
                        $types = array_unique(array_merge($types, $operation->getTypes()));
×
UNCOV
411
                        break;
×
412
                    }
413
            }
414
        }
415

416
        if ([] === $types) {
2✔
417
            return null;
2✔
418
        }
419

420
        return 1 === \count($types) ? $types[0] : $types;
2✔
421
    }
422

423
    private function isSingleRelation(ApiProperty $propertyMetadata): bool
424
    {
425
        $builtInTypes = $propertyMetadata->getBuiltinTypes() ?? [];
2✔
426

427
        foreach ($builtInTypes as $type) {
2✔
428
            $className = $type->getClassName();
2✔
429
            if (
430
                !$type->isCollection()
2✔
431
                && null !== $className
2✔
432
                && $this->resourceClassResolver->isResourceClass($className)
2✔
433
            ) {
UNCOV
434
                return true;
×
435
            }
436
        }
437

438
        return false;
2✔
439
    }
440

441
    /**
442
     * Builds the classes array.
443
     */
444
    private function getClasses(array $entrypointProperties, array $classes, string $hydraPrefix = ContextBuilder::HYDRA_PREFIX): array
445
    {
446
        $classes[] = [
2✔
447
            '@id' => '#Entrypoint',
2✔
448
            '@type' => $hydraPrefix.'Class',
2✔
449
            $hydraPrefix.'title' => 'Entrypoint',
2✔
450
            $hydraPrefix.'supportedProperty' => $entrypointProperties,
2✔
451
            $hydraPrefix.'supportedOperation' => [
2✔
452
                '@type' => $hydraPrefix.'Operation',
2✔
453
                $hydraPrefix.'method' => 'GET',
2✔
454
                $hydraPrefix.'title' => 'index',
2✔
455
                $hydraPrefix.'description' => 'The API Entrypoint.',
2✔
456
                $hydraPrefix.'returns' => 'Entrypoint',
2✔
457
            ],
2✔
458
        ];
2✔
459

460
        $classes[] = [
2✔
461
            '@id' => '#ConstraintViolationList',
2✔
462
            '@type' => $hydraPrefix.'Class',
2✔
463
            $hydraPrefix.'title' => 'ConstraintViolationList',
2✔
464
            $hydraPrefix.'description' => 'A constraint violation List.',
2✔
465
            $hydraPrefix.'supportedProperty' => [
2✔
466
                [
2✔
467
                    '@type' => $hydraPrefix.'SupportedProperty',
2✔
468
                    $hydraPrefix.'property' => [
2✔
469
                        '@id' => '#ConstraintViolationList/propertyPath',
2✔
470
                        '@type' => 'rdf:Property',
2✔
471
                        'rdfs:label' => 'propertyPath',
2✔
472
                        'domain' => '#ConstraintViolationList',
2✔
473
                        'range' => 'xmls:string',
2✔
474
                    ],
2✔
475
                    $hydraPrefix.'title' => 'propertyPath',
2✔
476
                    $hydraPrefix.'description' => 'The property path of the violation',
2✔
477
                    $hydraPrefix.'readable' => true,
2✔
478
                    $hydraPrefix.'writeable' => false,
2✔
479
                ],
2✔
480
                [
2✔
481
                    '@type' => $hydraPrefix.'SupportedProperty',
2✔
482
                    $hydraPrefix.'property' => [
2✔
483
                        '@id' => '#ConstraintViolationList/message',
2✔
484
                        '@type' => 'rdf:Property',
2✔
485
                        'rdfs:label' => 'message',
2✔
486
                        'domain' => '#ConstraintViolationList',
2✔
487
                        'range' => 'xmls:string',
2✔
488
                    ],
2✔
489
                    $hydraPrefix.'title' => 'message',
2✔
490
                    $hydraPrefix.'description' => 'The message associated with the violation',
2✔
491
                    $hydraPrefix.'readable' => true,
2✔
492
                    $hydraPrefix.'writeable' => false,
2✔
493
                ],
2✔
494
            ],
2✔
495
        ];
2✔
496

497
        return $classes;
2✔
498
    }
499

500
    /**
501
     * Gets a property definition.
502
     */
503
    private function getProperty(ApiProperty $propertyMetadata, string $propertyName, string $prefixedShortName, string $shortName, string $hydraPrefix): array
504
    {
505
        if ($iri = $propertyMetadata->getIris()) {
2✔
UNCOV
506
            $iri = 1 === (is_countable($iri) ? \count($iri) : 0) ? $iri[0] : $iri;
×
507
        }
508

509
        if (!isset($iri)) {
2✔
510
            $iri = "#$shortName/$propertyName";
2✔
511
        }
512

513
        $propertyData = ($propertyMetadata->getJsonldContext()[$hydraPrefix.'property'] ?? []) + [
2✔
514
            '@id' => $iri,
2✔
515
            '@type' => false === $propertyMetadata->isReadableLink() ? $hydraPrefix.'Link' : 'rdf:Property',
2✔
516
            'domain' => $prefixedShortName,
2✔
517
            'label' => $propertyName,
2✔
518
        ];
2✔
519

520
        if (!isset($propertyData['owl:deprecated']) && $propertyMetadata->getDeprecationReason()) {
2✔
UNCOV
521
            $propertyData['owl:deprecated'] = true;
×
522
        }
523

524
        if (!isset($propertyData['owl:maxCardinality']) && $this->isSingleRelation($propertyMetadata)) {
2✔
UNCOV
525
            $propertyData['owl:maxCardinality'] = 1;
×
526
        }
527

528
        if (!isset($propertyData['range']) && null !== $range = $this->getRange($propertyMetadata)) {
2✔
529
            $propertyData['range'] = $range;
2✔
530
        }
531

532
        $property = [
2✔
533
            '@type' => $hydraPrefix.'SupportedProperty',
2✔
534
            $hydraPrefix.'property' => $propertyData,
2✔
535
            $hydraPrefix.'title' => $propertyName,
2✔
536
            $hydraPrefix.'required' => $propertyMetadata->isRequired() ?? false,
2✔
537
            $hydraPrefix.'readable' => $propertyMetadata->isReadable(),
2✔
538
            $hydraPrefix.'writeable' => $propertyMetadata->isWritable() || $propertyMetadata->isInitializable(),
2✔
539
        ];
2✔
540

541
        if (null !== $description = $propertyMetadata->getDescription()) {
2✔
542
            $property[$hydraPrefix.'description'] = $description;
2✔
543
        }
544

545
        return $property;
2✔
546
    }
547

548
    /**
549
     * Computes the documentation.
550
     */
551
    private function computeDoc(Documentation $object, array $classes, string $hydraPrefix = ContextBuilder::HYDRA_PREFIX): array
552
    {
553
        $doc = ['@context' => $this->getContext($hydraPrefix), '@id' => $this->urlGenerator->generate('api_doc', ['_format' => self::FORMAT]), '@type' => $hydraPrefix.'ApiDocumentation'];
2✔
554

555
        if ('' !== $object->getTitle()) {
2✔
556
            $doc[$hydraPrefix.'title'] = $object->getTitle();
2✔
557
        }
558

559
        if ('' !== $object->getDescription()) {
2✔
560
            $doc[$hydraPrefix.'description'] = $object->getDescription();
2✔
561
        }
562

563
        $doc[$hydraPrefix.'entrypoint'] = $this->urlGenerator->generate('api_entrypoint');
2✔
564
        $doc[$hydraPrefix.'supportedClass'] = $classes;
2✔
565

566
        return $doc;
2✔
567
    }
568

569
    /**
570
     * Builds the JSON-LD context for the API documentation.
571
     */
572
    private function getContext(string $hydraPrefix = ContextBuilder::HYDRA_PREFIX): array
573
    {
574
        return [
2✔
575
            HYDRA_CONTEXT,
2✔
576
            [
2✔
577
                '@vocab' => $this->urlGenerator->generate('api_doc', ['_format' => self::FORMAT], UrlGeneratorInterface::ABS_URL).'#',
2✔
578
                'hydra' => ContextBuilderInterface::HYDRA_NS,
2✔
579
                'rdf' => ContextBuilderInterface::RDF_NS,
2✔
580
                'rdfs' => ContextBuilderInterface::RDFS_NS,
2✔
581
                'xmls' => ContextBuilderInterface::XML_NS,
2✔
582
                'owl' => ContextBuilderInterface::OWL_NS,
2✔
583
                'schema' => ContextBuilderInterface::SCHEMA_ORG_NS,
2✔
584
                'domain' => ['@id' => 'rdfs:domain', '@type' => '@id'],
2✔
585
                'range' => ['@id' => 'rdfs:range', '@type' => '@id'],
2✔
586
                'subClassOf' => ['@id' => 'rdfs:subClassOf', '@type' => '@id'],
2✔
587
            ],
2✔
588
        ];
2✔
589
    }
590

591
    /**
592
     * {@inheritdoc}
593
     */
594
    public function supportsNormalization(mixed $data, ?string $format = null, array $context = []): bool
595
    {
596
        return self::FORMAT === $format && $data instanceof Documentation;
2✔
597
    }
598

599
    public function getSupportedTypes($format): array
600
    {
601
        return self::FORMAT === $format ? [Documentation::class => true] : [];
410✔
602
    }
603
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc