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

api-platform / core / 14726067612

29 Apr 2025 07:47AM UTC coverage: 23.443% (+15.2%) from 8.252%
14726067612

push

github

web-flow
feat(symfony): Autoconfigure classes using `#[ApiResource]` attribute (#6943)

0 of 12 new or added lines in 4 files covered. (0.0%)

3578 existing lines in 159 files now uncovered.

11517 of 49127 relevant lines covered (23.44%)

54.29 hits per line

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

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

44
use const ApiPlatform\JsonLd\HYDRA_CONTEXT;
45

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

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

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

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

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

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

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

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

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

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

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

133
        $entrypointProperties[] = $entrypointProperty;
8✔
134
    }
135

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

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

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

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

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

164
        return $class;
8✔
165
    }
166

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

180
        if ($normalizationGroups) {
8✔
181
            $propertyNameContext['serializer_groups'] = $normalizationGroups;
8✔
182
        }
183

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

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

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

194
        foreach ($denormalizationGroups as $group) {
8✔
195
            $propertyNameContext['serializer_groups'][] = $group;
8✔
196
        }
197

198
        return [$propertyNameContext, $propertyContext];
8✔
199
    }
200

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

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

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

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

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

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

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

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

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

250
        return $properties;
8✔
251
    }
252

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

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

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

273
        return $hydraOperations;
8✔
274
    }
275

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

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

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

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

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

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

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

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

350
        ksort($hydraOperation);
8✔
351

352
        return $hydraOperation;
8✔
353
    }
354

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

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

366
        $types = [];
8✔
367

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

374
            /** @var Type|null $collectionValueType */
375
            $collectionValueType = null;
8✔
376
            $typeIsCollection = static function (Type $type) use (&$typeIsCollection, &$collectionValueType): bool {
8✔
377
                return match (true) {
378
                    $type instanceof CollectionType => null !== $collectionValueType = $type->getCollectionValueType(),
8✔
379
                    $type instanceof WrappingTypeInterface => $type->wrappedTypeIsSatisfiedBy($typeIsCollection),
8✔
380
                    $type instanceof CompositeTypeInterface => $type->composedTypesAreSatisfiedBy($typeIsCollection),
8✔
381
                    default => false,
8✔
382
                };
383
            };
8✔
384

385
            if ($nativeType->isSatisfiedBy($typeIsCollection)) {
8✔
386
                $nativeType = $collectionValueType;
8✔
387
            }
388

389
            // Check for specific types after potentially unwrapping the collection
390
            if (null === $nativeType) {
8✔
391
                return null; // Should not happen if collection had a value type, but safety check
×
392
            }
393

394
            if ($nativeType->isIdentifiedBy(TypeIdentifier::STRING)) {
8✔
395
                $types[] = 'xmls:string';
8✔
396
            }
397

398
            if ($nativeType->isIdentifiedBy(TypeIdentifier::INT)) {
8✔
399
                $types[] = 'xmls:integer';
8✔
400
            }
401

402
            if ($nativeType->isIdentifiedBy(TypeIdentifier::FLOAT)) {
8✔
403
                $types[] = 'xmls:decimal';
8✔
404
            }
405

406
            if ($nativeType->isIdentifiedBy(TypeIdentifier::BOOL)) {
8✔
407
                $types[] = 'xmls:boolean';
8✔
408
            }
409

410
            if ($nativeType->isIdentifiedBy(\DateTimeInterface::class)) {
8✔
411
                $types[] = 'xmls:dateTime';
8✔
412
            }
413

414
            /** @var class-string|null $className */
415
            $className = null;
8✔
416

417
            $typeIsResourceClass = function (Type $type) use (&$className): bool {
8✔
418
                return $type instanceof ObjectType && $this->resourceClassResolver->isResourceClass($className = $type->getClassName());
8✔
419
            };
8✔
420

421
            if ($nativeType->isSatisfiedBy($typeIsResourceClass) && $className) {
8✔
422
                $resourceMetadata = $this->resourceMetadataFactory->create($className);
8✔
423
                $operation = $resourceMetadata->getOperation();
8✔
424

425
                if (!$operation instanceof HttpOperation || !$operation->getTypes()) {
8✔
426
                    if (!\in_array("#{$operation->getShortName()}", $types, true)) {
8✔
427
                        $types[] = "#{$operation->getShortName()}";
8✔
428
                    }
429
                } else {
430
                    $types = array_unique(array_merge($types, $operation->getTypes()));
8✔
431
                }
432
            }
