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

api-platform / core / 17487610263

05 Sep 2025 08:12AM UTC coverage: 22.608% (+0.3%) from 22.319%
17487610263

push

github

web-flow
chore: remove @experimental flag from parameters (#7357)

12049 of 53296 relevant lines covered (22.61%)

26.21 hits per line

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

62.91
/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 ApiPlatform\Metadata\Util\TypeHelper;
33
use Symfony\Component\PropertyInfo\PropertyInfoExtractor;
34
use Symfony\Component\PropertyInfo\Type as LegacyType;
35
use Symfony\Component\Serializer\NameConverter\NameConverterInterface;
36
use Symfony\Component\Serializer\Normalizer\AbstractNormalizer;
37
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
38
use Symfony\Component\TypeInfo\Type;
39
use Symfony\Component\TypeInfo\Type\CollectionType;
40
use Symfony\Component\TypeInfo\Type\ObjectType;
41
use Symfony\Component\TypeInfo\TypeIdentifier;
42

43
use const ApiPlatform\JsonLd\HYDRA_CONTEXT;
44

45
/**
46
 * Creates a machine readable Hydra API documentation.
47
 *
48
 * @author Kévin Dunglas <dunglas@gmail.com>
49
 */
50
final class DocumentationNormalizer implements NormalizerInterface
51
{
52
    use HydraPrefixTrait;
53
    public const FORMAT = 'jsonld';
54

55
    public function __construct(
56
        private readonly ResourceMetadataCollectionFactoryInterface $resourceMetadataFactory,
57
        private readonly PropertyNameCollectionFactoryInterface $propertyNameCollectionFactory,
58
        private readonly PropertyMetadataFactoryInterface $propertyMetadataFactory,
59
        private readonly ResourceClassResolverInterface $resourceClassResolver,
60
        private readonly UrlGeneratorInterface $urlGenerator,
61
        private readonly ?NameConverterInterface $nameConverter = null,
62
        private readonly ?array $defaultContext = [],
63
        private readonly ?bool $entrypointEnabled = true,
64
    ) {
65
    }
654✔
66

67
    /**
68
     * {@inheritdoc}
69
     */
70
    public function normalize(mixed $object, ?string $format = null, array $context = []): array
71
    {
72
        $classes = [];
2✔
73
        $entrypointProperties = [];
2✔
74
        $hydraPrefix = $this->getHydraPrefix($context + $this->defaultContext);
2✔
75

76
        foreach ($object->getResourceNameCollection() as $resourceClass) {
2✔
77
            $resourceMetadataCollection = $this->resourceMetadataFactory->create($resourceClass);
2✔
78

79
            $resourceMetadata = $resourceMetadataCollection[0];
2✔
80
            if (true === $resourceMetadata->getHideHydraOperation()) {
2✔
81
                continue;
2✔
82
            }
83

84
            $shortName = $resourceMetadata->getShortName();
2✔
85
            $prefixedShortName = $resourceMetadata->getTypes()[0] ?? "#$shortName";
2✔
86

87
            $this->populateEntrypointProperties($resourceMetadata, $shortName, $prefixedShortName, $entrypointProperties, $hydraPrefix, $resourceMetadataCollection);
2✔
88
            $classes[] = $this->getClass($resourceClass, $resourceMetadata, $shortName, $prefixedShortName, $context, $hydraPrefix, $resourceMetadataCollection);
2✔
89
        }
90

91
        return $this->computeDoc($object, $this->getClasses($entrypointProperties, $classes, $hydraPrefix), $hydraPrefix);
2✔
92
    }
93

94
    /**
95
     * Populates entrypoint properties.
96
     */
97
    private function populateEntrypointProperties(ApiResource $resourceMetadata, string $shortName, string $prefixedShortName, array &$entrypointProperties, string $hydraPrefix, ?ResourceMetadataCollection $resourceMetadataCollection = null): void
98
    {
99
        $hydraCollectionOperations = $this->getHydraOperations(true, $resourceMetadataCollection, $hydraPrefix);
2✔
100
        if (empty($hydraCollectionOperations)) {
2✔
101
            return;
2✔
102
        }
103

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

128
        if ($resourceMetadata->getDeprecationReason()) {
×
129
            $entrypointProperty['owl:deprecated'] = true;
×
130
        }
131

132
        $entrypointProperties[] = $entrypointProperty;
×
133
    }
134

135
    /**
136
     * Gets a Hydra class.
137
     */
138
    private function getClass(string $resourceClass, ApiResource $resourceMetadata, string $shortName, string $prefixedShortName, array $context, string $hydraPrefix, ?ResourceMetadataCollection $resourceMetadataCollection = null): array
139
    {
140
        $description = $resourceMetadata->getDescription();
2✔
141
        $isDeprecated = $resourceMetadata->getDeprecationReason();
2✔
142

143
        $class = [
2✔
144
            '@id' => $prefixedShortName,
2✔
145
            '@type' => $hydraPrefix.'Class',
2✔
146
            $hydraPrefix.'title' => $shortName,
2✔
147
            $hydraPrefix.'supportedProperty' => $this->getHydraProperties($resourceClass, $resourceMetadata, $shortName, $prefixedShortName, $context, $hydraPrefix),
2✔
148
            $hydraPrefix.'supportedOperation' => $this->getHydraOperations(false, $resourceMetadataCollection, $hydraPrefix),
2✔
149
        ];
2✔
150

151
        if (null !== $description) {
2✔
152
            $class[$hydraPrefix.'description'] = $description;
2✔
153
        }
154

155
        if ($resourceMetadata instanceof ErrorResource) {
2✔
156
            $class['subClassOf'] = 'Error';
2✔
157
        }
158

159
        if ($isDeprecated) {
2✔
160
            $class['owl:deprecated'] = true;
×
161
        }
162

163
        return $class;
2✔
164
    }
165

166
    /**
167
     * Creates context for property metatata factories.
168
     */
169
    private function getPropertyMetadataFactoryContext(ApiResource $resourceMetadata): array
170
    {
171
        $normalizationGroups = $resourceMetadata->getNormalizationContext()[AbstractNormalizer::GROUPS] ?? null;
2✔
172
        $denormalizationGroups = $resourceMetadata->getDenormalizationContext()[AbstractNormalizer::GROUPS] ?? null;
2✔
173
        $propertyContext = [
2✔
174
            'normalization_groups' => $normalizationGroups,
2✔
175
            'denormalization_groups' => $denormalizationGroups,
2✔
176
        ];
2✔
177
        $propertyNameContext = [];
2✔
178

179
        if ($normalizationGroups) {
2✔
180
            $propertyNameContext['serializer_groups'] = $normalizationGroups;
×
181
        }
182

183
        if (!$denormalizationGroups) {
2✔
184
            return [$propertyNameContext, $propertyContext];
2✔
185
        }
186

187
        if (!isset($propertyNameContext['serializer_groups'])) {
×
188
            $propertyNameContext['serializer_groups'] = $denormalizationGroups;
×
189

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

193
        foreach ($denormalizationGroups as $group) {
×
194
            $propertyNameContext['serializer_groups'][] = $group;
×
195
        }
196

197
        return [$propertyNameContext, $propertyContext];
×
198
    }
199

200
    /**
201
     * Gets Hydra properties.
202
     */
203
    private function getHydraProperties(string $resourceClass, ApiResource $resourceMetadata, string $shortName, string $prefixedShortName, array $context, string $hydraPrefix = ContextBuilder::HYDRA_PREFIX): array
204
    {
205
        $classes = [];
2✔
206

207
        $classes[$resourceClass] = true;
2✔
208
        foreach ($resourceMetadata->getOperations() as $operation) {
2✔
209
            /** @var Operation $operation */
210
            if (!$operation instanceof CollectionOperationInterface) {
2✔
211
                continue;
2✔
212
            }
213

214
            $inputMetadata = $operation->getInput();
2✔
215
            if (null !== $inputClass = $inputMetadata['class'] ?? null) {
2✔
216
                $classes[$inputClass] = true;
×
217
            }
218

219
            $outputMetadata = $operation->getOutput();
2✔
220
            if (null !== $outputClass = $outputMetadata['class'] ?? null) {
2✔
221
                $classes[$outputClass] = true;
×
222
            }
223
        }
224

225
        /** @var string[] $classes */
226
        $classes = array_keys($classes);
2✔
227
        $properties = [];
2✔
228
        [$propertyNameContext, $propertyContext] = $this->getPropertyMetadataFactoryContext($resourceMetadata);
2✔
229
        foreach ($classes as $class) {
2✔
230
            foreach ($this->propertyNameCollectionFactory->create($class, $propertyNameContext) as $propertyName) {
2✔
231
                $propertyMetadata = $this->propertyMetadataFactory->create($class, $propertyName, $propertyContext);
2✔
232

233
                if (true === $propertyMetadata->isIdentifier() && false === $propertyMetadata->isWritable()) {
2✔
234
                    continue;
2✔
235
                }
236

237
                if ($this->nameConverter) {
2✔
238
                    $propertyName = $this->nameConverter->normalize($propertyName, $class, self::FORMAT, $context);
2✔
239
                }
240

241
                if (false === $propertyMetadata->getHydra()) {
2✔
242
                    continue;
2✔
243
                }
244

245
                $properties[] = $this->getProperty($propertyMetadata, $propertyName, $prefixedShortName, $shortName, $hydraPrefix);
2✔
246
            }
247
        }
248

249
        return $properties;
2✔
250
    }
251

252
    /**
253
     * Gets Hydra operations.
254
     */
255
    private function getHydraOperations(bool $collection, ?ResourceMetadataCollection $resourceMetadataCollection = null, string $hydraPrefix = ContextBuilder::HYDRA_PREFIX): array
256
    {
257
        $hydraOperations = [];
2✔
258
        foreach ($resourceMetadataCollection as $resourceMetadata) {
2✔
259
            foreach ($resourceMetadata->getOperations() as $operation) {
2✔
260
                if (true === $operation->getHideHydraOperation()) {
2✔
261
                    continue;
2✔
262
                }
263

264
                if (('POST' === $operation->getMethod() || $operation instanceof CollectionOperationInterface) !== $collection) {
2✔
265
                    continue;
2✔
266
                }
267

268
                $hydraOperations[] = $this->getHydraOperation($operation, $operation->getShortName(), $hydraPrefix);
2✔
269
            }
270
        }
271

272
        return $hydraOperations;
2✔
273
    }
274

275
    /**
276
     * Gets and populates if applicable a Hydra operation.
277
     */
278
    private function getHydraOperation(HttpOperation $operation, string $prefixedShortName, string $hydraPrefix): array
279
    {
280
        $method = $operation->getMethod() ?: 'GET';
2✔
281

282
        $hydraOperation = $operation->getHydraContext() ?? [];
2✔
283
        if ($operation->getDeprecationReason()) {
2✔
284
            $hydraOperation['owl:deprecated'] = true;
×
285
        }
286

287
        $shortName = $operation->getShortName();
2✔
288
        $inputMetadata = $operation->getInput() ?? [];
2✔
289
        $outputMetadata = $operation->getOutput() ?? [];
2✔
290

291
        $inputClass = \array_key_exists('class', $inputMetadata) ? $inputMetadata['class'] : false;
2✔
292
        $outputClass = \array_key_exists('class', $outputMetadata) ? $outputMetadata['class'] : false;
2✔
293

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

314
            if (null !== $inputClass) {
×
315
                $possibleValue = [];
×
316
                foreach ($operation->getInputFormats() ?? [] as $mimeTypes) {
×
317
                    foreach ($mimeTypes as $mimeType) {
×
318
                        $possibleValue[] = $mimeType;
×
319
                    }
320
                }
321

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

346
        $hydraOperation[$hydraPrefix.'method'] ??= $method;
2✔
347
        $hydraOperation[$hydraPrefix.'title'] ??= strtolower($method).$shortName.($operation instanceof CollectionOperationInterface ? 'Collection' : '');
2✔
348

349
        ksort($hydraOperation);
2✔
350

351
        return $hydraOperation;
2✔
352
    }
353

354
    /**
355
     * Gets the range of the property.
356
     */
357
    private function getRange(ApiProperty $propertyMetadata): array|string|null
358
    {
359
        $jsonldContext = $propertyMetadata->getJsonldContext();
2✔
360

361
        if (isset($jsonldContext['@type'])) {
2✔
362
            return $jsonldContext['@type'];
2✔
363
        }
364

365
        $types = [];
2✔
366

367
        if (method_exists(PropertyInfoExtractor::class, 'getType')) {
2✔
368
            $nativeType = $propertyMetadata->getNativeType();
2✔
369
            if (null === $nativeType) {
2✔
370
                return null;
×
371
            }
372

373
            if ($nativeType->isSatisfiedBy(fn ($t) => $t instanceof CollectionType)) {
2✔
374
                $nativeType = TypeHelper::getCollectionValueType($nativeType);
2✔
375
            }
376

377
            // Check for specific types after potentially unwrapping the collection
378
            if (null === $nativeType) {
2✔
379
                return null; // Should not happen if collection had a value type, but safety check
×
380
            }
381

382
            if ($nativeType->isIdentifiedBy(TypeIdentifier::STRING)) {
2✔
383
                $types[] = 'xmls:string';
2✔
384
            }
385

386
            if ($nativeType->isIdentifiedBy(TypeIdentifier::INT)) {
2✔
387
                $types[] = 'xmls:integer';
2✔
388
            }
389

390
            if ($nativeType->isIdentifiedBy(TypeIdentifier::FLOAT)) {
2✔
391
                $types[] = 'xmls:decimal';
×
392
            }
393

394
            if ($nativeType->isIdentifiedBy(TypeIdentifier::BOOL)) {
2✔
395
                $types[] = 'xmls:boolean';
×
396
            }
397

398
            if ($nativeType->isIdentifiedBy(\DateTimeInterface::class)) {
2✔
399
                $types[] = 'xmls:dateTime';
×
400
            }
401

402
            /** @var class-string|null $className */
403
            $className = null;
2✔
404

405
            $typeIsResourceClass = function (Type $type) use (&$className): bool {
2✔
406
                return $type instanceof ObjectType && $this->resourceClassResolver->isResourceClass($className = $type->getClassName());
2✔
407
            };
2✔
408

409
            if ($nativeType->isSatisfiedBy($typeIsResourceClass) && $className) {
2✔
410
                $resourceMetadata = $this->resourceMetadataFactory->create($className);
×
411
                $operation = $resourceMetadata->getOperation();
×
412

413
                if (!$operation instanceof HttpOperation || !$operation->getTypes()) {
×
414
                    if (!\in_array("#{$operation->getShortName()}", $types, true)) {
×
415
                        $types[] = "#{$operation->getShortName()}";
×
416
                    }
417
                } else {
418
                    $types = array_unique(array_merge($types, $operation->getTypes()));
×
419
                }
420
            }
421
        // TODO: remove in 5.x
422
        } else {
423
            $builtInTypes = $propertyMetadata->getBuiltinTypes() ?? [];
×
424

425
            foreach ($builtInTypes as $type) {
×
426
                if ($type->isCollection() && null !== $collectionType = $type->getCollectionValueTypes()[0] ?? null) {
×
427
                    $type = $collectionType;
×
428
                }
429

430
                switch ($type->getBuiltinType()) {
×
431
                    case LegacyType::BUILTIN_TYPE_STRING:
×
432
                        if (!\in_array('xmls:string', $types, true)) {
×
433
                            $types[] = 'xmls:string';
×
434
                        }
435
                        break;
×
436
                    case LegacyType::BUILTIN_TYPE_INT:
×
437
                        if (!\in_array('xmls:integer', $types, true)) {
×
438
                            $types[] = 'xmls:integer';
×
439
                        }
440
                        break;
×
441
                    case LegacyType::BUILTIN_TYPE_FLOAT:
×
442
                        if (!\in_array('xmls:decimal', $types, true)) {
×
443
                            $types[] = 'xmls:decimal';
×
444
                        }
445
                        break;
×
446
                    case LegacyType::BUILTIN_TYPE_BOOL:
×
447
                        if (!\in_array('xmls:boolean', $types, true)) {
×
448
                            $types[] = 'xmls:boolean';
×
449
                        }
450
                        break;
×
451
                    case LegacyType::BUILTIN_TYPE_OBJECT:
×
452
                        if (null === $className = $type->getClassName()) {
×
453
                            continue 2;
×
454
                        }
455

456
                        if (is_a($className, \DateTimeInterface::class, true)) {
×
457
                            if (!\in_array('xmls:dateTime', $types, true)) {
×
458
                                $types[] = 'xmls:dateTime';
×
459
                            }
460
                            break;
×
461
                        }
462

463
                        if ($this->resourceClassResolver->isResourceClass($className)) {
×
464
                            $resourceMetadata = $this->resourceMetadataFactory->create($className);
×
465
                            $operation = $resourceMetadata->getOperation();
×
466

467
                            if (!$operation instanceof HttpOperation || !$operation->getTypes()) {
×
468
                                if (!\in_array("#{$operation->getShortName()}", $types, true)) {
×
469
                                    $types[] = "#{$operation->getShortName()}";
×
470
                                }
471
                                break;
×
472
                            }
473

474
                            $types = array_unique(array_merge($types, $operation->getTypes()));
×
475
                            break;
×
476
                        }
477
                }
478
            }
479
        }
480

481
        if ([] === $types) {
2✔
482
            return null;
2✔
483
        }
484

485
        $types = array_unique($types);
2✔
486

487
        return 1 === \count($types) ? $types[0] : $types;
2✔
488
    }
489

490
    private function isSingleRelation(ApiProperty $propertyMetadata): bool
491
    {
492
        if (method_exists(PropertyInfoExtractor::class, 'getType')) {
2✔
493
            $nativeType = $propertyMetadata->getNativeType();
2✔
494
            if (null === $nativeType) {
2✔
495
                return false;
×
496
            }
497

498
            if ($nativeType instanceof CollectionType) {
2✔
499
                return false;
2✔
500
            }
501

502
            $typeIsResourceClass = function (Type $type) use (&$className): bool {
2✔
503
                return $type instanceof ObjectType && $this->resourceClassResolver->isResourceClass($className = $type->getClassName());
2✔
504
            };
2✔
505

506
            return $nativeType->isSatisfiedBy($typeIsResourceClass);
2✔
507
        }
508

509
        // TODO: remove in 5.x
510
        $builtInTypes = $propertyMetadata->getBuiltinTypes() ?? [];
×
511

512
        foreach ($builtInTypes as $type) {
×
513
            $className = $type->getClassName();
×
514
            if (
515
                !$type->isCollection()
×
516
                && null !== $className
×
517
                && $this->resourceClassResolver->isResourceClass($className)
×
518
            ) {
519
                return true;
×
520
            }
521
        }
522

523
        return false;
×
524
    }
525

526
    /**
527
     * Builds the classes array.
528
     */
529
    private function getClasses(array $entrypointProperties, array $classes, string $hydraPrefix = ContextBuilder::HYDRA_PREFIX): array
530
    {
531
        if ($this->entrypointEnabled) {
2✔
532
            $classes[] = [
2✔
533
                '@id' => '#Entrypoint',
2✔
534
                '@type' => $hydraPrefix.'Class',
2✔
535
                $hydraPrefix.'title' => 'Entrypoint',
2✔
536
                $hydraPrefix.'supportedProperty' => $entrypointProperties,
2✔
537
                $hydraPrefix.'supportedOperation' => [
2✔
538
                    '@type' => $hydraPrefix.'Operation',
2✔
539
                    $hydraPrefix.'method' => 'GET',
2✔
540
                    $hydraPrefix.'title' => 'index',
2✔
541
                    $hydraPrefix.'description' => 'The API Entrypoint.',
2✔
542
                    $hydraPrefix.'returns' => 'Entrypoint',
2✔
543
                ],
2✔
544
            ];
2✔
545
        }
546

547
        $classes[] = [
2✔
548
            '@id' => '#ConstraintViolationList',
2✔
549
            '@type' => $hydraPrefix.'Class',
2✔
550
            $hydraPrefix.'title' => 'ConstraintViolationList',
2✔
551
            $hydraPrefix.'description' => 'A constraint violation List.',
2✔
552
            $hydraPrefix.'supportedProperty' => [
2✔
553
                [
2✔
554
                    '@type' => $hydraPrefix.'SupportedProperty',
2✔
555
                    $hydraPrefix.'property' => [
2✔
556
                        '@id' => '#ConstraintViolationList/propertyPath',
2✔
557
                        '@type' => 'rdf:Property',
2✔
558
                        'rdfs:label' => 'propertyPath',
2✔
559
                        'domain' => '#ConstraintViolationList',
2✔
560
                        'range' => 'xmls:string',
2✔
561
                    ],
2✔
562
                    $hydraPrefix.'title' => 'propertyPath',
2✔
563
                    $hydraPrefix.'description' => 'The property path of the violation',
2✔
564
                    $hydraPrefix.'readable' => true,
2✔
565
                    $hydraPrefix.'writeable' => false,
2✔
566
                ],
2✔
567
                [
2✔
568
                    '@type' => $hydraPrefix.'SupportedProperty',
2✔
569
                    $hydraPrefix.'property' => [
2✔
570
                        '@id' => '#ConstraintViolationList/message',
2✔
571
                        '@type' => 'rdf:Property',
2✔
572
                        'rdfs:label' => 'message',
2✔
573
                        'domain' => '#ConstraintViolationList',
2✔
574
                        'range' => 'xmls:string',
2✔
575
                    ],
2✔
576
                    $hydraPrefix.'title' => 'message',
2✔
577
                    $hydraPrefix.'description' => 'The message associated with the violation',
2✔
578
                    $hydraPrefix.'readable' => true,
2✔
579
                    $hydraPrefix.'writeable' => false,
2✔
580
                ],
2✔
581
            ],
2✔
582
        ];
2✔
583

584
        return $classes;
2✔
585
    }
586

587
    /**
588
     * Gets a property definition.
589
     */
590
    private function getProperty(ApiProperty $propertyMetadata, string $propertyName, string $prefixedShortName, string $shortName, string $hydraPrefix): array
591
    {
592
        if ($iri = $propertyMetadata->getIris()) {
2✔
593
            $iri = 1 === (is_countable($iri) ? \count($iri) : 0) ? $iri[0] : $iri;
×
594
        }
595

596
        if (!isset($iri)) {
2✔
597
            $iri = "#$shortName/$propertyName";
2✔
598
        }
599

600
        $propertyData = ($propertyMetadata->getJsonldContext()[$hydraPrefix.'property'] ?? []) + [
2✔
601
            '@id' => $iri,
2✔
602
            '@type' => false === $propertyMetadata->isReadableLink() ? $hydraPrefix.'Link' : 'rdf:Property',
2✔
603
            'domain' => $prefixedShortName,
2✔
604
            'label' => $propertyName,
2✔
605
        ];
2✔
606

607
        if (!isset($propertyData['owl:deprecated']) && $propertyMetadata->getDeprecationReason()) {
2✔
608
            $propertyData['owl:deprecated'] = true;
×
609
        }
610

611
        if (!isset($propertyData['owl:maxCardinality']) && $this->isSingleRelation($propertyMetadata)) {
2✔
612
            $propertyData['owl:maxCardinality'] = 1;
×
613
        }
614

615
        if (!isset($propertyData['range']) && null !== $range = $this->getRange($propertyMetadata)) {
2✔
616
            $propertyData['range'] = $range;
2✔
617
        }
618

619
        $property = [
2✔
620
            '@type' => $hydraPrefix.'SupportedProperty',
2✔
621
            $hydraPrefix.'property' => $propertyData,
2✔
622
            $hydraPrefix.'title' => $propertyName,
2✔
623
            $hydraPrefix.'required' => $propertyMetadata->isRequired() ?? false,
2✔
624
            $hydraPrefix.'readable' => $propertyMetadata->isReadable(),
2✔
625
            $hydraPrefix.'writeable' => $propertyMetadata->isWritable() || $propertyMetadata->isInitializable(),
2✔
626
        ];
2✔
627

628
        if (null !== $description = $propertyMetadata->getDescription()) {
2✔
629
            $property[$hydraPrefix.'description'] = $description;
2✔
630
        }
631

632
        return $property;
2✔
633
    }
634

635
    /**
636
     * Computes the documentation.
637
     */
638
    private function computeDoc(Documentation $object, array $classes, string $hydraPrefix = ContextBuilder::HYDRA_PREFIX): array
639
    {
640
        $doc = ['@context' => $this->getContext($hydraPrefix), '@id' => $this->urlGenerator->generate('api_doc', ['_format' => self::FORMAT]), '@type' => $hydraPrefix.'ApiDocumentation'];
2✔
641

642
        if ('' !== $object->getTitle()) {
2✔
643
            $doc[$hydraPrefix.'title'] = $object->getTitle();
2✔
644
        }
645

646
        if ('' !== $object->getDescription()) {
2✔
647
            $doc[$hydraPrefix.'description'] = $object->getDescription();
2✔
648
        }
649

650
        if ($this->entrypointEnabled) {
2✔
651
            $doc[$hydraPrefix.'entrypoint'] = $this->urlGenerator->generate('api_entrypoint');
2✔
652
        }
653
        $doc[$hydraPrefix.'supportedClass'] = $classes;
2✔
654

655
        return $doc;
2✔
656
    }
657

658
    /**
659
     * Builds the JSON-LD context for the API documentation.
660
     */
661
    private function getContext(string $hydraPrefix = ContextBuilder::HYDRA_PREFIX): array
662
    {
663
        return [
2✔
664
            HYDRA_CONTEXT,
2✔
665
            [
2✔
666
                '@vocab' => $this->urlGenerator->generate('api_doc', ['_format' => self::FORMAT], UrlGeneratorInterface::ABS_URL).'#',
2✔
667
                'hydra' => ContextBuilderInterface::HYDRA_NS,
2✔
668
                'rdf' => ContextBuilderInterface::RDF_NS,
2✔
669
                'rdfs' => ContextBuilderInterface::RDFS_NS,
2✔
670
                'xmls' => ContextBuilderInterface::XML_NS,
2✔
671
                'owl' => ContextBuilderInterface::OWL_NS,
2✔
672
                'schema' => ContextBuilderInterface::SCHEMA_ORG_NS,
2✔
673
                'domain' => ['@id' => 'rdfs:domain', '@type' => '@id'],
2✔
674
                'range' => ['@id' => 'rdfs:range', '@type' => '@id'],
2✔
675
                'subClassOf' => ['@id' => 'rdfs:subClassOf', '@type' => '@id'],
2✔
676
            ],
2✔
677
        ];
2✔
678
    }
679

680
    /**
681
     * {@inheritdoc}
682
     */
683
    public function supportsNormalization(mixed $data, ?string $format = null, array $context = []): bool
684
    {
685
        return self::FORMAT === $format && $data instanceof Documentation;
2✔
686
    }
687

688
    /**
689
     * @param string|null $format
690
     */
691
    public function getSupportedTypes($format): array
692
    {
693
        return self::FORMAT === $format ? [Documentation::class => true] : [];
556✔
694
    }
695
}
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

© 2025 Coveralls, Inc