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

api-platform / core / 16705318661

03 Aug 2025 01:05PM UTC coverage: 0.0% (-21.9%) from 21.944%
16705318661

Pull #7317

github

web-flow
Merge 1ca8642ff into d06b1a0a0
Pull Request #7317: Fix/4372 skip null values in hal

0 of 14 new or added lines in 3 files covered. (0.0%)

11680 existing lines in 376 files now uncovered.

0 of 51817 relevant lines covered (0.0%)

0.0 hits per line

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

0.0
/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
    ) {
UNCOV
65
    }
×
66

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

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

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

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

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

UNCOV
91
        return $this->computeDoc($object, $this->getClasses($entrypointProperties, $classes, $hydraPrefix), $hydraPrefix);
×
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
    {
UNCOV
99
        $hydraCollectionOperations = $this->getHydraOperations(true, $resourceMetadataCollection, $hydraPrefix);
×
UNCOV
100
        if (empty($hydraCollectionOperations)) {
×
UNCOV
101
            return;
×
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
    {
UNCOV
140
        $description = $resourceMetadata->getDescription();
×
UNCOV
141
        $isDeprecated = $resourceMetadata->getDeprecationReason();
×
142

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

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

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

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

UNCOV
163
        return $class;
×
164
    }
165

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

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

UNCOV
183
        if (!$denormalizationGroups) {
×
UNCOV
184
            return [$propertyNameContext, $propertyContext];
×
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
    {
UNCOV
205
        $classes = [];
×
206

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

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

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

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

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

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

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

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

UNCOV
249
        return $properties;
×
250
    }
251

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

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

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

UNCOV
272
        return $hydraOperations;
×
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
    {
UNCOV
280
        $method = $operation->getMethod() ?: 'GET';
×
281

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

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

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

UNCOV
294
        if ('GET' === $method && $operation instanceof CollectionOperationInterface) {
×
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
            ];
×
UNCOV
300
        } elseif ('GET' === $method) {
×
UNCOV
301
            $hydraOperation += [
×
UNCOV
302
                '@type' => [$hydraPrefix.'Operation', 'schema:FindAction'],
×
UNCOV
303
                $hydraPrefix.'description' => "Retrieves a $shortName resource.",
×
UNCOV
304
                'returns' => null === $outputClass ? 'owl:Nothing' : $prefixedShortName,
×
UNCOV
305
            ];
×
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

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

UNCOV
349
        ksort($hydraOperation);
×
350

UNCOV
351
        return $hydraOperation;
×
352
    }
353

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

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

UNCOV
365
        $types = [];
×
366

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

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

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

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

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

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

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

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

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

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

UNCOV
409
            if ($nativeType->isSatisfiedBy($typeIsResourceClass) && $className) {
×
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

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

UNCOV
485
        $types = array_unique($types);
×
486

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

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

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

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

UNCOV
506
            return $nativeType->isSatisfiedBy($typeIsResourceClass);
×
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
    {
UNCOV
531
        if ($this->entrypointEnabled) {
×
UNCOV
532
            $classes[] = [
×
UNCOV
533
                '@id' => '#Entrypoint',
×
UNCOV
534
                '@type' => $hydraPrefix.'Class',
×
UNCOV
535
                $hydraPrefix.'title' => 'Entrypoint',
×
UNCOV
536
                $hydraPrefix.'supportedProperty' => $entrypointProperties,
×
UNCOV
537
                $hydraPrefix.'supportedOperation' => [
×
UNCOV
538
                    '@type' => $hydraPrefix.'Operation',
×
UNCOV
539
                    $hydraPrefix.'method' => 'GET',
×
UNCOV
540
                    $hydraPrefix.'title' => 'index',
×
UNCOV
541
                    $hydraPrefix.'description' => 'The API Entrypoint.',
×
UNCOV
542
                    $hydraPrefix.'returns' => 'Entrypoint',
×
UNCOV
543
                ],
×
UNCOV
544
            ];
×
545
        }
546

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

UNCOV
584
        return $classes;
×
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
    {
UNCOV
592
        if ($iri = $propertyMetadata->getIris()) {
×
593
            $iri = 1 === (is_countable($iri) ? \count($iri) : 0) ? $iri[0] : $iri;
×
594
        }
595

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

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

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

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

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

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

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

UNCOV
632
        return $property;
×
633
    }
634

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

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

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

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

UNCOV
655
        return $doc;
×
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
    {
UNCOV
663
        return [
×
UNCOV
664
            HYDRA_CONTEXT,
×
UNCOV
665
            [
×
UNCOV
666
                '@vocab' => $this->urlGenerator->generate('api_doc', ['_format' => self::FORMAT], UrlGeneratorInterface::ABS_URL).'#',
×
UNCOV
667
                'hydra' => ContextBuilderInterface::HYDRA_NS,
×
UNCOV
668
                'rdf' => ContextBuilderInterface::RDF_NS,
×
UNCOV
669
                'rdfs' => ContextBuilderInterface::RDFS_NS,
×
UNCOV
670
                'xmls' => ContextBuilderInterface::XML_NS,
×
UNCOV
671
                'owl' => ContextBuilderInterface::OWL_NS,
×
UNCOV
672
                'schema' => ContextBuilderInterface::SCHEMA_ORG_NS,
×
UNCOV
673
                'domain' => ['@id' => 'rdfs:domain', '@type' => '@id'],
×
UNCOV
674
                'range' => ['@id' => 'rdfs:range', '@type' => '@id'],
×
UNCOV
675
                'subClassOf' => ['@id' => 'rdfs:subClassOf', '@type' => '@id'],
×
UNCOV
676
            ],
×
UNCOV
677
        ];
×
678
    }
679

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

688
    public function getSupportedTypes($format): array
689
    {
UNCOV
690
        return self::FORMAT === $format ? [Documentation::class => true] : [];
×
691
    }
692
}
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