433
        // TODO: remove in 5.x
434
        } else {
UNCOV
435
            $builtInTypes = $propertyMetadata->getBuiltinTypes() ?? [];
×
436

UNCOV
437
            foreach ($builtInTypes as $type) {
×
UNCOV
438
                if ($type->isCollection() && null !== $collectionType = $type->getCollectionValueTypes()[0] ?? null) {
×
439
                    $type = $collectionType;
×
440
                }
441

442
                switch ($type->getBuiltinType()) {
×
443
                    case LegacyType::BUILTIN_TYPE_STRING:
×
UNCOV
444
                        if (!\in_array('xmls:string', $types, true)) {
×
UNCOV
445
                            $types[] = 'xmls:string';
×
446
                        }
UNCOV
447
                        break;
×
448
                    case LegacyType::BUILTIN_TYPE_INT:
×
449
                        if (!\in_array('xmls:integer', $types, true)) {
×
UNCOV
450
                            $types[] = 'xmls:integer';
×
451
                        }
UNCOV
452
                        break;
×
453
                    case LegacyType::BUILTIN_TYPE_FLOAT:
×
454
                        if (!\in_array('xmls:decimal', $types, true)) {
×
UNCOV
455
                            $types[] = 'xmls:decimal';
×
456
                        }
UNCOV
457
                        break;
×
458
                    case LegacyType::BUILTIN_TYPE_BOOL:
×
459
                        if (!\in_array('xmls:boolean', $types, true)) {
×
UNCOV
460
                            $types[] = 'xmls:boolean';
×
461
                        }
UNCOV
462
                        break;
×
463
                    case LegacyType::BUILTIN_TYPE_OBJECT:
×
464
                        if (null === $className = $type->getClassName()) {
×
UNCOV
465
                            continue 2;
×
466
                        }
467

468
                        if (is_a($className, \DateTimeInterface::class, true)) {
×
469
                            if (!\in_array('xmls:dateTime', $types, true)) {
×
UNCOV
470
                                $types[] = 'xmls:dateTime';
×
471
                            }
472
                            break;
×
473
                        }
474

UNCOV
475
                        if ($this->resourceClassResolver->isResourceClass($className)) {
×
476
                            $resourceMetadata = $this->resourceMetadataFactory->create($className);
×
UNCOV
477
                            $operation = $resourceMetadata->getOperation();
×
478

479
                            if (!$operation instanceof HttpOperation || !$operation->getTypes()) {
×
480
                                if (!\in_array("#{$operation->getShortName()}", $types, true)) {
×
481
                                    $types[] = "#{$operation->getShortName()}";
×
482
                                }
483
                                break;
×
484
                            }
485

UNCOV
486
                            $types = array_unique(array_merge($types, $operation->getTypes()));
×
487
                            break;
×
488
                        }
489
                }
490
            }
491
        }
492

493
        if ([] === $types) {
8✔
494
            return null;
8✔
495
        }
496

497
        $types = array_unique($types);
8✔
498

499
        return 1 === \count($types) ? $types[0] : $types;
8✔
500
    }
501

502
    private function isSingleRelation(ApiProperty $propertyMetadata): bool
503
    {
504
        if (method_exists(PropertyInfoExtractor::class, 'getType')) {
8✔
505
            $nativeType = $propertyMetadata->getNativeType();
8✔
506
            if (null === $nativeType) {
8✔
507
                return false;
8✔
508
            }
509

510
            if ($nativeType instanceof CollectionType) {
8✔
511
                return false;
8✔
512
            }
513

514
            $typeIsResourceClass = function (Type $type) use (&$className): bool {
8✔
515
                return $type instanceof ObjectType && $this->resourceClassResolver->isResourceClass($className = $type->getClassName());
8✔
516
            };
8✔
517

518
            return $nativeType->isSatisfiedBy($typeIsResourceClass);
8✔
519
        }
520

521
        // TODO: remove in 5.x
UNCOV
522
        $builtInTypes = $propertyMetadata->getBuiltinTypes() ?? [];
×
523

UNCOV
524
        foreach ($builtInTypes as $type) {
×
UNCOV
525
            $className = $type->getClassName();
×
526
            if (
UNCOV
527
                !$type->isCollection()
×
UNCOV
528
                && null !== $className
×
UNCOV
529
                && $this->resourceClassResolver->isResourceClass($className)
×
530
            ) {
531
                return true;
×
532
            }
533
        }
534

UNCOV
535
        return false;
×
536
    }
537

538
    /**
539
     * Builds the classes array.
540
     */
541
    private function getClasses(array $entrypointProperties, array $classes, string $hydraPrefix = ContextBuilder::HYDRA_PREFIX): array
542
    {
543
        if ($this->entrypointEnabled) {
8✔
544
            $classes[] = [
8✔
545
                '@id' => '#Entrypoint',
8✔
546
                '@type' => $hydraPrefix.'Class',
8✔
547
                $hydraPrefix.'title' => 'Entrypoint',
8✔
548
                $hydraPrefix.'supportedProperty' => $entrypointProperties,
8✔
549
                $hydraPrefix.'supportedOperation' => [
8✔
550
                    '@type' => $hydraPrefix.'Operation',
8✔
551
                    $hydraPrefix.'method' => 'GET',
8✔
552
                    $hydraPrefix.'title' => 'index',
8✔
553
                    $hydraPrefix.'description' => 'The API Entrypoint.',
8✔
554
                    $hydraPrefix.'returns' => 'Entrypoint',
8✔
555
                ],
8✔
556
            ];
8✔
557
        }
558

559
        $classes[] = [
8✔
560
            '@id' => '#ConstraintViolationList',
8✔
561
            '@type' => $hydraPrefix.'Class',
8✔
562
            $hydraPrefix.'title' => 'ConstraintViolationList',
8✔
563
            $hydraPrefix.'description' => 'A constraint violation List.',
8✔
564
            $hydraPrefix.'supportedProperty' => [
8✔
565
                [
8✔
566
                    '@type' => $hydraPrefix.'SupportedProperty',
8✔
567
                    $hydraPrefix.'property' => [
8✔
568
                        '@id' => '#ConstraintViolationList/propertyPath',
8✔
569
                        '@type' => 'rdf:Property',
8✔
570
                        'rdfs:label' => 'propertyPath',
8✔
571
                        'domain' => '#ConstraintViolationList',
8✔
572
                        'range' => 'xmls:string',
8✔
573
                    ],
8✔
574
                    $hydraPrefix.'title' => 'propertyPath',
8✔
575
                    $hydraPrefix.'description' => 'The property path of the violation',
8✔
576
                    $hydraPrefix.'readable' => true,
8✔
577
                    $hydraPrefix.'writeable' => false,
8✔
578
                ],
8✔
579
                [
8✔
580
                    '@type' => $hydraPrefix.'SupportedProperty',
8✔
581
                    $hydraPrefix.'property' => [
8✔
582
                        '@id' => '#ConstraintViolationList/message',
8✔
583
                        '@type' => 'rdf:Property',
8✔
584
                        'rdfs:label' => 'message',
8✔
585
                        'domain' => '#ConstraintViolationList',
8✔
586
                        'range' => 'xmls:string',
8✔
587
                    ],
8✔
588
                    $hydraPrefix.'title' => 'message',
8✔
589
                    $hydraPrefix.'description' => 'The message associated with the violation',
8✔
590
                    $hydraPrefix.'readable' => true,
8✔
591
                    $hydraPrefix.'writeable' => false,
8✔
592
                ],
8✔
593
            ],
8✔
594
        ];
8✔
595

596
        return $classes;
8✔
597
    }
598

599
    /**
600
     * Gets a property definition.
601
     */
602
    private function getProperty(ApiProperty $propertyMetadata, string $propertyName, string $prefixedShortName, string $shortName, string $hydraPrefix): array
603
    {
604
        if ($iri = $propertyMetadata->getIris()) {
8✔
605
            $iri = 1 === (is_countable($iri) ? \count($iri) : 0) ? $iri[0] : $iri;
8✔
606
        }
607

608
        if (!isset($iri)) {
8✔
609
            $iri = "#$shortName/$propertyName";
8✔
610
        }
611

612
        $propertyData = ($propertyMetadata->getJsonldContext()[$hydraPrefix.'property'] ?? []) + [
8✔
613
            '@id' => $iri,
8✔
614
            '@type' => false === $propertyMetadata->isReadableLink() ? $hydraPrefix.'Link' : 'rdf:Property',
8✔
615
            'domain' => $prefixedShortName,
8✔
616
            'label' => $propertyName,
8✔
617
        ];
8✔
618

619
        if (!isset($propertyData['owl:deprecated']) && $propertyMetadata->getDeprecationReason()) {
8✔
620
            $propertyData['owl:deprecated'] = true;
8✔
621
        }
622

623
        if (!isset($propertyData['owl:maxCardinality']) && $this->isSingleRelation($propertyMetadata)) {
8✔
624
            $propertyData['owl:maxCardinality'] = 1;
8✔
625
        }
626

627
        if (!isset($propertyData['range']) && null !== $range = $this->getRange($propertyMetadata)) {
8✔
628
            $propertyData['range'] = $range;
8✔
629
        }
630

631
        $property = [
8✔
632
            '@type' => $hydraPrefix.'SupportedProperty',
8✔
633
            $hydraPrefix.'property' => $propertyData,
8✔
634
            $hydraPrefix.'title' => $propertyName,
8✔
635
            $hydraPrefix.'required' => $propertyMetadata->isRequired() ?? false,
8✔
636
            $hydraPrefix.'readable' => $propertyMetadata->isReadable(),
8✔
637
            $hydraPrefix.'writeable' => $propertyMetadata->isWritable() || $propertyMetadata->isInitializable(),
8✔
638
        ];
8✔
639

640
        if (null !== $description = $propertyMetadata->getDescription()) {
8✔
641
            $property[$hydraPrefix.'description'] = $description;
8✔
642
        }
643

644
        return $property;
8✔
645
    }
646

647
    /**
648
     * Computes the documentation.
649
     */
650
    private function computeDoc(Documentation $object, array $classes, string $hydraPrefix = ContextBuilder::HYDRA_PREFIX): array
651
    {
652
        $doc = ['@context' => $this->getContext($hydraPrefix), '@id' => $this->urlGenerator->generate('api_doc', ['_format' => self::FORMAT]), '@type' => $hydraPrefix.'ApiDocumentation'];
8✔
653

654
        if ('' !== $object->getTitle()) {
8✔
655
            $doc[$hydraPrefix.'title'] = $object->getTitle();
8✔
656
        }
657

658
        if ('' !== $object->getDescription()) {
8✔
659
            $doc[$hydraPrefix.'description'] = $object->getDescription();
8✔
660
        }
661

662
        if ($this->entrypointEnabled) {
8✔
663
            $doc[$hydraPrefix.'entrypoint'] = $this->urlGenerator->generate('api_entrypoint');
8✔
664
        }
665
        $doc[$hydraPrefix.'supportedClass'] = $classes;
8✔
666

667
        return $doc;
8✔
668
    }
669

670
    /**
671
     * Builds the JSON-LD context for the API documentation.
672
     */
673
    private function getContext(string $hydraPrefix = ContextBuilder::HYDRA_PREFIX): array
674
    {
675
        return [
8✔
676
            HYDRA_CONTEXT,
8✔
677
            [
8✔
678
                '@vocab' => $this->urlGenerator->generate('api_doc', ['_format' => self::FORMAT], UrlGeneratorInterface::ABS_URL).'#',
8✔
679
                'hydra' => ContextBuilderInterface::HYDRA_NS,
8✔
680
                'rdf' => ContextBuilderInterface::RDF_NS,
8✔
681
                'rdfs' => ContextBuilderInterface::RDFS_NS,
8✔
682
                'xmls' => ContextBuilderInterface::XML_NS,
8✔
683
                'owl' => ContextBuilderInterface::OWL_NS,
8✔
684
                'schema' => ContextBuilderInterface::SCHEMA_ORG_NS,
8✔
685
                'domain' => ['@id' => 'rdfs:domain', '@type' => '@id'],
8✔
686
                'range' => ['@id' => 'rdfs:range', '@type' => '@id'],
8✔
687
                'subClassOf' => ['@id' => 'rdfs:subClassOf', '@type' => '@id'],
8✔
688
            ],
8✔
689
        ];
8✔
690
    }
691

692
    /**
693
     * {@inheritdoc}
694
     */
695
    public function supportsNormalization(mixed $data, ?string $format = null, array $context = []): bool
696
    {
697
        return self::FORMAT === $format && $data instanceof Documentation;
8✔
698
    }
699

700
    public function getSupportedTypes($format): array
701
    {
702
        return self::FORMAT === $format ? [Documentation::class => true] : [];
1,432✔
703
    }
704
}
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