diff --git a/phpstan.neon.dist b/phpstan.neon.dist index e7e440998df..c0f6e770b05 100644 --- a/phpstan.neon.dist +++ b/phpstan.neon.dist @@ -199,3 +199,25 @@ parameters: identifier: function.alreadyNarrowedType path: tests/Symfony/Bundle/Command/DebugResourceCommandTest.php reportUnmatched: false + + # Runtime resource example services are registered only by the runtime_resources test kernel configs + - + message: '#Service "ApiPlatform\\Tests\\Fixtures\\TestBundle\\RuntimeResource\\DefinitionProvider" is not registered in the container\.#' + identifier: symfonyContainer.serviceNotFound + path: tests/Functional/RuntimeResourceEavTest.php + count: 4 + - + message: '#Service "ApiPlatform\\Tests\\Fixtures\\TestBundle\\RuntimeResource\\RuntimeResources" is not registered in the container\.#' + identifier: symfonyContainer.serviceNotFound + path: tests/Functional/RuntimeResourceEavTest.php + count: 2 + - + message: '#Service "ApiPlatform\\Tests\\Fixtures\\TestBundle\\RuntimeResource\\DefinitionProvider" is not registered in the container\.#' + identifier: symfonyContainer.serviceNotFound + path: tests/Functional/RuntimeResourceMongoDbTest.php + count: 4 + - + message: '#Service "ApiPlatform\\Tests\\Fixtures\\TestBundle\\RuntimeResource\\RuntimeResources" is not registered in the container\.#' + identifier: symfonyContainer.serviceNotFound + path: tests/Functional/RuntimeResourceMongoDbTest.php + count: 2 diff --git a/src/JsonSchema/DefinitionNameFactory.php b/src/JsonSchema/DefinitionNameFactory.php index 3316da57e1a..2bd9c44ba08 100644 --- a/src/JsonSchema/DefinitionNameFactory.php +++ b/src/JsonSchema/DefinitionNameFactory.php @@ -16,8 +16,9 @@ use ApiPlatform\Metadata\Operation; use ApiPlatform\Metadata\Util\ResourceClassInfoTrait; use Symfony\Component\Serializer\Normalizer\AbstractNormalizer; +use Symfony\Contracts\Service\ResetInterface; -final class DefinitionNameFactory implements DefinitionNameFactoryInterface +final class DefinitionNameFactory implements DefinitionNameFactoryInterface, ResetInterface { use ResourceClassInfoTrait; @@ -26,6 +27,11 @@ final class DefinitionNameFactory implements DefinitionNameFactoryInterface private array $prefixCache = []; + public function reset(): void + { + $this->prefixCache = []; + } + public function create(string $className, string $format = 'json', ?string $inputOrOutputClass = null, ?Operation $operation = null, array $serializerContext = []): string { if ($operation) { diff --git a/src/JsonSchema/Tests/DefinitionNameFactoryTest.php b/src/JsonSchema/Tests/DefinitionNameFactoryTest.php index 347c92dd4b5..454821907a6 100644 --- a/src/JsonSchema/Tests/DefinitionNameFactoryTest.php +++ b/src/JsonSchema/Tests/DefinitionNameFactoryTest.php @@ -231,4 +231,16 @@ public function testCreateDifferentPrefixesForClassesWithTheSameOperationShortNa $definitionNameFactory->create(Fixtures\DefinitionNameFactory\NamespaceC\Module\DummyClass::class, 'jsonapi', null, new Get(class: Fixtures\DefinitionNameFactory\NamespaceC\Module\DummyClass::class, shortName: 'DummyClass')) ); } + + public function testResetClearsShortNamePrefixCache(): void + { + $definitionNameFactory = new DefinitionNameFactory(); + + $this->assertSame('Thing', $definitionNameFactory->create(InputThingCreate::class, 'json', null, new Get(class: InputThingCreate::class, shortName: 'Thing'))); + $this->assertNotSame('Thing', $definitionNameFactory->create(OutputThingCreate::class, 'json', null, new Get(class: OutputThingCreate::class, shortName: 'Thing'))); + + $definitionNameFactory->reset(); + + $this->assertSame('Thing', $definitionNameFactory->create(OutputThingCreate::class, 'json', null, new Get(class: OutputThingCreate::class, shortName: 'Thing'))); + } } diff --git a/src/Metadata/IdentifiersExtractor.php b/src/Metadata/IdentifiersExtractor.php index 3b3015a6fc9..cf093c48a63 100644 --- a/src/Metadata/IdentifiersExtractor.php +++ b/src/Metadata/IdentifiersExtractor.php @@ -22,6 +22,7 @@ use ApiPlatform\Metadata\Util\ResourceClassInfoTrait; use ApiPlatform\Metadata\Util\TypeHelper; use Symfony\Component\PropertyAccess\Exception\NoSuchPropertyException; +use Symfony\Component\PropertyAccess\Exception\UnexpectedTypeException; use Symfony\Component\PropertyAccess\PropertyAccess; use Symfony\Component\PropertyAccess\PropertyAccessorInterface; @@ -122,7 +123,11 @@ private function getIdentifierValue(object $item, string $class, string $propert } if ($toProperty) { - return $this->resolveIdentifierValue($this->propertyAccessor->getValue($item, "$toProperty.$property"), $parameterName); + try { + return $this->resolveIdentifierValue($this->propertyAccessor->getValue($item, "$toProperty.$property"), $parameterName); + } catch (NoSuchPropertyException|UnexpectedTypeException $e) { + throw new RuntimeException('Not able to retrieve identifiers.', $e->getCode(), $e); + } } $resourceClass = $this->getResourceClass($item, true); @@ -144,7 +149,7 @@ private function getIdentifierValue(object $item, string $class, string $propert if ($type->isIdentifiedBy($class)) { return $this->resolveIdentifierValue($this->propertyAccessor->getValue($item, "$propertyName.$property"), $parameterName); } - } catch (NoSuchPropertyException $e) { + } catch (NoSuchPropertyException|UnexpectedTypeException $e) { throw new RuntimeException('Not able to retrieve identifiers.', $e->getCode(), $e); } } diff --git a/src/Metadata/Tests/IdentifiersExtractorTest.php b/src/Metadata/Tests/IdentifiersExtractorTest.php index 9693e3499b1..6879d57c4aa 100644 --- a/src/Metadata/Tests/IdentifiersExtractorTest.php +++ b/src/Metadata/Tests/IdentifiersExtractorTest.php @@ -13,6 +13,7 @@ namespace ApiPlatform\Metadata\Tests; +use ApiPlatform\Metadata\Exception\RuntimeException; use ApiPlatform\Metadata\Get; use ApiPlatform\Metadata\HttpOperation; use ApiPlatform\Metadata\IdentifiersExtractor; @@ -24,6 +25,7 @@ use ApiPlatform\Metadata\Tests\Fixtures\ApiResource\Dummy; use ApiPlatform\Metadata\Tests\Fixtures\ApiResource\DummyWithEnumIdentifier; use ApiPlatform\Metadata\Tests\Fixtures\ApiResource\RelationMultiple; +use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\TestCase; use Prophecy\Argument; use Prophecy\PhpUnit\ProphecyTrait; @@ -174,6 +176,46 @@ public function testGetIdentifiersFromItemWithToProperty(): void ); } + public static function unreadableToPropertyProvider(): iterable + { + yield 'missing property' => ['missing']; + yield 'null relation' => ['first']; + } + + #[DataProvider('unreadableToPropertyProvider')] + public function testGetIdentifiersFromItemWithUnreadableToPropertyThrowsRuntimeException(string $toProperty): void + { + $resourceClassResolver = $this->createStub(ResourceClassResolverInterface::class); + $resourceClassResolver->method('isResourceClass')->willReturn(true); + $resourceClassResolver->method('getResourceClass')->willReturn(RelationMultiple::class); + + $identifiersExtractor = new IdentifiersExtractor( + $this->createStub(ResourceMetadataCollectionFactoryInterface::class), + $resourceClassResolver, + $this->createStub(PropertyNameCollectionFactoryInterface::class), + $this->createStub(PropertyMetadataFactoryInterface::class) + ); + + $operation = (new Get()) + ->withUriTemplate('/resources/{firstId}') + ->withUriVariables([ + 'firstId' => (new Link()) + ->withFromClass(Dummy::class) + ->withToProperty($toProperty) + ->withIdentifiers(['id']) + ->withParameterName('firstId'), + ]) + ->withClass(RelationMultiple::class); + + $item = new RelationMultiple(); + $item->id = 1; + + $this->expectException(RuntimeException::class); + $this->expectExceptionMessage('Not able to retrieve identifiers.'); + + $identifiersExtractor->getIdentifiersFromItem($item, $operation); + } + public function testGetIdentifierWithEnumValues(): void { $resourceMetadataFactoryProphecy = $this->prophesize(ResourceMetadataCollectionFactoryInterface::class); diff --git a/src/OpenApi/Factory/OpenApiFactory.php b/src/OpenApi/Factory/OpenApiFactory.php index 4e26ad1c83d..b17f969a018 100644 --- a/src/OpenApi/Factory/OpenApiFactory.php +++ b/src/OpenApi/Factory/OpenApiFactory.php @@ -225,7 +225,10 @@ private function collectPaths(ApiResource $resource, ResourceMetadataCollection $this->routeCollection = $this->router->getRouteCollection(); } - if ($this->routeCollection && $routeName && $route = $this->routeCollection->get($routeName)) { + $extraProperties = $operation->getExtraProperties(); + if ($operation->getRouteName() && ($extraProperties['user_defined_uri_template'] ?? false) && true === ($extraProperties['openapi_use_uri_template'] ?? false)) { + $path = rtrim($operation->getRoutePrefix() ?? '', '/').'/'.ltrim($operation->getUriTemplate() ?? '', '/'); + } elseif ($this->routeCollection && $routeName && $route = $this->routeCollection->get($routeName)) { $path = $route->getPath(); } else { $path = rtrim($operation->getRoutePrefix() ?? '', '/').'/'.ltrim($operation->getUriTemplate() ?? '', '/'); @@ -312,6 +315,10 @@ private function collectPaths(ApiResource $resource, ResourceMetadataCollection continue; } + if (!str_contains($path, '{'.$parameterName.'}')) { + continue; + } + $description = $uriVariable->getDescription(); if (null === $description) { $fromClass = $uriVariable->getFromClass(); diff --git a/src/OpenApi/Tests/Factory/OpenApiFactoryTest.php b/src/OpenApi/Tests/Factory/OpenApiFactoryTest.php index 223edf36a04..f8184819596 100644 --- a/src/OpenApi/Tests/Factory/OpenApiFactoryTest.php +++ b/src/OpenApi/Tests/Factory/OpenApiFactoryTest.php @@ -74,6 +74,9 @@ use Prophecy\Argument; use Prophecy\PhpUnit\ProphecyTrait; use Psr\Container\ContainerInterface; +use Symfony\Component\Routing\Route; +use Symfony\Component\Routing\RouteCollection; +use Symfony\Component\Routing\RouterInterface; use Symfony\Component\Serializer\NameConverter\CamelCaseToSnakeCaseNameConverter; use Symfony\Component\TypeInfo\Type; @@ -287,7 +290,7 @@ public function testInvoke(): void $baseOperation = (new HttpOperation())->withTypes(['http://schema.example.com/Dummy'])->withInputFormats(self::OPERATION_FORMATS['input_formats'])->withOutputFormats(self::OPERATION_FORMATS['output_formats'])->withClass(Dummy::class)->withShortName('Parameter')->withDescription('This is a dummy'); $parameterResource = (new ApiResource())->withOperations(new Operations([ - 'uriVariableSchema' => (new Get(uriTemplate: '/uri_variable_uuid', uriVariables: ['id' => new Link(schema: ['type' => 'string', 'format' => 'uuid'], description: 'hello', required: true, openApi: new Parameter('id', 'path'))]))->withOperation($baseOperation), + 'uriVariableSchema' => (new Get(uriTemplate: '/uri_variable_uuid/{id}', uriVariables: ['id' => new Link(schema: ['type' => 'string', 'format' => 'uuid'], description: 'hello', required: true, openApi: new Parameter('id', 'path'))]))->withOperation($baseOperation), 'parameters' => (new Put(uriTemplate: '/parameters', parameters: [ 'foo' => new HeaderParameter(description: 'hi', schema: ['type' => 'string', 'format' => 'uuid']), ]))->withOperation($baseOperation), @@ -1334,7 +1337,7 @@ public function testInvoke(): void ) ), $emptyResponsePath->getPost()); - $parameter = $paths->getPath('/uri_variable_uuid')->getGet()->getParameters()[0]; + $parameter = $paths->getPath('/uri_variable_uuid/{id}')->getGet()->getParameters()[0]; $this->assertEquals(['type' => 'string', 'format' => 'uuid'], $parameter->getSchema()); $parameter = $paths->getPath('/parameters')->getPut()->getParameters()[0]; @@ -2004,6 +2007,86 @@ public function testDeleteOperationWithDeserializeDocumentsRequestBody(): void $this->assertCount(0, $plainInputSchema->getDefinitions()); } + public function testUriVariableAbsentFromPathIsSkipped(): void + { + $openApi = $this->createOpenApiForOperations([ + (new Get()) + ->withUriTemplate('/things/fixed/{id}') + ->withUriVariables([ + 'kind' => new Link(fromClass: Dummy::class, identifiers: ['kind']), + 'id' => new Link(fromClass: Dummy::class, identifiers: ['id']), + ]) + ->withShortName('Dummy') + ->withName('things_fixed_get'), + ]); + + $parameters = $openApi->getPaths()->getPath('/things/fixed/{id}')->getGet()->getParameters(); + + $this->assertSame(['id'], array_map(static fn (Parameter $parameter): string => $parameter->getName(), array_values(array_filter($parameters, static fn (Parameter $parameter): bool => 'path' === $parameter->getIn())))); + } + + public function testUserDefinedUriTemplateIsDocumentedInsteadOfSharedRoutePathWhenOptedIn(): void + { + $routeCollection = new RouteCollection(); + $routeCollection->add('shared_route', new Route('/shared/{kind}')); + $router = $this->createStub(RouterInterface::class); + $router->method('getRouteCollection')->willReturn($routeCollection); + + $operations = static fn (array $extraProperties): array => [ + (new Get())->withUriTemplate('/shared/a')->withRouteName('shared_route')->withShortName('Dummy')->withName('shared_a')->withExtraProperties($extraProperties), + (new Get())->withUriTemplate('/shared/b')->withRouteName('shared_route')->withShortName('Dummy')->withName('shared_b')->withExtraProperties($extraProperties), + ]; + + $optedIn = $this->createOpenApiForOperations($operations(['user_defined_uri_template' => true, 'openapi_use_uri_template' => true]), $router); + $this->assertSame(['/shared/a', '/shared/b'], array_keys($optedIn->getPaths()->getPaths())); + + $default = $this->createOpenApiForOperations($operations(['user_defined_uri_template' => true]), $router); + $this->assertSame(['/shared/{kind}'], array_keys($default->getPaths()->getPaths())); + } + + /** + * @param HttpOperation[] $operations + */ + private function createOpenApiForOperations(array $operations, ?RouterInterface $router = null): OpenApi + { + $resourceNameCollectionFactory = $this->createStub(ResourceNameCollectionFactoryInterface::class); + $resourceCollectionMetadataFactory = $this->createStub(ResourceMetadataCollectionFactoryInterface::class); + $propertyNameCollectionFactory = $this->createStub(PropertyNameCollectionFactoryInterface::class); + $propertyMetadataFactory = $this->createStub(PropertyMetadataFactoryInterface::class); + + $resourceCollectionMetadata = new ResourceMetadataCollection(Dummy::class, [(new ApiResource(operations: $operations))->withClass(Dummy::class)]); + + $resourceCollectionMetadataFactory + ->method('create') + ->willReturnCallback(static fn (string $resourceClass): ResourceMetadataCollection => Dummy::class === $resourceClass ? $resourceCollectionMetadata : new ResourceMetadataCollection($resourceClass, [])); + $resourceNameCollectionFactory->method('create')->willReturn(new ResourceNameCollection([Dummy::class])); + $propertyNameCollectionFactory->method('create')->willReturn(new PropertyNameCollection([])); + + $schemaFactory = new SchemaFactory( + resourceMetadataFactory: $resourceCollectionMetadataFactory, + propertyNameCollectionFactory: $propertyNameCollectionFactory, + propertyMetadataFactory: $propertyMetadataFactory, + nameConverter: new CamelCaseToSnakeCaseNameConverter(), + definitionNameFactory: new DefinitionNameFactory(), + ); + + $factory = new OpenApiFactory( + $resourceNameCollectionFactory, + $resourceCollectionMetadataFactory, + $propertyNameCollectionFactory, + $propertyMetadataFactory, + $schemaFactory, + null, + [], + new Options('Test API', 'This is a test API.', '1.2.3'), + new PaginationOptions(), + $router, + ['json' => ['application/problem+json']] + ); + + return $factory->__invoke(); + } + /** * @param Parameter[] $parameters */ diff --git a/src/OpenApi/composer.json b/src/OpenApi/composer.json index 48bef8240ff..466cda2f4a0 100644 --- a/src/OpenApi/composer.json +++ b/src/OpenApi/composer.json @@ -44,6 +44,7 @@ "api-platform/doctrine-orm": "^5.0", "api-platform/doctrine-odm": "^5.0", "api-platform/serializer": "^5.0", + "symfony/routing": "^7.4 || ^8.0", "symfony/type-info": "^7.4 || ^8.0" }, "autoload": { diff --git a/src/Serializer/AbstractItemNormalizer.php b/src/Serializer/AbstractItemNormalizer.php index 85e4e0959a6..e6732c21b72 100644 --- a/src/Serializer/AbstractItemNormalizer.php +++ b/src/Serializer/AbstractItemNormalizer.php @@ -81,6 +81,8 @@ abstract class AbstractItemNormalizer extends AbstractObjectNormalizer implement public const SKIP_NULL_TO_ONE_RELATIONS = 'skip_null_to_one_relations'; private const TYPE_PROPERTY_FORMAT = 'api_type_property_format'; + public const MERGE_PATCH_MAPS = 'api_merge_patch_maps'; + protected PropertyAccessorInterface $propertyAccessor; protected array $localCache = []; protected array $localFactoryOptionsCache = []; @@ -891,6 +893,23 @@ protected function setAttributeValue(object $object, string $attribute, mixed $v return; } + if (\is_array($value) + && ($context[self::MERGE_PATCH_MAPS] ?? $this->defaultContext[self::MERGE_PATCH_MAPS] ?? false) + && ($context['api_allow_update'] ?? false) + && ($context[static::DEEP_OBJECT_TO_POPULATE] ?? $this->defaultContext[static::DEEP_OBJECT_TO_POPULATE] ?? false) + && null !== $mapType = $this->getStringKeyedMapType($this->propertyMetadataFactory->create($context['resource_class'], $attribute, $this->getFactoryOptions($context))->getNativeType()) + ) { + try { + $currentValue = $this->propertyAccessor->getValue($object, $attribute); + } catch (NoSuchPropertyException|UninitializedPropertyException) { + $currentValue = null; + } + + if (\is_array($currentValue)) { + $value = $this->mergePatchMap($currentValue, $value, $mapType->getCollectionValueType()); + } + } + // symfony/serializer only reads the current value of typed attributes (https://github.com/symfony/symfony/pull/67883), and it can't type them here if (!isset($context[static::OBJECT_TO_POPULATE]) && ($context[static::DEEP_OBJECT_TO_POPULATE] ?? $this->defaultContext[static::DEEP_OBJECT_TO_POPULATE] ?? false) @@ -914,6 +933,49 @@ protected function setAttributeValue(object $object, string $attribute, mixed $v } } + private function getStringKeyedMapType(?Type $type): ?CollectionType + { + if ($type instanceof NullableType) { + $type = $type->getWrappedType(); + } + + if (!$type instanceof CollectionType || $type->isList()) { + return null; + } + + $keyType = $type->getCollectionKeyType(); + + return $keyType instanceof BuiltinType && TypeIdentifier::STRING === $keyType->getTypeIdentifier() ? $type : null; + } + + private function mergePatchMap(array $target, array $patch, Type $valueType): array + { + $nestedMapType = $this->getStringKeyedMapType($valueType); + $isUntypedValue = $valueType instanceof BuiltinType && TypeIdentifier::MIXED === $valueType->getTypeIdentifier(); + + foreach ($patch as $key => $patchValue) { + if (null === $patchValue) { + unset($target[$key]); + continue; + } + + if (\is_array($patchValue) && $nestedMapType) { + $target[$key] = $this->mergePatchMap(\is_array($target[$key] ?? null) ? $target[$key] : [], $patchValue, $nestedMapType->getCollectionValueType()); + continue; + } + + if (\is_array($patchValue) && $isUntypedValue && !array_is_list($patchValue)) { + $currentValue = $target[$key] ?? null; + $target[$key] = $this->mergePatchMap(\is_array($currentValue) && !array_is_list($currentValue) ? $currentValue : [], $patchValue, $valueType); + continue; + } + + $target[$key] = $patchValue; + } + + return $target; + } + /** * Validates the type of the value. Allows using integers as floats for JSON formats. * diff --git a/src/State/ResourceObjectResolver.php b/src/State/ResourceObjectResolver.php new file mode 100644 index 00000000000..a097cc3d1f4 --- /dev/null +++ b/src/State/ResourceObjectResolver.php @@ -0,0 +1,67 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace ApiPlatform\State; + +use ApiPlatform\Metadata\ResourceClassResolverInterface; +use ApiPlatform\Metadata\Util\ClassInfoTrait; +use Symfony\Component\ObjectMapper\Attribute\Map; +use Symfony\Component\ObjectMapper\Metadata\ObjectMapperMetadataFactoryInterface; +use Symfony\Component\ObjectMapper\ObjectMapperInterface; + +final class ResourceObjectResolver implements ResourceObjectResolverInterface +{ + use ClassInfoTrait; + + public function __construct( + private readonly ResourceClassResolverInterface $resourceClassResolver, + private readonly ?ObjectMapperInterface $objectMapper = null, + private readonly ?ObjectMapperMetadataFactoryInterface $objectMapperMetadata = null, + ) { + } + + public function resolve(object $data): iterable + { + if ($this->resourceClassResolver->isResourceClass($class = $this->getObjectClass($data))) { + return [$data]; + } + + if (!$this->objectMapper) { + return []; + } + + if ($this->objectMapperMetadata) { + $mappings = $this->objectMapperMetadata->create($data); + + if (!$mappings) { + return []; + } + + return array_map( + fn ($mapping) => $this->objectMapper->map($data, $mapping->target), + $mappings + ); + } + + $mapAttributes = (new \ReflectionClass($class))->getAttributes(Map::class); + + if (!$mapAttributes) { + return []; + } + + return array_map( + fn ($mapAttribute) => $this->objectMapper->map($data, $mapAttribute->newInstance()->target), + $mapAttributes + ); + } +} diff --git a/src/State/ResourceObjectResolverInterface.php b/src/State/ResourceObjectResolverInterface.php new file mode 100644 index 00000000000..5ebf599c335 --- /dev/null +++ b/src/State/ResourceObjectResolverInterface.php @@ -0,0 +1,22 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace ApiPlatform\State; + +interface ResourceObjectResolverInterface +{ + /** + * @return iterable + */ + public function resolve(object $data): iterable; +} diff --git a/src/State/SerializerContextBuilderInterface.php b/src/State/SerializerContextBuilderInterface.php index ef70685347a..93c5bfd1b81 100644 --- a/src/State/SerializerContextBuilderInterface.php +++ b/src/State/SerializerContextBuilderInterface.php @@ -62,6 +62,7 @@ interface SerializerContextBuilderInterface * force_resource_class?: class-string, * api_allow_update?: bool, * deep_object_to_populate?: bool, + * api_merge_patch_maps?: bool, * collect_denormalization_errors?: bool, * exclude_from_cache_key?: string[], * api_included?: bool, diff --git a/src/State/Tests/Fixtures/Entity/MappedEntity.php b/src/State/Tests/Fixtures/Entity/MappedEntity.php new file mode 100644 index 00000000000..8c31fc1b9a1 --- /dev/null +++ b/src/State/Tests/Fixtures/Entity/MappedEntity.php @@ -0,0 +1,23 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace ApiPlatform\State\Tests\Fixtures\Entity; + +use ApiPlatform\State\Tests\Fixtures\ApiResource\Dummy; +use Symfony\Component\ObjectMapper\Attribute\Map; + +#[Map(target: Dummy::class)] +class MappedEntity +{ + public int $id = 1; +} diff --git a/src/State/Tests/ResourceObjectResolverTest.php b/src/State/Tests/ResourceObjectResolverTest.php new file mode 100644 index 00000000000..2409d4e8a78 --- /dev/null +++ b/src/State/Tests/ResourceObjectResolverTest.php @@ -0,0 +1,81 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace ApiPlatform\State\Tests; + +use ApiPlatform\Metadata\ResourceClassResolverInterface; +use ApiPlatform\State\ResourceObjectResolver; +use ApiPlatform\State\Tests\Fixtures\ApiResource\Dummy; +use ApiPlatform\State\Tests\Fixtures\Entity\MappedEntity; +use PHPUnit\Framework\TestCase; +use Symfony\Component\ObjectMapper\Metadata\Mapping; +use Symfony\Component\ObjectMapper\Metadata\ObjectMapperMetadataFactoryInterface; +use Symfony\Component\ObjectMapper\ObjectMapperInterface; + +class ResourceObjectResolverTest extends TestCase +{ + public function testResolveResourceObject(): void + { + $resourceClassResolver = $this->createMock(ResourceClassResolverInterface::class); + $resourceClassResolver->expects($this->once())->method('isResourceClass')->with(Dummy::class)->willReturn(true); + $objectMapper = $this->createMock(ObjectMapperInterface::class); + $objectMapper->expects($this->never())->method('map'); + + $dummy = new Dummy(); + $resolver = new ResourceObjectResolver($resourceClassResolver, $objectMapper); + + $this->assertSame([$dummy], iterator_to_array($resolver->resolve($dummy), false)); + } + + public function testResolveMappedObjectWithMetadataFactory(): void + { + $resourceClassResolver = $this->createStub(ResourceClassResolverInterface::class); + $resourceClassResolver->method('isResourceClass')->willReturn(false); + + $entity = new MappedEntity(); + $dummy = new Dummy(); + $objectMapper = $this->createMock(ObjectMapperInterface::class); + $objectMapper->expects($this->once())->method('map')->with($entity, Dummy::class)->willReturn($dummy); + $metadataFactory = $this->createMock(ObjectMapperMetadataFactoryInterface::class); + $metadataFactory->expects($this->once())->method('create')->with($entity)->willReturn([new Mapping(target: Dummy::class)]); + + $resolver = new ResourceObjectResolver($resourceClassResolver, $objectMapper, $metadataFactory); + + $this->assertSame([$dummy], iterator_to_array($resolver->resolve($entity), false)); + } + + public function testResolveMappedObjectWithMapAttribute(): void + { + $resourceClassResolver = $this->createStub(ResourceClassResolverInterface::class); + $resourceClassResolver->method('isResourceClass')->willReturn(false); + + $entity = new MappedEntity(); + $dummy = new Dummy(); + $objectMapper = $this->createMock(ObjectMapperInterface::class); + $objectMapper->expects($this->once())->method('map')->with($entity, Dummy::class)->willReturn($dummy); + + $resolver = new ResourceObjectResolver($resourceClassResolver, $objectMapper); + + $this->assertSame([$dummy], iterator_to_array($resolver->resolve($entity), false)); + } + + public function testResolveNonResourceWithoutObjectMapper(): void + { + $resourceClassResolver = $this->createStub(ResourceClassResolverInterface::class); + $resourceClassResolver->method('isResourceClass')->willReturn(false); + + $resolver = new ResourceObjectResolver($resourceClassResolver); + + $this->assertSame([], iterator_to_array($resolver->resolve(new MappedEntity()), false)); + } +} diff --git a/src/Symfony/Bundle/DependencyInjection/ApiPlatformExtension.php b/src/Symfony/Bundle/DependencyInjection/ApiPlatformExtension.php index c481d7a04be..302377d0f1a 100644 --- a/src/Symfony/Bundle/DependencyInjection/ApiPlatformExtension.php +++ b/src/Symfony/Bundle/DependencyInjection/ApiPlatformExtension.php @@ -1039,9 +1039,15 @@ private function registerMercureConfiguration(ContainerBuilder $container, array if ($this->isConfigEnabled($container, $config['doctrine'])) { $loader->load('doctrine_orm_mercure_publisher.php'); + if ($config['mercure']['resolve_resource_objects']) { + $container->getDefinition('api_platform.doctrine.orm.listener.mercure.publish')->setArgument('$resourceObjectResolver', new Reference('api_platform.state.resource_object_resolver')); + } } if ($this->isConfigEnabled($container, $config['doctrine_mongodb_odm'])) { $loader->load('doctrine_odm_mercure_publisher.php'); + if ($config['mercure']['resolve_resource_objects']) { + $container->getDefinition('api_platform.doctrine_mongodb.odm.listener.mercure.publish')->setArgument('$resourceObjectResolver', new Reference('api_platform.state.resource_object_resolver')); + } } if ($this->isConfigEnabled($container, $config['graphql'])) { diff --git a/src/Symfony/Bundle/DependencyInjection/Configuration.php b/src/Symfony/Bundle/DependencyInjection/Configuration.php index ae97418b16d..b2467ed72d2 100644 --- a/src/Symfony/Bundle/DependencyInjection/Configuration.php +++ b/src/Symfony/Bundle/DependencyInjection/Configuration.php @@ -454,6 +454,10 @@ private function addMercureSection(ArrayNodeDefinition $rootNode): void ->defaultFalse() ->info('Always include @type in updates (including delete ones).') ->end() + ->booleanNode('resolve_resource_objects') + ->defaultFalse() + ->info('Publish one update per resource exposing the persisted object (e.g. resources using stateOptions), resolved by api_platform.state.resource_object_resolver.') + ->end() ->end() ->end() ->end(); diff --git a/src/Symfony/Bundle/Resources/config/doctrine_orm_http_cache_purger.php b/src/Symfony/Bundle/Resources/config/doctrine_orm_http_cache_purger.php index 0f177f96b32..94e596bf35a 100644 --- a/src/Symfony/Bundle/Resources/config/doctrine_orm_http_cache_purger.php +++ b/src/Symfony/Bundle/Resources/config/doctrine_orm_http_cache_purger.php @@ -28,6 +28,7 @@ service('api_platform.object_mapper')->nullOnInvalid(), service('api_platform.object_mapper.metadata_factory')->nullOnInvalid(), service('api_platform.metadata.resource.metadata_collection_factory'), + service('api_platform.state.resource_object_resolver'), ]) ->tag('doctrine.event_listener', ['event' => 'preUpdate']) ->tag('doctrine.event_listener', ['event' => 'onFlush']) diff --git a/src/Symfony/Bundle/Resources/config/json_schema.php b/src/Symfony/Bundle/Resources/config/json_schema.php index fd1faea77e6..71b40250277 100644 --- a/src/Symfony/Bundle/Resources/config/json_schema.php +++ b/src/Symfony/Bundle/Resources/config/json_schema.php @@ -55,5 +55,6 @@ ->decorate('api_platform.json_schema.schema_factory', null, -2) ->args([service('api_platform.json_schema.backward_compatible_schema_factory.inner')]); - $services->set('api_platform.json_schema.definition_name_factory', DefinitionNameFactory::class); + $services->set('api_platform.json_schema.definition_name_factory', DefinitionNameFactory::class) + ->tag('kernel.reset', ['method' => 'reset']); }; diff --git a/src/Symfony/Bundle/Resources/config/state/state.php b/src/Symfony/Bundle/Resources/config/state/state.php index f3dd834d730..1827036cd63 100644 --- a/src/Symfony/Bundle/Resources/config/state/state.php +++ b/src/Symfony/Bundle/Resources/config/state/state.php @@ -20,6 +20,8 @@ use ApiPlatform\State\Pagination\Pagination; use ApiPlatform\State\Pagination\PaginationOptions; use ApiPlatform\State\Provider\BackedEnumProvider; +use ApiPlatform\State\ResourceObjectResolver; +use ApiPlatform\State\ResourceObjectResolverInterface; use ApiPlatform\State\SerializerContextBuilderInterface; use Symfony\Component\DependencyInjection\ServiceLocator; @@ -84,4 +86,13 @@ $services->set('api_platform.state_provider.backed_enum', BackedEnumProvider::class) ->tag('api_platform.state_provider', ['key' => 'ApiPlatform\State\Provider\BackedEnumProvider']) ->tag('api_platform.state_provider', ['key' => 'api_platform.state_provider.backed_enum']); + + $services->set('api_platform.state.resource_object_resolver', ResourceObjectResolver::class) + ->args([ + service('api_platform.resource_class_resolver'), + service('api_platform.object_mapper')->nullOnInvalid(), + service('api_platform.object_mapper.metadata_factory')->nullOnInvalid(), + ]); + + $services->alias(ResourceObjectResolverInterface::class, 'api_platform.state.resource_object_resolver'); }; diff --git a/src/Symfony/Doctrine/EventListener/PublishMercureUpdatesListener.php b/src/Symfony/Doctrine/EventListener/PublishMercureUpdatesListener.php index 71aeabc23bf..c78e6032dd2 100644 --- a/src/Symfony/Doctrine/EventListener/PublishMercureUpdatesListener.php +++ b/src/Symfony/Doctrine/EventListener/PublishMercureUpdatesListener.php @@ -26,6 +26,7 @@ use ApiPlatform\Metadata\ResourceClassResolverInterface; use ApiPlatform\Metadata\UrlGeneratorInterface; use ApiPlatform\Metadata\Util\ResourceClassInfoTrait; +use ApiPlatform\State\ResourceObjectResolverInterface; use Doctrine\Common\EventArgs; use Doctrine\ODM\MongoDB\Event\OnFlushEventArgs as MongoDbOdmOnFlushEventArgs; use Doctrine\ORM\Event\OnFlushEventArgs as OrmOnFlushEventArgs; @@ -61,6 +62,8 @@ final class PublishMercureUpdatesListener implements ResetInterface private readonly ?ExpressionLanguage $expressionLanguage; /** @var list */ private array $createdObjects; + /** @var list */ + private array $createdSources; /** @var list */ private array $updatedObjects; /** @var list */ @@ -69,7 +72,7 @@ final class PublishMercureUpdatesListener implements ResetInterface /** * @param array $formats */ - public function __construct(ResourceClassResolverInterface $resourceClassResolver, private readonly IriConverterInterface $iriConverter, ResourceMetadataCollectionFactoryInterface $resourceMetadataFactory, private readonly SerializerInterface $serializer, private readonly array $formats, ?MessageBusInterface $messageBus = null, private readonly ?HubRegistry $hubRegistry = null, private readonly ?GraphQlSubscriptionManagerInterface $graphQlSubscriptionManager = null, private readonly ?GraphQlMercureSubscriptionIriGeneratorInterface $graphQlMercureSubscriptionIriGenerator = null, ?ExpressionLanguage $expressionLanguage = null, private bool $includeType = false) + public function __construct(ResourceClassResolverInterface $resourceClassResolver, private readonly IriConverterInterface $iriConverter, ResourceMetadataCollectionFactoryInterface $resourceMetadataFactory, private readonly SerializerInterface $serializer, private readonly array $formats, ?MessageBusInterface $messageBus = null, private readonly ?HubRegistry $hubRegistry = null, private readonly ?GraphQlSubscriptionManagerInterface $graphQlSubscriptionManager = null, private readonly ?GraphQlMercureSubscriptionIriGeneratorInterface $graphQlMercureSubscriptionIriGenerator = null, ?ExpressionLanguage $expressionLanguage = null, private bool $includeType = false, private readonly ?ResourceObjectResolverInterface $resourceObjectResolver = null) { if (null === $messageBus && null === $hubRegistry) { throw new InvalidArgumentException('A message bus or a hub registry must be provided.'); @@ -131,6 +134,13 @@ public function onFlush(EventArgs $eventArgs): void public function postFlush(): void { try { + foreach ($this->createdSources as $source) { + foreach ($this->resourceObjectResolver?->resolve($source) ?? [] as $object) { + $this->storeResourceToPublish($object, 'createdObjects'); + } + } + $this->createdSources = []; + foreach ($this->createdObjects as $entry) { $this->publishUpdate($entry['object'], $entry['options'], 'create', $entry['operation']); } @@ -153,11 +163,31 @@ public function postFlush(): void public function reset(): void { $this->createdObjects = []; + $this->createdSources = []; $this->updatedObjects = []; $this->deletedObjects = []; } - private function storeObjectToPublish(object $object, string $property): void + private function storeObjectToPublish(object $source, string $property): void + { + if (!$this->resourceObjectResolver) { + $this->storeResourceToPublish($source, $property); + + return; + } + + if ('createdObjects' === $property && null === $this->getResourceClass($source)) { + $this->createdSources[] = $source; + + return; + } + + foreach ($this->resourceObjectResolver->resolve($source) as $object) { + $this->storeResourceToPublish($object, $property); + } + } + + private function storeResourceToPublish(object $object, string $property): void { if (null === $resourceClass = $this->getResourceClass($object)) { return; diff --git a/src/Symfony/Doctrine/EventListener/PurgeHttpCacheListener.php b/src/Symfony/Doctrine/EventListener/PurgeHttpCacheListener.php index 47bafd9fad9..7347e9a7c90 100644 --- a/src/Symfony/Doctrine/EventListener/PurgeHttpCacheListener.php +++ b/src/Symfony/Doctrine/EventListener/PurgeHttpCacheListener.php @@ -25,6 +25,8 @@ use ApiPlatform\Metadata\ResourceClassResolverInterface; use ApiPlatform\Metadata\UrlGeneratorInterface; use ApiPlatform\Metadata\Util\ClassInfoTrait; +use ApiPlatform\State\ResourceObjectResolver; +use ApiPlatform\State\ResourceObjectResolverInterface; use Doctrine\Common\EventArgs; use Doctrine\ODM\MongoDB\DocumentManager; use Doctrine\ODM\MongoDB\Event\OnFlushEventArgs as MongoDbOdmOnFlushEventArgs; @@ -50,6 +52,7 @@ final class PurgeHttpCacheListener implements ResetInterface { use ClassInfoTrait; private readonly PropertyAccessorInterface $propertyAccessor; + private readonly ResourceObjectResolverInterface $resourceObjectResolver; private array $tags = []; private array $scheduledInsertions = []; @@ -60,9 +63,11 @@ public function __construct(private readonly PurgerInterface $purger, ?PropertyAccessorInterface $propertyAccessor = null, private readonly ?ObjectMapperInterface $objectMapper = null, private readonly ?ObjectMapperMetadataFactoryInterface $objectMapperMetadata = null, - private readonly ?ResourceMetadataCollectionFactoryInterface $resourceMetadataCollectionFactory = null) + private readonly ?ResourceMetadataCollectionFactoryInterface $resourceMetadataCollectionFactory = null, + ?ResourceObjectResolverInterface $resourceObjectResolver = null) { $this->propertyAccessor = $propertyAccessor ?? PropertyAccess::createPropertyAccessor(); + $this->resourceObjectResolver = $resourceObjectResolver ?? new ResourceObjectResolver($resourceClassResolver, $objectMapper, $objectMapperMetadata); } /** @@ -155,16 +160,16 @@ private function gatherResourceAndItemTags(object $entity, bool $purgeItem): voi $resources = $this->getResourcesForEntity($entity); foreach ($resources as $resource) { - try { - foreach ($this->getCollectionOperations($resource) as $operation) { + foreach ($this->getCollectionOperations($resource) as $operation) { + try { $iri = $this->iriConverter->getIriFromResource($resource, UrlGeneratorInterface::ABS_PATH, $operation); $this->tags[$iri] = $iri; + } catch (OperationNotFoundException|InvalidArgumentException) { } + } - if ($purgeItem) { - $this->addTagForItem($entity); - } - } catch (OperationNotFoundException|InvalidArgumentException) { + if ($purgeItem) { + $this->addTagForItem($entity); } } } @@ -186,10 +191,6 @@ private function getCollectionOperations(object $resource): iterable continue; } - if (!empty($operation->getUriVariables())) { - continue; - } - yield $operation; } } @@ -366,44 +367,11 @@ private function addTagForItem(mixed $value): void } } - private function getResourcesForEntity(object $entity): array + /** + * @return iterable + */ + private function getResourcesForEntity(object $entity): iterable { - $resources = []; - - if (!$this->resourceClassResolver->isResourceClass($class = $this->getObjectClass($entity))) { - // is the entity mapped to resource(s)? - if (!$this->objectMapper) { - return []; - } - - if ($this->objectMapperMetadata) { - $mappings = $this->objectMapperMetadata->create($entity); - - if (!$mappings) { - return []; - } - - $resources = array_map( - fn ($mapping) => $this->objectMapper->map($entity, $mapping->target), - $mappings - ); - } else { - $mapAttributes = (new \ReflectionClass($class))->getAttributes(Map::class); - - if (!$mapAttributes) { - return []; - } - - // loop over all mappings to fetch all resources mapped to this entity - $resources = array_map( - fn ($mapAttribute) => $this->objectMapper->map($entity, $mapAttribute->newInstance()->target), - $mapAttributes - ); - } - } else { - $resources[] = $entity; - } - - return $resources; + return $this->resourceObjectResolver->resolve($entity); } } diff --git a/src/Symfony/Routing/IriConverter.php b/src/Symfony/Routing/IriConverter.php index cdc2a1b6816..bd31300beeb 100644 --- a/src/Symfony/Routing/IriConverter.php +++ b/src/Symfony/Routing/IriConverter.php @@ -104,7 +104,7 @@ public function getResourceFromIri(string $iri, array $context = [], ?Operation if (\is_string($expectedClass) && $expectedClass !== $parameters['_api_resource_class'] && class_exists($expectedClass)) { foreach ($this->resourceMetadataCollectionFactory->create($expectedClass) as $resourceMetadata) { foreach ($resourceMetadata->getOperations() ?? [] as $candidate) { - if ($candidate instanceof HttpOperation && !$candidate instanceof CollectionOperationInterface && $candidate->getRouteName() === ($parameters['_route'] ?? null)) { + if ($candidate instanceof HttpOperation && !$candidate instanceof CollectionOperationInterface && $candidate->getRouteName() === ($parameters['_route'] ?? null) && $candidate->getUriTemplate() === $routeOperation->getUriTemplate()) { $dispatchOperation = $candidate; break 2; } diff --git a/src/Symfony/Tests/Doctrine/EventListener/PurgeHttpCacheListenerTest.php b/src/Symfony/Tests/Doctrine/EventListener/PurgeHttpCacheListenerTest.php index d304aa832ea..33506d6437c 100644 --- a/src/Symfony/Tests/Doctrine/EventListener/PurgeHttpCacheListenerTest.php +++ b/src/Symfony/Tests/Doctrine/EventListener/PurgeHttpCacheListenerTest.php @@ -207,7 +207,7 @@ public function testNothingToPurge(): void $iriConverterProphecy = $this->prophesize(IriConverterInterface::class); $iriConverterProphecy->getIriFromResource(Argument::type(DummyNoGetOperation::class), UrlGeneratorInterface::ABS_PATH, new GetCollection())->willThrow(new InvalidArgumentException())->shouldBeCalled(); - $iriConverterProphecy->getIriFromResource($dummyNoGetOperation)->shouldNotBeCalled(); + $iriConverterProphecy->getIriFromResource($dummyNoGetOperation)->willThrow(new InvalidArgumentException())->shouldBeCalled(); $resourceClassResolverProphecy = $this->prophesize(ResourceClassResolverInterface::class); $resourceClassResolverProphecy->isResourceClass(DummyNoGetOperation::class)->willReturn(true)->shouldBeCalled(); @@ -424,7 +424,7 @@ static function (object $resource, int $referenceType = UrlGeneratorInterface::A $listener->postFlush(); } - public function testPreUpdateSkipsCollectionOperationsWithUriVariables(): void + public function testPreUpdatePurgesCollectionOperationsWithUriVariables(): void { $dummy = new Dummy(); $dummy->setId(1); @@ -443,16 +443,20 @@ public function testPreUpdateSkipsCollectionOperationsWithUriVariables(): void $purger->expects($this->once())->method('purge')->with($this->callback(static function (array $tags): bool { sort($tags); - return ['/dummies', '/dummies/1'] === $tags; + return ['/dummies', '/dummies/1', '/related_dummies/1/dummies'] === $tags; })); $iriConverter = $this->createMock(IriConverterInterface::class); - $iriConverter->expects($this->exactly(2))->method('getIriFromResource')->willReturnCallback( - static function (object $resource, int $referenceType = UrlGeneratorInterface::ABS_PATH, ?Operation $operation = null) use ($getCollection): string { + $iriConverter->expects($this->exactly(3))->method('getIriFromResource')->willReturnCallback( + static function (object $resource, int $referenceType = UrlGeneratorInterface::ABS_PATH, ?Operation $operation = null) use ($getCollection, $getSubresourceCollection): string { if ($operation === $getCollection) { return '/dummies'; } + if ($operation === $getSubresourceCollection) { + return '/related_dummies/1/dummies'; + } + return '/dummies/1'; } ); diff --git a/src/Symfony/Tests/Validator/Metadata/Property/Restriction/PropertySchemaCountRestrictionTest.php b/src/Symfony/Tests/Validator/Metadata/Property/Restriction/PropertySchemaCountRestrictionTest.php index 8ab006b6996..4b760178886 100644 --- a/src/Symfony/Tests/Validator/Metadata/Property/Restriction/PropertySchemaCountRestrictionTest.php +++ b/src/Symfony/Tests/Validator/Metadata/Property/Restriction/PropertySchemaCountRestrictionTest.php @@ -18,6 +18,7 @@ use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\TestCase; use Prophecy\PhpUnit\ProphecyTrait; +use Symfony\Component\TypeInfo\Type; use Symfony\Component\Validator\Constraint; use Symfony\Component\Validator\Constraints\Count; use Symfony\Component\Validator\Constraints\Positive; @@ -59,5 +60,8 @@ public static function createProvider(): \Generator yield 'min items' => [new Count(min: 1), new ApiProperty(), ['minItems' => 1]]; yield 'max items' => [new Count(max: 10), new ApiProperty(), ['maxItems' => 10]]; yield 'min/max items' => [new Count(min: 1, max: 10), new ApiProperty(), ['minItems' => 1, 'maxItems' => 10]]; + yield 'list items' => [new Count(min: 1, max: 10), (new ApiProperty())->withNativeType(Type::list(Type::string())), ['minItems' => 1, 'maxItems' => 10]]; + yield 'string-keyed map properties' => [new Count(min: 1, max: 3), (new ApiProperty())->withNativeType(Type::array(Type::mixed(), Type::string())), ['minProperties' => 1, 'maxProperties' => 3]]; + yield 'nullable string-keyed map properties' => [new Count(max: 3), (new ApiProperty())->withNativeType(Type::nullable(Type::array(Type::mixed(), Type::string()))), ['maxProperties' => 3]]; } } diff --git a/src/Symfony/Validator/Metadata/Property/Restriction/PropertySchemaCountRestriction.php b/src/Symfony/Validator/Metadata/Property/Restriction/PropertySchemaCountRestriction.php index 55c3b5183fb..5c901775c1d 100644 --- a/src/Symfony/Validator/Metadata/Property/Restriction/PropertySchemaCountRestriction.php +++ b/src/Symfony/Validator/Metadata/Property/Restriction/PropertySchemaCountRestriction.php @@ -14,6 +14,11 @@ namespace ApiPlatform\Symfony\Validator\Metadata\Property\Restriction; use ApiPlatform\Metadata\ApiProperty; +use Symfony\Component\TypeInfo\Type; +use Symfony\Component\TypeInfo\Type\BuiltinType; +use Symfony\Component\TypeInfo\Type\CollectionType; +use Symfony\Component\TypeInfo\Type\NullableType; +use Symfony\Component\TypeInfo\TypeIdentifier; use Symfony\Component\Validator\Constraint; use Symfony\Component\Validator\Constraints\Count; @@ -30,13 +35,14 @@ class PropertySchemaCountRestriction implements PropertySchemaRestrictionMetadat public function create(Constraint $constraint, ApiProperty $propertyMetadata): array { $restriction = []; + $isMap = $this->isStringKeyedMap($propertyMetadata); if (null !== $constraint->min) { - $restriction['minItems'] = $constraint->min; + $restriction[$isMap ? 'minProperties' : 'minItems'] = $constraint->min; } if (null !== $constraint->max) { - $restriction['maxItems'] = $constraint->max; + $restriction[$isMap ? 'maxProperties' : 'maxItems'] = $constraint->max; } return $restriction; @@ -49,4 +55,16 @@ public function supports(Constraint $constraint, ApiProperty $propertyMetadata): { return $constraint instanceof Count; } + + private function isStringKeyedMap(ApiProperty $propertyMetadata): bool + { + $type = $propertyMetadata->getNativeType(); + + if ($type instanceof NullableType) { + $type = $type->getWrappedType(); + } + + return $type instanceof CollectionType + && !$type->getCollectionKeyType()->isSatisfiedBy(static fn (Type $t): bool => $t instanceof BuiltinType && $t->isIdentifiedBy(TypeIdentifier::INT)); + } } diff --git a/tests/Fixtures/TestBundle/ApiResource/Settings.php b/tests/Fixtures/TestBundle/ApiResource/Settings.php new file mode 100644 index 00000000000..c829e127a9e --- /dev/null +++ b/tests/Fixtures/TestBundle/ApiResource/Settings.php @@ -0,0 +1,56 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace ApiPlatform\Tests\Fixtures\TestBundle\ApiResource; + +use ApiPlatform\Metadata\Get; +use ApiPlatform\Metadata\Operation; +use ApiPlatform\Metadata\Patch; +use Symfony\Component\Validator\Constraints as Assert; + +#[Get(uriTemplate: '/merge_patch_settings/{id}', provider: [self::class, 'provide'])] +#[Patch( + uriTemplate: '/merge_patch_settings/{id}', + denormalizationContext: ['api_merge_patch_maps' => true], + provider: [self::class, 'provide'], + processor: [self::class, 'process'], +)] +#[Patch( + uriTemplate: '/merge_patch_settings/{id}/replace', + provider: [self::class, 'provide'], + processor: [self::class, 'process'], +)] +class Settings +{ + public int $id; + + /** + * @var array + */ + #[Assert\Count(max: 3)] + public array $settings = []; + + public static function provide(Operation $operation, array $uriVariables = []): self + { + $settings = new self(); + $settings->id = (int) $uriVariables['id']; + $settings->settings = ['a' => 1, 'b' => 2, 'c' => ['e' => 2]]; + + return $settings; + } + + public static function process(mixed $data): mixed + { + return $data; + } +} diff --git a/tests/Fixtures/TestBundle/ApiResource/SharedBackingGadget.php b/tests/Fixtures/TestBundle/ApiResource/SharedBackingGadget.php new file mode 100644 index 00000000000..3d7417153ef --- /dev/null +++ b/tests/Fixtures/TestBundle/ApiResource/SharedBackingGadget.php @@ -0,0 +1,49 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace ApiPlatform\Tests\Fixtures\TestBundle\ApiResource; + +use ApiPlatform\Doctrine\Orm\State\Options; +use ApiPlatform\Metadata\ApiResource; +use ApiPlatform\Metadata\Get; +use ApiPlatform\Metadata\GetCollection; +use ApiPlatform\Metadata\Link; +use ApiPlatform\Metadata\Patch; +use ApiPlatform\Tests\Fixtures\TestBundle\Entity\SharedBackingEntity; +use Symfony\Component\ObjectMapper\Attribute\Map; + +#[ApiResource( + operations: [ + new Get(), + new Patch(), + new GetCollection(), + new GetCollection( + uriTemplate: '/shared_backing_owners/{ownerId}/gadgets', + uriVariables: ['ownerId' => new Link(fromClass: self::class, identifiers: ['ownerId'])], + ), + new GetCollection( + uriTemplate: '/shared_backing_kinds/{kind}/gadgets', + uriVariables: ['kind' => new Link(fromClass: self::class, identifiers: ['kind'])], + ), + ], + stateOptions: new Options(entityClass: SharedBackingEntity::class), +)] +#[Map(target: SharedBackingEntity::class)] +final class SharedBackingGadget +{ + public ?int $id = null; + + public string $name; + + public string $kind; +} diff --git a/tests/Fixtures/TestBundle/ApiResource/SharedBackingThing.php b/tests/Fixtures/TestBundle/ApiResource/SharedBackingThing.php new file mode 100644 index 00000000000..0f0a4e0bd79 --- /dev/null +++ b/tests/Fixtures/TestBundle/ApiResource/SharedBackingThing.php @@ -0,0 +1,38 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace ApiPlatform\Tests\Fixtures\TestBundle\ApiResource; + +use ApiPlatform\Doctrine\Orm\State\Options; +use ApiPlatform\Metadata\ApiResource; +use ApiPlatform\Metadata\Get; +use ApiPlatform\Metadata\GetCollection; +use ApiPlatform\Metadata\Patch; +use ApiPlatform\Metadata\Post; +use ApiPlatform\Tests\Fixtures\TestBundle\Entity\SharedBackingEntity; +use Symfony\Component\ObjectMapper\Attribute\Map; + +#[ApiResource( + operations: [new Get(), new Patch(), new GetCollection(), new Post()], + mercure: true, + stateOptions: new Options(entityClass: SharedBackingEntity::class), +)] +#[Map(target: SharedBackingEntity::class)] +final class SharedBackingThing +{ + public ?int $id = null; + + public string $name; + + public string $kind; +} diff --git a/tests/Fixtures/TestBundle/ApiResource/SharedRouteAlpha.php b/tests/Fixtures/TestBundle/ApiResource/SharedRouteAlpha.php new file mode 100644 index 00000000000..9805d53e174 --- /dev/null +++ b/tests/Fixtures/TestBundle/ApiResource/SharedRouteAlpha.php @@ -0,0 +1,21 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace ApiPlatform\Tests\Fixtures\TestBundle\ApiResource; + +use ApiPlatform\Metadata\Get; + +#[Get(name: 'shared_route_alpha', routeName: 'shared_static_route', uriVariables: [])] +final class SharedRouteAlpha +{ +} diff --git a/tests/Fixtures/TestBundle/ApiResource/SharedRouteBeta.php b/tests/Fixtures/TestBundle/ApiResource/SharedRouteBeta.php new file mode 100644 index 00000000000..5814573bbb8 --- /dev/null +++ b/tests/Fixtures/TestBundle/ApiResource/SharedRouteBeta.php @@ -0,0 +1,21 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace ApiPlatform\Tests\Fixtures\TestBundle\ApiResource; + +use ApiPlatform\Metadata\Get; + +#[Get(name: 'shared_route_beta', routeName: 'shared_static_route', uriVariables: [])] +final class SharedRouteBeta +{ +} diff --git a/tests/Fixtures/TestBundle/ApiResource/SharedRouteIri/VariableRouteAlpha.php b/tests/Fixtures/TestBundle/ApiResource/SharedRouteIri/VariableRouteAlpha.php new file mode 100644 index 00000000000..7cfaa9d8bbe --- /dev/null +++ b/tests/Fixtures/TestBundle/ApiResource/SharedRouteIri/VariableRouteAlpha.php @@ -0,0 +1,30 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace ApiPlatform\Tests\Fixtures\TestBundle\ApiResource\SharedRouteIri; + +use ApiPlatform\Metadata\Get; +use ApiPlatform\Metadata\Operation; + +#[Get(uriTemplate: '/shared_route_variable/alpha/{id}', name: 'shared_route_variable_alpha_get', routeName: 'shared_route_variable_item', openapi: false, provider: [self::class, 'provide'])] +final class VariableRouteAlpha +{ + public function __construct(public int $id = 0) + { + } + + public static function provide(Operation $operation, array $uriVariables = []): self + { + return new self((int) $uriVariables['id']); + } +} diff --git a/tests/Fixtures/TestBundle/ApiResource/SharedRouteIri/VariableRouteBeta.php b/tests/Fixtures/TestBundle/ApiResource/SharedRouteIri/VariableRouteBeta.php new file mode 100644 index 00000000000..6e41cfa7f11 --- /dev/null +++ b/tests/Fixtures/TestBundle/ApiResource/SharedRouteIri/VariableRouteBeta.php @@ -0,0 +1,30 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace ApiPlatform\Tests\Fixtures\TestBundle\ApiResource\SharedRouteIri; + +use ApiPlatform\Metadata\Get; +use ApiPlatform\Metadata\Operation; + +#[Get(uriTemplate: '/shared_route_variable/beta/{id}', name: 'shared_route_variable_beta_get', routeName: 'shared_route_variable_item', openapi: false, provider: [self::class, 'provide'])] +final class VariableRouteBeta +{ + public function __construct(public int $id = 0) + { + } + + public static function provide(Operation $operation, array $uriVariables = []): self + { + return new self((int) $uriVariables['id']); + } +} diff --git a/tests/Fixtures/TestBundle/Document/RuntimeResource/AttributeDefinition.php b/tests/Fixtures/TestBundle/Document/RuntimeResource/AttributeDefinition.php new file mode 100644 index 00000000000..bc89ded1188 --- /dev/null +++ b/tests/Fixtures/TestBundle/Document/RuntimeResource/AttributeDefinition.php @@ -0,0 +1,39 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace ApiPlatform\Tests\Fixtures\TestBundle\Document\RuntimeResource; + +use Doctrine\ODM\MongoDB\Mapping\Annotations as ODM; + +#[ODM\EmbeddedDocument] +class AttributeDefinition +{ + /** + * @param array $options + */ + public function __construct( + #[ODM\Field] + private string $name, + #[ODM\Field] + private string $type, + #[ODM\Field(type: 'bool')] + private bool $required = false, + #[ODM\Field(type: 'bool')] + private bool $collection = false, + #[ODM\Field(type: 'hash')] + private array $options = [], + #[ODM\Field(type: 'bool')] + private bool $filterable = false, + ) { + } +} diff --git a/tests/Fixtures/TestBundle/Document/RuntimeResource/Document.php b/tests/Fixtures/TestBundle/Document/RuntimeResource/Document.php new file mode 100644 index 00000000000..4913137861f --- /dev/null +++ b/tests/Fixtures/TestBundle/Document/RuntimeResource/Document.php @@ -0,0 +1,48 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace ApiPlatform\Tests\Fixtures\TestBundle\Document\RuntimeResource; + +use Doctrine\ODM\MongoDB\Mapping\Annotations as ODM; + +#[ODM\Document(collection: 'runtime_document')] +#[ODM\Index(keys: ['resource' => 'asc'])] +class Document +{ + #[ODM\Id(strategy: 'INCREMENT', type: 'int')] + private ?int $id = null; + + /** + * @param array $values + */ + public function __construct( + #[ODM\Field] + private string $resource, + #[ODM\Field(type: 'hash')] + private array $values = [], + ) { + } + + public function getId(): ?int + { + return $this->id; + } + + /** + * @param array $values + */ + public function setValues(array $values): void + { + $this->values = $values; + } +} diff --git a/tests/Fixtures/TestBundle/Document/RuntimeResource/Generation.php b/tests/Fixtures/TestBundle/Document/RuntimeResource/Generation.php new file mode 100644 index 00000000000..3db4044bd29 --- /dev/null +++ b/tests/Fixtures/TestBundle/Document/RuntimeResource/Generation.php @@ -0,0 +1,26 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace ApiPlatform\Tests\Fixtures\TestBundle\Document\RuntimeResource; + +use Doctrine\ODM\MongoDB\Mapping\Annotations as ODM; + +#[ODM\Document(collection: 'runtime_generation')] +class Generation +{ + #[ODM\Id(strategy: 'NONE', type: 'int')] + private int $id = 1; + + #[ODM\Field(type: 'int')] + private int $value = 0; +} diff --git a/tests/Fixtures/TestBundle/Document/RuntimeResource/ResourceDefinition.php b/tests/Fixtures/TestBundle/Document/RuntimeResource/ResourceDefinition.php new file mode 100644 index 00000000000..13057141d6a --- /dev/null +++ b/tests/Fixtures/TestBundle/Document/RuntimeResource/ResourceDefinition.php @@ -0,0 +1,51 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace ApiPlatform\Tests\Fixtures\TestBundle\Document\RuntimeResource; + +use Doctrine\Common\Collections\ArrayCollection; +use Doctrine\Common\Collections\Collection; +use Doctrine\ODM\MongoDB\Mapping\Annotations as ODM; + +#[ODM\Document(collection: 'runtime_resource_definition')] +class ResourceDefinition +{ + #[ODM\Id(strategy: 'INCREMENT', type: 'int')] + private ?int $id = null; + + /** @var Collection */ + #[ODM\EmbedMany(targetDocument: AttributeDefinition::class)] + private Collection $attributes; + + public function __construct( + #[ODM\Field] + #[ODM\UniqueIndex] + private string $name, + #[ODM\Field] + private string $label = '', + #[ODM\Field(nullable: true)] + private ?string $security = null, + ) { + $this->attributes = new ArrayCollection(); + } + + /** + * @param array $options + */ + public function addAttribute(string $name, string $type, bool $required = false, bool $collection = false, array $options = [], bool $filterable = false): self + { + $this->attributes->add(new AttributeDefinition($name, $type, $required, $collection, $options, $filterable)); + + return $this; + } +} diff --git a/tests/Fixtures/TestBundle/Entity/RuntimeResource/AttributeDefinition.php b/tests/Fixtures/TestBundle/Entity/RuntimeResource/AttributeDefinition.php new file mode 100644 index 00000000000..de2d0192059 --- /dev/null +++ b/tests/Fixtures/TestBundle/Entity/RuntimeResource/AttributeDefinition.php @@ -0,0 +1,68 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace ApiPlatform\Tests\Fixtures\TestBundle\Entity\RuntimeResource; + +use Doctrine\ORM\Mapping as ORM; + +#[ORM\Entity] +#[ORM\Table(name: 'runtime_attribute_definition')] +class AttributeDefinition +{ + #[ORM\Id] + #[ORM\GeneratedValue] + #[ORM\Column] + private ?int $id = null; + + #[ORM\Column] + private int $position; + + /** + * @param array $options + */ + public function __construct( + #[ORM\ManyToOne(inversedBy: 'attributes')] + #[ORM\JoinColumn(nullable: false, onDelete: 'CASCADE')] + private ResourceDefinition $definition, + #[ORM\Column] + private string $name, + #[ORM\Column] + private string $type, + #[ORM\Column] + private bool $required = false, + #[ORM\Column(name: 'is_collection')] + private bool $collection = false, + #[ORM\Column(type: 'json')] + private array $options = [], + #[ORM\Column] + private bool $filterable = false, + ) { + $this->position = $definition->getAttributes()->count(); + $definition->getAttributes()->add($this); + } + + public function getName(): string + { + return $this->name; + } + + public function isCollection(): bool + { + return $this->collection; + } + + public function getType(): string + { + return $this->type; + } +} diff --git a/tests/Fixtures/TestBundle/Entity/RuntimeResource/AttributeValue.php b/tests/Fixtures/TestBundle/Entity/RuntimeResource/AttributeValue.php new file mode 100644 index 00000000000..cbda472c773 --- /dev/null +++ b/tests/Fixtures/TestBundle/Entity/RuntimeResource/AttributeValue.php @@ -0,0 +1,82 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace ApiPlatform\Tests\Fixtures\TestBundle\Entity\RuntimeResource; + +use Doctrine\ORM\Mapping as ORM; + +#[ORM\Entity] +#[ORM\Table(name: 'runtime_attribute_value')] +class AttributeValue +{ + public const FIELDS = [ + 'string' => 'stringValue', + 'enum' => 'stringValue', + 'text' => 'textValue', + 'integer' => 'integerValue', + 'float' => 'floatValue', + 'boolean' => 'booleanValue', + 'datetime' => 'datetimeValue', + 'reference' => 'referenceId', + ]; + + #[ORM\Id] + #[ORM\GeneratedValue] + #[ORM\Column] + private ?int $id = null; + + #[ORM\Column(name: 'string_value', nullable: true)] + private ?string $stringValue = null; + + #[ORM\Column(name: 'text_value', type: 'text', nullable: true)] + private ?string $textValue = null; + + #[ORM\Column(name: 'integer_value', nullable: true)] + private ?int $integerValue = null; + + #[ORM\Column(name: 'float_value', nullable: true)] + private ?float $floatValue = null; + + #[ORM\Column(name: 'boolean_value', nullable: true)] + private ?bool $booleanValue = null; + + #[ORM\Column(name: 'datetime_value', nullable: true)] + private ?\DateTimeImmutable $datetimeValue = null; + + #[ORM\Column(name: 'reference_id', nullable: true)] + private ?int $referenceId = null; + + public function __construct( + #[ORM\ManyToOne(inversedBy: 'values')] + #[ORM\JoinColumn(nullable: false, onDelete: 'CASCADE')] + private EntityRow $entity, + #[ORM\ManyToOne] + #[ORM\JoinColumn(nullable: false, onDelete: 'CASCADE')] + private AttributeDefinition $attribute, + #[ORM\Column] + private int $position, + mixed $value, + ) { + $this->{self::FIELDS[$attribute->getType()]} = $value; + } + + public function getAttribute(): AttributeDefinition + { + return $this->attribute; + } + + public function getValue(): mixed + { + return $this->{self::FIELDS[$this->attribute->getType()]}; + } +} diff --git a/tests/Fixtures/TestBundle/Entity/RuntimeResource/EntityRow.php b/tests/Fixtures/TestBundle/Entity/RuntimeResource/EntityRow.php new file mode 100644 index 00000000000..3dd6a666d1c --- /dev/null +++ b/tests/Fixtures/TestBundle/Entity/RuntimeResource/EntityRow.php @@ -0,0 +1,70 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace ApiPlatform\Tests\Fixtures\TestBundle\Entity\RuntimeResource; + +use Doctrine\Common\Collections\ArrayCollection; +use Doctrine\Common\Collections\Collection; +use Doctrine\ORM\Mapping as ORM; + +#[ORM\Entity] +#[ORM\Table(name: 'runtime_entity_row')] +class EntityRow +{ + #[ORM\Id] + #[ORM\GeneratedValue] + #[ORM\Column] + private ?int $id = null; + + /** @var Collection */ + #[ORM\OneToMany(targetEntity: AttributeValue::class, mappedBy: 'entity', cascade: ['persist'], orphanRemoval: true)] + #[ORM\OrderBy(['position' => 'ASC'])] + private Collection $values; + + public function __construct( + #[ORM\ManyToOne] + #[ORM\JoinColumn(nullable: false, onDelete: 'CASCADE')] + private ResourceDefinition $definition, + ) { + $this->values = new ArrayCollection(); + } + + public function getId(): ?int + { + return $this->id; + } + + /** + * @return Collection + */ + public function getValues(): Collection + { + return $this->values; + } + + /** + * @param array $values + */ + public function replaceValues(array $values): void + { + $this->values->clear(); + foreach ($this->definition->getAttributes() as $attribute) { + $value = $values[$attribute->getName()] ?? null; + foreach ($attribute->isCollection() ? (array) $value : [$value] as $position => $item) { + if (null !== $item) { + $this->values->add(new AttributeValue($this, $attribute, $position, $item)); + } + } + } + } +} diff --git a/tests/Fixtures/TestBundle/Entity/RuntimeResource/Generation.php b/tests/Fixtures/TestBundle/Entity/RuntimeResource/Generation.php new file mode 100644 index 00000000000..1008bb3eb27 --- /dev/null +++ b/tests/Fixtures/TestBundle/Entity/RuntimeResource/Generation.php @@ -0,0 +1,28 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace ApiPlatform\Tests\Fixtures\TestBundle\Entity\RuntimeResource; + +use Doctrine\ORM\Mapping as ORM; + +#[ORM\Entity] +#[ORM\Table(name: 'runtime_generation')] +class Generation +{ + #[ORM\Id] + #[ORM\Column] + private int $id = 1; + + #[ORM\Column] + private int $value = 0; +} diff --git a/tests/Fixtures/TestBundle/Entity/RuntimeResource/ResourceDefinition.php b/tests/Fixtures/TestBundle/Entity/RuntimeResource/ResourceDefinition.php new file mode 100644 index 00000000000..f2ed536921c --- /dev/null +++ b/tests/Fixtures/TestBundle/Entity/RuntimeResource/ResourceDefinition.php @@ -0,0 +1,62 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace ApiPlatform\Tests\Fixtures\TestBundle\Entity\RuntimeResource; + +use Doctrine\Common\Collections\ArrayCollection; +use Doctrine\Common\Collections\Collection; +use Doctrine\ORM\Mapping as ORM; + +#[ORM\Entity] +#[ORM\Table(name: 'runtime_resource_definition')] +class ResourceDefinition +{ + #[ORM\Id] + #[ORM\GeneratedValue] + #[ORM\Column] + private ?int $id = null; + + /** @var Collection */ + #[ORM\OneToMany(targetEntity: AttributeDefinition::class, mappedBy: 'definition', cascade: ['persist'])] + #[ORM\OrderBy(['position' => 'ASC'])] + private Collection $attributes; + + public function __construct( + #[ORM\Column(unique: true)] + private string $name, + #[ORM\Column] + private string $label = '', + #[ORM\Column(nullable: true)] + private ?string $security = null, + ) { + $this->attributes = new ArrayCollection(); + } + + public function getId(): ?int + { + return $this->id; + } + + public function getName(): string + { + return $this->name; + } + + /** + * @return Collection + */ + public function getAttributes(): Collection + { + return $this->attributes; + } +} diff --git a/tests/Fixtures/TestBundle/Entity/SharedBackingEntity.php b/tests/Fixtures/TestBundle/Entity/SharedBackingEntity.php new file mode 100644 index 00000000000..8b55d5bd579 --- /dev/null +++ b/tests/Fixtures/TestBundle/Entity/SharedBackingEntity.php @@ -0,0 +1,31 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace ApiPlatform\Tests\Fixtures\TestBundle\Entity; + +use Doctrine\ORM\Mapping as ORM; + +#[ORM\Entity] +class SharedBackingEntity +{ + #[ORM\Id] + #[ORM\GeneratedValue] + #[ORM\Column(type: 'integer')] + public ?int $id = null; + + #[ORM\Column] + public string $kind; + + #[ORM\Column] + public string $name; +} diff --git a/tests/Fixtures/TestBundle/RuntimeResource/Attribute.php b/tests/Fixtures/TestBundle/RuntimeResource/Attribute.php new file mode 100644 index 00000000000..8b924a669ce --- /dev/null +++ b/tests/Fixtures/TestBundle/RuntimeResource/Attribute.php @@ -0,0 +1,35 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace ApiPlatform\Tests\Fixtures\TestBundle\RuntimeResource; + +final readonly class Attribute +{ + /** + * @param array $options + */ + public function __construct( + public string $name, + public AttributeType $type, + public bool $required = false, + public bool $collection = false, + public array $options = [], + public bool $filterable = false, + ) { + } + + public function target(): ?string + { + return AttributeType::Reference === $this->type ? (string) ($this->options['target'] ?? '') : null; + } +} diff --git a/tests/Fixtures/TestBundle/RuntimeResource/AttributeType.php b/tests/Fixtures/TestBundle/RuntimeResource/AttributeType.php new file mode 100644 index 00000000000..acd62f4a3a8 --- /dev/null +++ b/tests/Fixtures/TestBundle/RuntimeResource/AttributeType.php @@ -0,0 +1,26 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace ApiPlatform\Tests\Fixtures\TestBundle\RuntimeResource; + +enum AttributeType: string +{ + case String = 'string'; + case Text = 'text'; + case Integer = 'integer'; + case Float = 'float'; + case Boolean = 'boolean'; + case Datetime = 'datetime'; + case Enum = 'enum'; + case Reference = 'reference'; +} diff --git a/tests/Fixtures/TestBundle/RuntimeResource/Definition.php b/tests/Fixtures/TestBundle/RuntimeResource/Definition.php new file mode 100644 index 00000000000..0f4c0346245 --- /dev/null +++ b/tests/Fixtures/TestBundle/RuntimeResource/Definition.php @@ -0,0 +1,28 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace ApiPlatform\Tests\Fixtures\TestBundle\RuntimeResource; + +final readonly class Definition +{ + /** + * @param array $attributes + */ + public function __construct( + public string $name, + public string $label = '', + public ?string $security = null, + public array $attributes = [], + ) { + } +} diff --git a/tests/Fixtures/TestBundle/RuntimeResource/DefinitionProvider.php b/tests/Fixtures/TestBundle/RuntimeResource/DefinitionProvider.php new file mode 100644 index 00000000000..9d2bddc74d8 --- /dev/null +++ b/tests/Fixtures/TestBundle/RuntimeResource/DefinitionProvider.php @@ -0,0 +1,29 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace ApiPlatform\Tests\Fixtures\TestBundle\RuntimeResource; + +interface DefinitionProvider +{ + /** + * @return iterable + */ + public function definitions(): iterable; + + public function generation(): int; + + /** + * Applies the definition changes and bumps the generation in the same write. + */ + public function publish(?callable $changes = null): int; +} diff --git a/tests/Fixtures/TestBundle/RuntimeResource/Odm/DocumentFilter.php b/tests/Fixtures/TestBundle/RuntimeResource/Odm/DocumentFilter.php new file mode 100644 index 00000000000..f94c11e5bf6 --- /dev/null +++ b/tests/Fixtures/TestBundle/RuntimeResource/Odm/DocumentFilter.php @@ -0,0 +1,46 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace ApiPlatform\Tests\Fixtures\TestBundle\RuntimeResource\Odm; + +use ApiPlatform\Doctrine\Odm\Filter\FilterInterface; +use ApiPlatform\Metadata\IriConverterInterface; +use ApiPlatform\Metadata\Operation; +use ApiPlatform\Tests\Fixtures\TestBundle\RuntimeResource\RuntimeMapper; +use ApiPlatform\Tests\Fixtures\TestBundle\RuntimeResource\RuntimeResources; +use Doctrine\ODM\MongoDB\Aggregation\Builder; +use MongoDB\BSON\UTCDateTime; + +final class DocumentFilter implements FilterInterface +{ + public function __construct( + private readonly RuntimeResources $resources, + private readonly IriConverterInterface $iriConverter, + ) { + } + + public function apply(Builder $aggregationBuilder, string $resourceClass, ?Operation $operation = null, array &$context = []): void + { + $parameter = $context['parameter']; + $attribute = $this->resources->get((string) $operation?->getClass())->attributes[$parameter->getProperty()] ?? null; + $value = null === $attribute ? null : RuntimeMapper::filterValue($attribute, $parameter->getValue(), $this->iriConverter); + $match = $aggregationBuilder->match()->field('values.'.$parameter->getProperty()); + + null === $value ? $match->in([]) : $match->equals($value instanceof \DateTimeInterface ? new UTCDateTime($value->getTimestamp() * 1000 + (int) $value->format('v')) : $value); + } + + public function getDescription(string $resourceClass): array + { + return []; + } +} diff --git a/tests/Fixtures/TestBundle/RuntimeResource/Odm/DocumentProcessor.php b/tests/Fixtures/TestBundle/RuntimeResource/Odm/DocumentProcessor.php new file mode 100644 index 00000000000..c32df9aabe2 --- /dev/null +++ b/tests/Fixtures/TestBundle/RuntimeResource/Odm/DocumentProcessor.php @@ -0,0 +1,64 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace ApiPlatform\Tests\Fixtures\TestBundle\RuntimeResource\Odm; + +use ApiPlatform\Metadata\DeleteOperationInterface; +use ApiPlatform\Metadata\Operation; +use ApiPlatform\Metadata\Post; +use ApiPlatform\State\ProcessorInterface; +use ApiPlatform\Tests\Fixtures\TestBundle\Document\RuntimeResource\Document; +use ApiPlatform\Tests\Fixtures\TestBundle\RuntimeResource\RuntimeMapper; +use ApiPlatform\Tests\Fixtures\TestBundle\RuntimeResource\RuntimeObject; +use ApiPlatform\Tests\Fixtures\TestBundle\RuntimeResource\RuntimeResources; +use Doctrine\ODM\MongoDB\DocumentManager; +use Doctrine\Persistence\ManagerRegistry; +use MongoDB\BSON\UTCDateTime; +use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; + +/** + * @implements ProcessorInterface + */ +final class DocumentProcessor implements ProcessorInterface +{ + public function __construct( + private readonly ManagerRegistry $registry, + private readonly RuntimeMapper $mapper, + private readonly DocumentProvider $provider, + ) { + } + + public function process(mixed $data, Operation $operation, array $uriVariables = [], array $context = []): ?RuntimeObject + { + $manager = $this->registry->getManagerForClass(Document::class); + \assert($manager instanceof DocumentManager && $data instanceof RuntimeObject); + + $name = (string) RuntimeResources::nameOf($data::class); + $document = $operation instanceof Post + ? new Document($name) + : $manager->getRepository(Document::class)->findOneBy(['id' => (int) ($uriVariables['id'] ?? 0), 'resource' => $name]) ?? throw new NotFoundHttpException(); + + if ($operation instanceof DeleteOperationInterface) { + $manager->remove($document); + $manager->flush(); + + return null; + } + + $document->setValues(array_map(static fn (mixed $value): mixed => $value instanceof \DateTimeInterface ? new UTCDateTime($value->getTimestamp() * 1000 + (int) $value->format('v')) : $value, $this->mapper->extract($data))); + $manager->persist($document); + $manager->flush(); + + return $this->provider->find($name, (int) $document->getId()); + } +} diff --git a/tests/Fixtures/TestBundle/RuntimeResource/Odm/DocumentProvider.php b/tests/Fixtures/TestBundle/RuntimeResource/Odm/DocumentProvider.php new file mode 100644 index 00000000000..9b89899d122 --- /dev/null +++ b/tests/Fixtures/TestBundle/RuntimeResource/Odm/DocumentProvider.php @@ -0,0 +1,95 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace ApiPlatform\Tests\Fixtures\TestBundle\RuntimeResource\Odm; + +use ApiPlatform\Doctrine\Odm\State\Options; +use ApiPlatform\Metadata\CollectionOperationInterface; +use ApiPlatform\Metadata\Operation; +use ApiPlatform\State\Pagination\PaginatorInterface; +use ApiPlatform\State\Pagination\TraversablePaginator; +use ApiPlatform\State\ProviderInterface; +use ApiPlatform\Tests\Fixtures\TestBundle\Document\RuntimeResource\Document; +use ApiPlatform\Tests\Fixtures\TestBundle\RuntimeResource\RuntimeMapper; +use ApiPlatform\Tests\Fixtures\TestBundle\RuntimeResource\RuntimeObject; +use ApiPlatform\Tests\Fixtures\TestBundle\RuntimeResource\RuntimeResources; +use Doctrine\ODM\MongoDB\Aggregation\Builder; +use Doctrine\ODM\MongoDB\DocumentManager; +use Doctrine\Persistence\ManagerRegistry; +use MongoDB\BSON\UTCDateTime; + +final class DocumentProvider implements ProviderInterface +{ + public function __construct( + private readonly ProviderInterface $itemProvider, + private readonly ProviderInterface $collectionProvider, + private readonly ManagerRegistry $registry, + private readonly RuntimeMapper $mapper, + ) { + } + + public function provide(Operation $operation, array $uriVariables = [], array $context = []): object|array|null + { + $name = RuntimeResources::nameOf((string) $operation->getClass()); + if (null === $name) { + return null; + } + + $operation = $operation->withStateOptions(new Options(documentClass: Document::class, handleLinks: [self::class, 'handleLinks'])); + if (!$operation instanceof CollectionOperationInterface) { + $document = $this->itemProvider->provide($operation, $uriVariables, $context); + + return $document instanceof Document ? $this->find($name, (int) $document->getId()) : null; + } + + $documents = $this->collectionProvider->provide($operation, $uriVariables, $context); + $objects = $this->mapper->hydrate($name, array_map(static fn (Document $document): int => (int) $document->getId(), iterator_to_array($documents, false)), $this->load(...)); + + return $documents instanceof PaginatorInterface ? new TraversablePaginator(new \ArrayIterator($objects), $documents->getCurrentPage(), $documents->getItemsPerPage(), $documents->getTotalItems()) : $objects; + } + + /** + * @param array $uriVariables + * @param array $context + */ + public static function handleLinks(Builder $aggregationBuilder, array $uriVariables, array $context): void + { + $aggregationBuilder->match()->field('resource')->equals(RuntimeResources::nameOf((string) $context['operation']->getClass())); + if (isset($uriVariables['id'])) { + $aggregationBuilder->match()->field('id')->equals((int) $uriVariables['id']); + } + } + + public function find(string $name, int $id): ?RuntimeObject + { + return $this->mapper->hydrate($name, [$id], $this->load(...))[0] ?? null; + } + + /** + * @param list $ids + * + * @return array> + */ + private function load(string $name, array $ids): array + { + $manager = $this->registry->getManagerForClass(Document::class); + \assert($manager instanceof DocumentManager); + + $values = []; + foreach ($manager->getDocumentCollection(Document::class)->find(['resource' => $name, '_id' => ['$in' => $ids]], ['typeMap' => ['root' => 'array', 'document' => 'array', 'array' => 'array']]) as $row) { + $values[$row['_id']] = array_map(static fn (mixed $value): mixed => $value instanceof UTCDateTime ? \DateTimeImmutable::createFromInterface($value->toDateTime()) : $value, $row['values'] ?? []); + } + + return $values; + } +} diff --git a/tests/Fixtures/TestBundle/RuntimeResource/Odm/OdmDefinitionProvider.php b/tests/Fixtures/TestBundle/RuntimeResource/Odm/OdmDefinitionProvider.php new file mode 100644 index 00000000000..5ee213bf97e --- /dev/null +++ b/tests/Fixtures/TestBundle/RuntimeResource/Odm/OdmDefinitionProvider.php @@ -0,0 +1,69 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace ApiPlatform\Tests\Fixtures\TestBundle\RuntimeResource\Odm; + +use ApiPlatform\Tests\Fixtures\TestBundle\Document\RuntimeResource\Generation; +use ApiPlatform\Tests\Fixtures\TestBundle\Document\RuntimeResource\ResourceDefinition; +use ApiPlatform\Tests\Fixtures\TestBundle\RuntimeResource\Attribute; +use ApiPlatform\Tests\Fixtures\TestBundle\RuntimeResource\AttributeType; +use ApiPlatform\Tests\Fixtures\TestBundle\RuntimeResource\Definition; +use ApiPlatform\Tests\Fixtures\TestBundle\RuntimeResource\DefinitionProvider; +use Doctrine\ODM\MongoDB\DocumentManager; +use Doctrine\Persistence\ManagerRegistry; +use MongoDB\Operation\FindOneAndUpdate; + +final class OdmDefinitionProvider implements DefinitionProvider +{ + public function __construct(private readonly ManagerRegistry $registry) + { + } + + public function definitions(): iterable + { + foreach ($this->manager()->getDocumentCollection(ResourceDefinition::class)->find([], ['sort' => ['_id' => 1], 'typeMap' => ['root' => 'array', 'document' => 'array', 'array' => 'array']]) as $row) { + $attributes = []; + foreach ($row['attributes'] ?? [] as $attribute) { + if (null !== $type = AttributeType::tryFrom($attribute['type'])) { + $attributes[$attribute['name']] = new Attribute($attribute['name'], $type, $attribute['required'], $attribute['collection'], $attribute['options'] ?? [], $attribute['filterable']); + } + } + + yield new Definition($row['name'], $row['label'], $row['security'] ?? null, $attributes); + } + } + + public function generation(): int + { + return (int) ($this->manager()->getDocumentCollection(Generation::class)->findOne(['_id' => 1])['value'] ?? 0); + } + + public function publish(?callable $changes = null): int + { + $manager = $this->manager(); + if (null !== $changes) { + $changes($manager); + $manager->flush(); + } + + return (int) $manager->getDocumentCollection(Generation::class)->findOneAndUpdate(['_id' => 1], ['$inc' => ['value' => 1]], ['upsert' => true, 'returnDocument' => FindOneAndUpdate::RETURN_DOCUMENT_AFTER])['value']; + } + + private function manager(): DocumentManager + { + $manager = $this->registry->getManagerForClass(Generation::class); + \assert($manager instanceof DocumentManager); + + return $manager; + } +} diff --git a/tests/Fixtures/TestBundle/RuntimeResource/Orm/EavFilter.php b/tests/Fixtures/TestBundle/RuntimeResource/Orm/EavFilter.php new file mode 100644 index 00000000000..f64a1f39bb3 --- /dev/null +++ b/tests/Fixtures/TestBundle/RuntimeResource/Orm/EavFilter.php @@ -0,0 +1,56 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace ApiPlatform\Tests\Fixtures\TestBundle\RuntimeResource\Orm; + +use ApiPlatform\Doctrine\Orm\Filter\FilterInterface; +use ApiPlatform\Doctrine\Orm\Util\QueryNameGeneratorInterface; +use ApiPlatform\Metadata\IriConverterInterface; +use ApiPlatform\Metadata\Operation; +use ApiPlatform\Tests\Fixtures\TestBundle\Entity\RuntimeResource\AttributeValue; +use ApiPlatform\Tests\Fixtures\TestBundle\RuntimeResource\RuntimeMapper; +use ApiPlatform\Tests\Fixtures\TestBundle\RuntimeResource\RuntimeResources; +use Doctrine\ORM\QueryBuilder; + +final class EavFilter implements FilterInterface +{ + public function __construct( + private readonly RuntimeResources $resources, + private readonly IriConverterInterface $iriConverter, + ) { + } + + public function apply(QueryBuilder $queryBuilder, QueryNameGeneratorInterface $queryNameGenerator, string $resourceClass, ?Operation $operation = null, array $context = []): void + { + $parameter = $context['parameter']; + $attribute = $this->resources->get((string) $operation?->getClass())->attributes[$parameter->getProperty()] ?? null; + $value = null === $attribute ? null : RuntimeMapper::filterValue($attribute, $parameter->getValue(), $this->iriConverter); + if (null === $value) { + $queryBuilder->andWhere('1 = 0'); + + return; + } + + [$v, $a] = [$queryNameGenerator->generateJoinAlias('value'), $queryNameGenerator->generateJoinAlias('attribute')]; + [$name, $expected] = [$queryNameGenerator->generateParameterName('attribute'), $queryNameGenerator->generateParameterName('value')]; + $queryBuilder + ->andWhere(\sprintf('EXISTS (SELECT %1$s FROM %3$s %1$s JOIN %1$s.attribute %2$s WHERE %1$s.entity = %4$s AND %2$s.name = :%5$s AND %1$s.%6$s = :%7$s)', $v, $a, AttributeValue::class, $queryBuilder->getRootAliases()[0], $name, AttributeValue::FIELDS[$attribute->type->value], $expected)) + ->setParameter($name, $attribute->name) + ->setParameter($expected, $value); + } + + public function getDescription(string $resourceClass): array + { + return []; + } +} diff --git a/tests/Fixtures/TestBundle/RuntimeResource/Orm/EavProcessor.php b/tests/Fixtures/TestBundle/RuntimeResource/Orm/EavProcessor.php new file mode 100644 index 00000000000..a2dcb8a853a --- /dev/null +++ b/tests/Fixtures/TestBundle/RuntimeResource/Orm/EavProcessor.php @@ -0,0 +1,64 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace ApiPlatform\Tests\Fixtures\TestBundle\RuntimeResource\Orm; + +use ApiPlatform\Metadata\DeleteOperationInterface; +use ApiPlatform\Metadata\Operation; +use ApiPlatform\Metadata\Post; +use ApiPlatform\State\ProcessorInterface; +use ApiPlatform\Tests\Fixtures\TestBundle\Entity\RuntimeResource\EntityRow; +use ApiPlatform\Tests\Fixtures\TestBundle\Entity\RuntimeResource\ResourceDefinition; +use ApiPlatform\Tests\Fixtures\TestBundle\RuntimeResource\RuntimeMapper; +use ApiPlatform\Tests\Fixtures\TestBundle\RuntimeResource\RuntimeObject; +use ApiPlatform\Tests\Fixtures\TestBundle\RuntimeResource\RuntimeResources; +use Doctrine\ORM\EntityManagerInterface; +use Doctrine\Persistence\ManagerRegistry; +use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; + +/** + * @implements ProcessorInterface + */ +final class EavProcessor implements ProcessorInterface +{ + public function __construct( + private readonly ManagerRegistry $registry, + private readonly RuntimeMapper $mapper, + private readonly EavProvider $provider, + ) { + } + + public function process(mixed $data, Operation $operation, array $uriVariables = [], array $context = []): ?RuntimeObject + { + $manager = $this->registry->getManagerForClass(EntityRow::class); + \assert($manager instanceof EntityManagerInterface && $data instanceof RuntimeObject); + + $definition = $manager->getRepository(ResourceDefinition::class)->findOneBy(['name' => RuntimeResources::nameOf($data::class)]); + $row = $operation instanceof Post + ? new EntityRow($definition) + : $manager->getRepository(EntityRow::class)->findOneBy(['id' => $uriVariables['id'] ?? null, 'definition' => $definition]) ?? throw new NotFoundHttpException(); + + if ($operation instanceof DeleteOperationInterface) { + $manager->remove($row); + $manager->flush(); + + return null; + } + + $row->replaceValues($this->mapper->extract($data)); + $manager->persist($row); + $manager->flush(); + + return $this->provider->find(RuntimeResources::nameOf($data::class), (int) $row->getId()); + } +} diff --git a/tests/Fixtures/TestBundle/RuntimeResource/Orm/EavProvider.php b/tests/Fixtures/TestBundle/RuntimeResource/Orm/EavProvider.php new file mode 100644 index 00000000000..99521e11385 --- /dev/null +++ b/tests/Fixtures/TestBundle/RuntimeResource/Orm/EavProvider.php @@ -0,0 +1,121 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace ApiPlatform\Tests\Fixtures\TestBundle\RuntimeResource\Orm; + +use ApiPlatform\Doctrine\Orm\State\Options; +use ApiPlatform\Doctrine\Orm\Util\QueryNameGeneratorInterface; +use ApiPlatform\Metadata\CollectionOperationInterface; +use ApiPlatform\Metadata\Operation; +use ApiPlatform\State\Pagination\PaginatorInterface; +use ApiPlatform\State\Pagination\TraversablePaginator; +use ApiPlatform\State\ProviderInterface; +use ApiPlatform\Tests\Fixtures\TestBundle\Entity\RuntimeResource\EntityRow; +use ApiPlatform\Tests\Fixtures\TestBundle\RuntimeResource\RuntimeMapper; +use ApiPlatform\Tests\Fixtures\TestBundle\RuntimeResource\RuntimeObject; +use ApiPlatform\Tests\Fixtures\TestBundle\RuntimeResource\RuntimeResources; +use Doctrine\ORM\EntityManagerInterface; +use Doctrine\ORM\QueryBuilder; +use Doctrine\Persistence\ManagerRegistry; + +final class EavProvider implements ProviderInterface +{ + public function __construct( + private readonly ProviderInterface $itemProvider, + private readonly ProviderInterface $collectionProvider, + private readonly ManagerRegistry $registry, + private readonly RuntimeMapper $mapper, + ) { + } + + public function provide(Operation $operation, array $uriVariables = [], array $context = []): object|array|null + { + $name = RuntimeResources::nameOf((string) $operation->getClass()); + if (null === $name) { + return null; + } + + $operation = $operation->withStateOptions(new Options(entityClass: EntityRow::class, handleLinks: [self::class, 'handleLinks'])); + if (!$operation instanceof CollectionOperationInterface) { + $row = $this->itemProvider->provide($operation, $uriVariables, $context); + + return $row instanceof EntityRow ? $this->find($name, (int) $row->getId()) : null; + } + + $rows = $this->collectionProvider->provide($operation, $uriVariables, $context); + $objects = $this->mapper->hydrate($name, array_map(static fn (EntityRow $row): int => (int) $row->getId(), iterator_to_array($rows, false)), $this->load(...)); + + return $rows instanceof PaginatorInterface ? new TraversablePaginator(new \ArrayIterator($objects), $rows->getCurrentPage(), $rows->getItemsPerPage(), $rows->getTotalItems()) : $objects; + } + + /** + * @param array $uriVariables + * @param array $context + */ + public static function handleLinks(QueryBuilder $queryBuilder, array $uriVariables, QueryNameGeneratorInterface $queryNameGenerator, array $context): void + { + $alias = $queryBuilder->getRootAliases()[0]; + $definition = $queryNameGenerator->generateJoinAlias('definition'); + $name = $queryNameGenerator->generateParameterName('resource'); + $queryBuilder->innerJoin("$alias.definition", $definition)->andWhere("$definition.name = :$name")->setParameter($name, RuntimeResources::nameOf((string) $context['operation']->getClass())); + + if (isset($uriVariables['id'])) { + $id = $queryNameGenerator->generateParameterName('id'); + $queryBuilder->andWhere("$alias.id = :$id")->setParameter($id, $uriVariables['id']); + } + } + + public function find(string $name, int $id): ?RuntimeObject + { + return $this->mapper->hydrate($name, [$id], $this->load(...))[0] ?? null; + } + + /** + * @param list $ids + * + * @return array> + */ + private function load(string $name, array $ids): array + { + $manager = $this->registry->getManagerForClass(EntityRow::class); + \assert($manager instanceof EntityManagerInterface); + + $rows = $manager->createQueryBuilder() + ->select('r', 'v', 'a') + ->from(EntityRow::class, 'r') + ->innerJoin('r.definition', 'd') + ->leftJoin('r.values', 'v') + ->leftJoin('v.attribute', 'a') + ->where('d.name = :name AND r.id IN (:ids)') + ->orderBy('v.position') + ->setParameter('name', $name) + ->setParameter('ids', $ids) + ->getQuery() + ->getResult(); + + $values = []; + foreach ($rows as $row) { + $values[$row->getId()] = []; + foreach ($row->getValues() as $value) { + $attribute = $value->getAttribute(); + if ($attribute->isCollection()) { + $values[$row->getId()][$attribute->getName()][] = $value->getValue(); + } else { + $values[$row->getId()][$attribute->getName()] = $value->getValue(); + } + } + } + + return $values; + } +} diff --git a/tests/Fixtures/TestBundle/RuntimeResource/Orm/OrmDefinitionProvider.php b/tests/Fixtures/TestBundle/RuntimeResource/Orm/OrmDefinitionProvider.php new file mode 100644 index 00000000000..2b3724a5b11 --- /dev/null +++ b/tests/Fixtures/TestBundle/RuntimeResource/Orm/OrmDefinitionProvider.php @@ -0,0 +1,85 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace ApiPlatform\Tests\Fixtures\TestBundle\RuntimeResource\Orm; + +use ApiPlatform\Tests\Fixtures\TestBundle\Entity\RuntimeResource\Generation; +use ApiPlatform\Tests\Fixtures\TestBundle\Entity\RuntimeResource\ResourceDefinition; +use ApiPlatform\Tests\Fixtures\TestBundle\RuntimeResource\Attribute; +use ApiPlatform\Tests\Fixtures\TestBundle\RuntimeResource\AttributeType; +use ApiPlatform\Tests\Fixtures\TestBundle\RuntimeResource\Definition; +use ApiPlatform\Tests\Fixtures\TestBundle\RuntimeResource\DefinitionProvider; +use Doctrine\DBAL\Exception\TableNotFoundException; +use Doctrine\ORM\EntityManagerInterface; +use Doctrine\Persistence\ManagerRegistry; + +final class OrmDefinitionProvider implements DefinitionProvider +{ + public function __construct(private readonly ManagerRegistry $registry) + { + } + + public function definitions(): iterable + { + try { + $rows = $this->manager()->createQuery(\sprintf('SELECT d, a FROM %s d LEFT JOIN d.attributes a ORDER BY d.id, a.position', ResourceDefinition::class))->getArrayResult(); + } catch (TableNotFoundException) { + return; + } + + foreach ($rows as $row) { + $attributes = []; + foreach ($row['attributes'] as $attribute) { + if (null !== $type = AttributeType::tryFrom($attribute['type'])) { + $attributes[$attribute['name']] = new Attribute($attribute['name'], $type, $attribute['required'], $attribute['collection'], $attribute['options'], $attribute['filterable']); + } + } + + yield new Definition($row['name'], $row['label'], $row['security'], $attributes); + } + } + + public function generation(): int + { + try { + return (int) $this->manager()->getConnection()->fetchOne('SELECT value FROM runtime_generation WHERE id = 1'); + } catch (TableNotFoundException) { + return 0; + } + } + + public function publish(?callable $changes = null): int + { + return $this->manager()->wrapInTransaction(static function (EntityManagerInterface $manager) use ($changes): int { + if (null !== $changes) { + $changes($manager); + $manager->flush(); + } + + $connection = $manager->getConnection(); + if (0 === $connection->executeStatement('UPDATE runtime_generation SET value = value + 1 WHERE id = 1')) { + $connection->insert('runtime_generation', ['id' => 1, 'value' => 1]); + } + + return (int) $connection->fetchOne('SELECT value FROM runtime_generation WHERE id = 1'); + }); + } + + private function manager(): EntityManagerInterface + { + $manager = $this->registry->getManagerForClass(Generation::class); + \assert($manager instanceof EntityManagerInterface); + + return $manager; + } +} diff --git a/tests/Fixtures/TestBundle/RuntimeResource/RuntimeMapper.php b/tests/Fixtures/TestBundle/RuntimeResource/RuntimeMapper.php new file mode 100644 index 00000000000..1769e6caddc --- /dev/null +++ b/tests/Fixtures/TestBundle/RuntimeResource/RuntimeMapper.php @@ -0,0 +1,131 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace ApiPlatform\Tests\Fixtures\TestBundle\RuntimeResource; + +use ApiPlatform\Metadata\Exception\ExceptionInterface; +use ApiPlatform\Metadata\IriConverterInterface; + +final class RuntimeMapper +{ + public function __construct(private readonly RuntimeResources $resources) + { + } + + /** + * @param list $ids + * @param \Closure(string, list): iterable> $load raw values by id, references as ids + * + * @return list + */ + public function hydrate(string $name, array $ids, \Closure $load): array + { + $rows = $attempted = []; + $pending = [$name => array_fill_keys($ids, true)]; + for ($depth = 0; $depth < 2 && [] !== $pending; ++$depth) { + $next = []; + foreach ($pending as $resource => $resourceIds) { + $attempted[$resource] = ($attempted[$resource] ?? []) + $resourceIds; + foreach ($load($resource, array_keys($resourceIds)) as $id => $values) { + $rows[$resource][$id] = $values; + foreach ($this->references($resource, $values) as [$target, $targetId]) { + if (!isset($attempted[$target][$targetId])) { + $next[$target][$targetId] = true; + } + } + } + } + $pending = $next; + } + + $objects = []; + $object = function (string $resource, int $id) use (&$objects): RuntimeObject { + if (!isset($objects[$resource][$id])) { + $class = (string) $this->resources->classOf($resource); + $objects[$resource][$id] = new $class(); + $objects[$resource][$id]->id = $id; + } + + return $objects[$resource][$id]; + }; + $exists = static fn (string $resource, int $id): bool => isset($rows[$resource][$id]) || !isset($attempted[$resource][$id]); + + foreach ($rows as $resource => $byId) { + foreach ($byId as $id => $values) { + $instance = $object($resource, $id); + foreach ($this->resources->all()[$resource]->attributes as $attribute) { + $value = $values[$attribute->name] ?? null; + if (null !== $target = $attribute->target()) { + $targetIds = array_filter((array) $value, static fn (int $targetId): bool => $exists($target, $targetId)); + $value = array_map(static fn (int $targetId): RuntimeObject => $object($target, $targetId), array_values($targetIds)); + $value = $attribute->collection ? $value : $value[0] ?? null; + } + $instance->{$attribute->name} = $value ?? ($attribute->collection ? [] : null); + } + } + } + + return array_values(array_map(static fn (int $id): RuntimeObject => $objects[$name][$id], array_filter($ids, static fn (int $id): bool => isset($rows[$name][$id])))); + } + + /** + * @return array raw values by attribute name, references as ids + */ + public function extract(RuntimeObject $object): array + { + $id = static fn (mixed $value): mixed => $value instanceof RuntimeObject ? $value->id : $value; + $values = []; + foreach ($this->resources->get($object::class)->attributes ?? [] as $attribute) { + $value = $object->{$attribute->name}; + $values[$attribute->name] = $attribute->collection ? array_map($id, (array) $value) : $id($value); + } + + return $values; + } + + public static function filterValue(Attribute $attribute, mixed $value, IriConverterInterface $iriConverter): mixed + { + if (!\is_string($value)) { + return null; + } + + try { + return match ($attribute->type) { + AttributeType::Integer => (int) $value, + AttributeType::Float => (float) $value, + AttributeType::Boolean => filter_var($value, \FILTER_VALIDATE_BOOL), + AttributeType::Datetime => false === strtotime($value) ? null : new \DateTimeImmutable($value), + AttributeType::Reference => ($resource = $iriConverter->getResourceFromIri($value)) instanceof RuntimeObject && $resource->getResource() === $attribute->target() ? $resource->id : null, + default => $value, + }; + } catch (ExceptionInterface) { + return null; + } + } + + /** + * @param array $values + * + * @return iterable + */ + private function references(string $resource, array $values): iterable + { + foreach ($this->resources->all()[$resource]->attributes as $attribute) { + if (null !== $target = $attribute->target()) { + foreach ((array) ($values[$attribute->name] ?? []) as $targetId) { + yield [$target, $targetId]; + } + } + } + } +} diff --git a/tests/Fixtures/TestBundle/RuntimeResource/RuntimeObject.php b/tests/Fixtures/TestBundle/RuntimeResource/RuntimeObject.php new file mode 100644 index 00000000000..d6564b7e055 --- /dev/null +++ b/tests/Fixtures/TestBundle/RuntimeResource/RuntimeObject.php @@ -0,0 +1,42 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace ApiPlatform\Tests\Fixtures\TestBundle\RuntimeResource; + +abstract class RuntimeObject +{ + public ?int $id = null; + + /** @var array */ + private array $attributes = []; + + public function getResource(): string + { + return RuntimeResources::nameOf(static::class) ?? ''; + } + + public function __get(string $name): mixed + { + return $this->attributes[$name] ?? null; + } + + public function __set(string $name, mixed $value): void + { + $this->attributes[$name] = $value; + } + + public function __isset(string $name): bool + { + return \array_key_exists($name, $this->attributes); + } +} diff --git a/tests/Fixtures/TestBundle/RuntimeResource/RuntimeObjectNormalizer.php b/tests/Fixtures/TestBundle/RuntimeResource/RuntimeObjectNormalizer.php new file mode 100644 index 00000000000..beaecf6c81e --- /dev/null +++ b/tests/Fixtures/TestBundle/RuntimeResource/RuntimeObjectNormalizer.php @@ -0,0 +1,51 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace ApiPlatform\Tests\Fixtures\TestBundle\RuntimeResource; + +use ApiPlatform\Metadata\IriConverterInterface; +use Symfony\Component\Serializer\Normalizer\NormalizerAwareInterface; +use Symfony\Component\Serializer\Normalizer\NormalizerAwareTrait; +use Symfony\Component\Serializer\Normalizer\NormalizerInterface; + +final class RuntimeObjectNormalizer implements NormalizerInterface, NormalizerAwareInterface +{ + use NormalizerAwareTrait; + + private const DEPTH = 'runtime_resource_depth'; + private const CURRENT = 'runtime_resource_current'; + + public function __construct(private readonly IriConverterInterface $iriConverter) + { + } + + public function normalize(mixed $data, ?string $format = null, array $context = []): array|string|int|float|bool|\ArrayObject|null + { + $depth = $context[self::DEPTH] ?? 0; + if ($depth > 1) { + return $this->iriConverter->getIriFromResource($data); + } + + return $this->normalizer->normalize($data, $format, [self::DEPTH => $depth + 1, self::CURRENT => $data] + $context); + } + + public function supportsNormalization(mixed $data, ?string $format = null, array $context = []): bool + { + return $data instanceof RuntimeObject && ($context[self::CURRENT] ?? null) !== $data; + } + + public function getSupportedTypes(?string $format): array + { + return [RuntimeObject::class => false]; + } +} diff --git a/tests/Fixtures/TestBundle/RuntimeResource/RuntimePropertyMetadataFactory.php b/tests/Fixtures/TestBundle/RuntimeResource/RuntimePropertyMetadataFactory.php new file mode 100644 index 00000000000..f8693951251 --- /dev/null +++ b/tests/Fixtures/TestBundle/RuntimeResource/RuntimePropertyMetadataFactory.php @@ -0,0 +1,67 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace ApiPlatform\Tests\Fixtures\TestBundle\RuntimeResource; + +use ApiPlatform\Metadata\ApiProperty; +use ApiPlatform\Metadata\Exception\PropertyNotFoundException; +use ApiPlatform\Metadata\Property\Factory\PropertyMetadataFactoryInterface; +use Symfony\Component\TypeInfo\Type; + +final class RuntimePropertyMetadataFactory implements PropertyMetadataFactoryInterface +{ + public function __construct( + private readonly PropertyMetadataFactoryInterface $decorated, + private readonly RuntimeResources $resources, + ) { + } + + public function create(string $resourceClass, string $property, array $options = []): ApiProperty + { + if (null === $definition = $this->resources->get($resourceClass)) { + return $this->decorated->create($resourceClass, $property, $options); + } + + if ('id' === $property) { + return new ApiProperty(readable: true, writable: false, identifier: true, nativeType: Type::int()); + } + + if ('resource' === $property) { + return new ApiProperty(readable: false, writable: false, nativeType: Type::string()); + } + + $attribute = $definition->attributes[$property] ?? throw new PropertyNotFoundException(\sprintf('Property "%s" of "%s" not found.', $property, $resourceClass)); + $type = match ($attribute->type) { + AttributeType::String, AttributeType::Text, AttributeType::Enum => Type::string(), + AttributeType::Integer => Type::int(), + AttributeType::Float => Type::float(), + AttributeType::Boolean => Type::bool(), + AttributeType::Datetime => Type::object(\DateTimeImmutable::class), + AttributeType::Reference => Type::object((string) $this->resources->classOf((string) $attribute->target())), + }; + + return new ApiProperty( + readable: true, + writable: true, + required: $attribute->required, + readableLink: true, + writableLink: false, + schema: array_filter(['maxLength' => $attribute->options['maxLength'] ?? null, 'enum' => $attribute->options['values'] ?? null]) ?: null, + nativeType: match (true) { + $attribute->collection => Type::list($type), + $attribute->required => $type, + default => Type::nullable($type), + }, + ); + } +} diff --git a/tests/Fixtures/TestBundle/RuntimeResource/RuntimePropertyNameCollectionFactory.php b/tests/Fixtures/TestBundle/RuntimeResource/RuntimePropertyNameCollectionFactory.php new file mode 100644 index 00000000000..647303d8507 --- /dev/null +++ b/tests/Fixtures/TestBundle/RuntimeResource/RuntimePropertyNameCollectionFactory.php @@ -0,0 +1,35 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace ApiPlatform\Tests\Fixtures\TestBundle\RuntimeResource; + +use ApiPlatform\Metadata\Property\Factory\PropertyNameCollectionFactoryInterface; +use ApiPlatform\Metadata\Property\PropertyNameCollection; + +final class RuntimePropertyNameCollectionFactory implements PropertyNameCollectionFactoryInterface +{ + public function __construct( + private readonly PropertyNameCollectionFactoryInterface $decorated, + private readonly RuntimeResources $resources, + ) { + } + + public function create(string $resourceClass, array $options = []): PropertyNameCollection + { + if (null === $definition = $this->resources->get($resourceClass)) { + return $this->decorated->create($resourceClass, $options); + } + + return new PropertyNameCollection(['id', ...array_keys($definition->attributes)]); + } +} diff --git a/tests/Fixtures/TestBundle/RuntimeResource/RuntimeResourceBundle.php b/tests/Fixtures/TestBundle/RuntimeResource/RuntimeResourceBundle.php new file mode 100644 index 00000000000..923a5aa6840 --- /dev/null +++ b/tests/Fixtures/TestBundle/RuntimeResource/RuntimeResourceBundle.php @@ -0,0 +1,50 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace ApiPlatform\Tests\Fixtures\TestBundle\RuntimeResource; + +use Symfony\Component\DependencyInjection\ContainerBuilder; +use Symfony\Component\HttpKernel\Bundle\Bundle; + +final class RuntimeResourceBundle extends Bundle +{ + private static ?\Closure $resources = null; + + public function build(ContainerBuilder $container): void + { + $container->addCompilerPass(new RuntimeValidatorLoaderPass()); + } + + public function boot(): void + { + $container = $this->container; + if (null === self::$resources) { + spl_autoload_register([self::class, 'load']); + } + + self::$resources = static fn (): RuntimeResources => $container->get(RuntimeResources::class); + } + + public function shutdown(): void + { + spl_autoload_unregister([self::class, 'load']); + self::$resources = null; + } + + public static function load(string $class): void + { + if (null !== self::$resources && null !== (self::$resources)()->get($class)) { + eval(\sprintf('namespace %s; final class %s extends \\%s {}', RuntimeResources::NAMESPACE, substr($class, \strlen(RuntimeResources::NAMESPACE) + 1), RuntimeObject::class)); + } + } +} diff --git a/tests/Fixtures/TestBundle/RuntimeResource/RuntimeResourceMetadataCollectionFactory.php b/tests/Fixtures/TestBundle/RuntimeResource/RuntimeResourceMetadataCollectionFactory.php new file mode 100644 index 00000000000..f9bc3bc70d6 --- /dev/null +++ b/tests/Fixtures/TestBundle/RuntimeResource/RuntimeResourceMetadataCollectionFactory.php @@ -0,0 +1,96 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace ApiPlatform\Tests\Fixtures\TestBundle\RuntimeResource; + +use ApiPlatform\Metadata\ApiResource; +use ApiPlatform\Metadata\Delete; +use ApiPlatform\Metadata\Get; +use ApiPlatform\Metadata\GetCollection; +use ApiPlatform\Metadata\Link; +use ApiPlatform\Metadata\Operations; +use ApiPlatform\Metadata\Parameters; +use ApiPlatform\Metadata\Patch; +use ApiPlatform\Metadata\Post; +use ApiPlatform\Metadata\Put; +use ApiPlatform\Metadata\QueryParameter; +use ApiPlatform\Metadata\Resource\Factory\OperationDefaultsTrait; +use ApiPlatform\Metadata\Resource\Factory\ResourceMetadataCollectionFactoryInterface; +use ApiPlatform\Metadata\Resource\ResourceMetadataCollection; +use ApiPlatform\Metadata\Util\CamelCaseToSnakeCaseNameConverter; + +final class RuntimeResourceMetadataCollectionFactory implements ResourceMetadataCollectionFactoryInterface +{ + use OperationDefaultsTrait; + + /** + * @param array $defaults + */ + public function __construct( + private readonly ResourceMetadataCollectionFactoryInterface $decorated, + private readonly RuntimeResources $resources, + private readonly string $provider, + private readonly string $processor, + private readonly string $filter, + array $defaults = [], + ) { + $this->defaults = $defaults; + $this->camelCaseToSnakeCaseNameConverter = new CamelCaseToSnakeCaseNameConverter(); + } + + public function create(string $resourceClass): ResourceMetadataCollection + { + if (null === $definition = $this->resources->get($resourceClass)) { + return $this->decorated->create($resourceClass); + } + + $collectionLinks = ['resource' => new Link(fromClass: $resourceClass, identifiers: ['resource'], parameterName: 'resource')]; + $itemLinks = $collectionLinks + ['id' => new Link(fromClass: $resourceClass, identifiers: ['id'], parameterName: 'id')]; + $collection = ['routeName' => RuntimeRouter::COLLECTION_ROUTE, 'uriTemplate' => '/runtime/'.$definition->name, 'uriVariables' => $collectionLinks]; + $item = ['routeName' => RuntimeRouter::ITEM_ROUTE, 'uriTemplate' => '/runtime/'.$definition->name.'/{id}', 'uriVariables' => $itemLinks]; + $name = static fn (string $suffix): string => RuntimeRouter::operationName($definition->name, $suffix); + + $parameters = []; + foreach ($definition->attributes as $attribute) { + if ($attribute->filterable) { + $parameters[$attribute->name] = new QueryParameter(key: $attribute->name, property: $attribute->name, filter: $this->filter); + } + } + + $resource = $this->addGlobalDefaults(new ApiResource( + class: $resourceClass, + shortName: ucfirst($definition->name), + description: $definition->label, + security: $definition->security, + provider: $this->provider, + processor: $this->processor, + collectDenormalizationErrors: true, + extraProperties: ['openapi_use_uri_template' => true], + )); + + $operations = []; + foreach ([ + new Get(...$item, name: $name('get')), + new GetCollection(...$collection, name: $name('get_collection'), parameters: new Parameters($parameters)), + new Post(...$collection, name: $name('post'), read: false), + new Put(...$item, name: $name('put')), + new Patch(...$item, name: $name('patch')), + new Delete(...$item, name: $name('delete')), + ] as $operation) { + [$key, $operation] = $this->getOperationWithDefaults($resource, $operation); + $operations[$key] = $operation; + } + + return new ResourceMetadataCollection($resourceClass, [$resource->withOperations(new Operations($operations))]); + } +} diff --git a/tests/Fixtures/TestBundle/RuntimeResource/RuntimeResourceNameCollectionFactory.php b/tests/Fixtures/TestBundle/RuntimeResource/RuntimeResourceNameCollectionFactory.php new file mode 100644 index 00000000000..1c6df179293 --- /dev/null +++ b/tests/Fixtures/TestBundle/RuntimeResource/RuntimeResourceNameCollectionFactory.php @@ -0,0 +1,31 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace ApiPlatform\Tests\Fixtures\TestBundle\RuntimeResource; + +use ApiPlatform\Metadata\Resource\Factory\ResourceNameCollectionFactoryInterface; +use ApiPlatform\Metadata\Resource\ResourceNameCollection; + +final class RuntimeResourceNameCollectionFactory implements ResourceNameCollectionFactoryInterface +{ + public function __construct( + private readonly ResourceNameCollectionFactoryInterface $decorated, + private readonly RuntimeResources $resources, + ) { + } + + public function create(): ResourceNameCollection + { + return new ResourceNameCollection([...iterator_to_array($this->decorated->create()), ...array_values($this->resources->classes())]); + } +} diff --git a/tests/Fixtures/TestBundle/RuntimeResource/RuntimeResources.php b/tests/Fixtures/TestBundle/RuntimeResource/RuntimeResources.php new file mode 100644 index 00000000000..e4d89e6fb88 --- /dev/null +++ b/tests/Fixtures/TestBundle/RuntimeResource/RuntimeResources.php @@ -0,0 +1,145 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace ApiPlatform\Tests\Fixtures\TestBundle\RuntimeResource; + +use ApiPlatform\Metadata\Resource\Factory\ResourceMetadataCollectionFactoryInterface; +use ApiPlatform\Metadata\Resource\Factory\ResourceNameCollectionFactoryInterface; +use Symfony\Component\HttpKernel\Event\RequestEvent; + +final class RuntimeResources +{ + public const NAMESPACE = __NAMESPACE__.'\Generated'; + + /** @var array|null */ + private ?array $definitions = null; + /** @var array */ + private array $classes = []; + private ?int $generation = null; + /** @var array|null */ + private ?array $staticShortNames = null; + private bool $loading = false; + + /** + * @param \Closure(): ResourceNameCollectionFactoryInterface $staticResourceNames + * @param \Closure(): ResourceMetadataCollectionFactoryInterface $resourceMetadata + */ + public function __construct( + private readonly DefinitionProvider $provider, + private readonly \Closure $staticResourceNames, + private readonly \Closure $resourceMetadata, + ) { + } + + public static function nameOf(string $class): ?string + { + return 1 === preg_match('/^'.preg_quote(self::NAMESPACE, '/').'\\\\([A-Z][a-z0-9]*)_[0-9a-f]{8}\z/', $class, $matches) ? lcfirst($matches[1]) : null; + } + + public function onKernelRequest(RequestEvent $event): void + { + if ($event->isMainRequest() && $this->generation !== $generation = $this->provider->generation()) { + $this->generation = $generation; + $this->definitions = null; + $this->classes = []; + } + } + + /** + * @return array + */ + public function all(): array + { + if (null !== $this->definitions || $this->loading) { + return $this->definitions ?? []; + } + + $this->loading = true; + try { + $this->generation ??= $this->provider->generation(); + $taken = $this->staticShortNames(); + $definitions = []; + foreach ($this->provider->definitions() as $definition) { + if (1 === preg_match('/^[a-z][a-z0-9]{0,63}\z/', $definition->name) && !isset($definitions[$definition->name]) && !isset($taken[$definition->name])) { + $definitions[$definition->name] = $definition; + } + } + } finally { + $this->loading = false; + } + + foreach ($definitions as $name => $definition) { + $definitions[$name] = new Definition($definition->name, $definition->label, $definition->security, array_filter($definition->attributes, static fn (Attribute $attribute): bool => 1 === preg_match('/^[a-z][a-zA-Z0-9]{0,63}\z/', $attribute->name) + && !\in_array($attribute->name, ['id', 'resource'], true) + && (null === $attribute->target() || isset($definitions[$attribute->target()])))); + } + + $this->classes = []; + foreach ($definitions as $name => $definition) { + $reachable = [$name => $definition]; + for ($queue = [$name]; null !== $current = array_shift($queue);) { + foreach ($definitions[$current]->attributes as $attribute) { + if (null !== ($target = $attribute->target()) && !isset($reachable[$target])) { + $reachable[$target] = $definitions[$target]; + $queue[] = $target; + } + } + } + ksort($reachable); + $this->classes[$name] = self::NAMESPACE.'\\'.ucfirst($name).'_'.substr(hash('xxh128', serialize($reachable)), 0, 8); + } + + return $this->definitions = $definitions; + } + + /** + * @return array + */ + public function classes(): array + { + $this->all(); + + return $this->classes; + } + + public function classOf(string $name): ?string + { + return $this->classes()[$name] ?? null; + } + + public function get(string $class): ?Definition + { + $name = self::nameOf($class); + + return null !== $name && $this->classOf($name) === $class ? $this->definitions[$name] : null; + } + + /** + * @return array + */ + private function staticShortNames(): array + { + if (null !== $this->staticShortNames) { + return $this->staticShortNames; + } + + $shortNames = []; + foreach (($this->staticResourceNames)()->create() as $class) { + foreach (($this->resourceMetadata)()->create($class) as $resource) { + $shortNames[strtolower((string) $resource->getShortName())] = true; + } + } + + return $this->staticShortNames = $shortNames; + } +} diff --git a/tests/Fixtures/TestBundle/RuntimeResource/RuntimeRouter.php b/tests/Fixtures/TestBundle/RuntimeResource/RuntimeRouter.php new file mode 100644 index 00000000000..288b1a0b83e --- /dev/null +++ b/tests/Fixtures/TestBundle/RuntimeResource/RuntimeRouter.php @@ -0,0 +1,100 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace ApiPlatform\Tests\Fixtures\TestBundle\RuntimeResource; + +use ApiPlatform\Metadata\UrlGeneratorInterface; +use Symfony\Component\HttpKernel\Event\RequestEvent; +use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; +use Symfony\Component\Routing\Exception\ResourceNotFoundException; +use Symfony\Component\Routing\RequestContext; +use Symfony\Component\Routing\RouteCollection; +use Symfony\Component\Routing\RouterInterface; + +final class RuntimeRouter implements RouterInterface, UrlGeneratorInterface +{ + public const COLLECTION_ROUTE = 'runtime_collection'; + public const ITEM_ROUTE = 'runtime_item'; + + private const OPERATIONS = [ + self::COLLECTION_ROUTE => ['GET' => 'get_collection', 'HEAD' => 'get_collection', 'POST' => 'post'], + self::ITEM_ROUTE => ['GET' => 'get', 'HEAD' => 'get', 'PUT' => 'put', 'PATCH' => 'patch', 'DELETE' => 'delete'], + ]; + + public function __construct( + private readonly RouterInterface&UrlGeneratorInterface $router, + private readonly RuntimeResources $resources, + ) { + } + + public static function operationName(string $name, string $suffix): string + { + return 'runtime_'.$name.'_'.$suffix; + } + + public function onKernelRequest(RequestEvent $event): void + { + $request = $event->getRequest(); + if (!isset(self::OPERATIONS[$request->attributes->get('_route')])) { + return; + } + + $request->attributes->add($this->resolve($request->attributes->all(), $request->getMethod()) ?? throw new NotFoundHttpException(\sprintf('No route found for "%s %s".', $request->getMethod(), $request->getPathInfo()))); + } + + public function match(string $pathinfo): array + { + $parameters = $this->router->match($pathinfo); + if (!isset(self::OPERATIONS[$parameters['_route'] ?? ''])) { + return $parameters; + } + + return ($this->resolve($parameters, 'GET') ?? throw new ResourceNotFoundException(\sprintf('No runtime resource matches "%s".', $pathinfo))) + $parameters; + } + + public function generate(string $name, array $parameters = [], int $referenceType = self::ABSOLUTE_PATH): string + { + return $this->router->generate($name, $parameters, $referenceType); + } + + public function setContext(RequestContext $context): void + { + $this->router->setContext($context); + } + + public function getContext(): RequestContext + { + return $this->router->getContext(); + } + + public function getRouteCollection(): RouteCollection + { + return $this->router->getRouteCollection(); + } + + /** + * @param array $parameters + * + * @return array{_api_resource_class: string, _api_operation_name: string}|null + */ + private function resolve(array $parameters, string $method): ?array + { + $suffix = self::OPERATIONS[$parameters['_route']][$method] ?? null; + $name = $parameters['resource'] ?? null; + if (null === $suffix || !\is_string($name) || null === $class = $this->resources->classOf($name)) { + return null; + } + + return ['_api_resource_class' => $class, '_api_operation_name' => self::operationName($name, $suffix)]; + } +} diff --git a/tests/Fixtures/TestBundle/RuntimeResource/RuntimeValidatorLoader.php b/tests/Fixtures/TestBundle/RuntimeResource/RuntimeValidatorLoader.php new file mode 100644 index 00000000000..7442e999c22 --- /dev/null +++ b/tests/Fixtures/TestBundle/RuntimeResource/RuntimeValidatorLoader.php @@ -0,0 +1,82 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace ApiPlatform\Tests\Fixtures\TestBundle\RuntimeResource; + +use Symfony\Component\Validator\Constraint; +use Symfony\Component\Validator\Constraints\All; +use Symfony\Component\Validator\Constraints\Callback; +use Symfony\Component\Validator\Constraints\Choice; +use Symfony\Component\Validator\Constraints\Length; +use Symfony\Component\Validator\Constraints\NotBlank; +use Symfony\Component\Validator\Constraints\NotNull; +use Symfony\Component\Validator\Constraints\Range; +use Symfony\Component\Validator\Constraints\Type; +use Symfony\Component\Validator\Context\ExecutionContextInterface; +use Symfony\Component\Validator\Mapping\ClassMetadata; +use Symfony\Component\Validator\Mapping\Loader\LoaderInterface; + +final class RuntimeValidatorLoader implements LoaderInterface +{ + public function __construct(private readonly RuntimeResources $resources) + { + } + + public function loadClassMetadata(ClassMetadata $metadata): bool + { + if (null === $definition = $this->resources->get($metadata->getClassName())) { + return false; + } + + $constraints = array_map($this->constraints(...), $definition->attributes); + $metadata->addConstraint(new Callback(callback: [self::class, 'validate'], payload: $constraints)); + + return true; + } + + /** + * @param array> $constraints + */ + public static function validate(RuntimeObject $object, ExecutionContextInterface $context, array $constraints): void + { + foreach ($constraints as $property => $propertyConstraints) { + $context->getValidator()->inContext($context)->atPath($property)->validate($object->{$property}, $propertyConstraints); + } + } + + /** + * @return list + */ + private function constraints(Attribute $attribute): array + { + $options = $attribute->options; + $constraints = match ($attribute->type) { + AttributeType::String, AttributeType::Text => [new Type('string'), ...(isset($options['maxLength']) ? [new Length(max: $options['maxLength'])] : [])], + AttributeType::Integer, AttributeType::Float => [new Type('numeric'), ...(isset($options['min']) || isset($options['max']) ? [new Range(min: $options['min'] ?? null, max: $options['max'] ?? null)] : [])], + AttributeType::Boolean => [new Type('bool')], + AttributeType::Datetime => [new Type(\DateTimeInterface::class)], + AttributeType::Enum => [new Choice(choices: $options['values'] ?? [])], + AttributeType::Reference => [new Type((string) $this->resources->classOf((string) $attribute->target()))], + }; + + if ($attribute->collection) { + $constraints = [new All($constraints)]; + } + + if ($attribute->required) { + array_unshift($constraints, AttributeType::Boolean === $attribute->type ? new NotNull() : new NotBlank()); + } + + return $constraints; + } +} diff --git a/tests/Fixtures/TestBundle/RuntimeResource/RuntimeValidatorLoaderPass.php b/tests/Fixtures/TestBundle/RuntimeResource/RuntimeValidatorLoaderPass.php new file mode 100644 index 00000000000..50376951c36 --- /dev/null +++ b/tests/Fixtures/TestBundle/RuntimeResource/RuntimeValidatorLoaderPass.php @@ -0,0 +1,26 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace ApiPlatform\Tests\Fixtures\TestBundle\RuntimeResource; + +use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface; +use Symfony\Component\DependencyInjection\ContainerBuilder; +use Symfony\Component\DependencyInjection\Reference; + +final class RuntimeValidatorLoaderPass implements CompilerPassInterface +{ + public function process(ContainerBuilder $container): void + { + $container->getDefinition('validator.builder')->addMethodCall('addLoader', [new Reference(RuntimeValidatorLoader::class)]); + } +} diff --git a/tests/Fixtures/TestBundle/State/SharedBackingResourceObjectResolver.php b/tests/Fixtures/TestBundle/State/SharedBackingResourceObjectResolver.php new file mode 100644 index 00000000000..7f253480c9e --- /dev/null +++ b/tests/Fixtures/TestBundle/State/SharedBackingResourceObjectResolver.php @@ -0,0 +1,38 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace ApiPlatform\Tests\Fixtures\TestBundle\State; + +use ApiPlatform\State\ResourceObjectResolverInterface; +use ApiPlatform\Tests\Fixtures\TestBundle\ApiResource\SharedBackingGadget; +use ApiPlatform\Tests\Fixtures\TestBundle\ApiResource\SharedBackingThing; +use ApiPlatform\Tests\Fixtures\TestBundle\Entity\SharedBackingEntity; +use Symfony\Component\ObjectMapper\ObjectMapperInterface; + +final readonly class SharedBackingResourceObjectResolver implements ResourceObjectResolverInterface +{ + public function __construct( + private ResourceObjectResolverInterface $inner, + private ObjectMapperInterface $objectMapper, + ) { + } + + public function resolve(object $data): iterable + { + if (!$data instanceof SharedBackingEntity) { + return $this->inner->resolve($data); + } + + return [$this->objectMapper->map($data, 'thing' === $data->kind ? SharedBackingThing::class : SharedBackingGadget::class)]; + } +} diff --git a/tests/Fixtures/app/AppKernel.php b/tests/Fixtures/app/AppKernel.php index e670b1c9de8..0c31290a00b 100644 --- a/tests/Fixtures/app/AppKernel.php +++ b/tests/Fixtures/app/AppKernel.php @@ -20,6 +20,7 @@ use ApiPlatform\Symfony\Bundle\ApiPlatformBundle; use ApiPlatform\Tests\Fixtures\TestBundle\Document\User as UserDocument; use ApiPlatform\Tests\Fixtures\TestBundle\Entity\User; +use ApiPlatform\Tests\Fixtures\TestBundle\RuntimeResource\RuntimeResourceBundle; use ApiPlatform\Tests\Fixtures\TestBundle\TestBundle; use Doctrine\Bundle\DoctrineBundle\Command\Proxy\ValidateSchemaCommand; use Doctrine\Bundle\DoctrineBundle\ConnectionFactory; @@ -56,6 +57,7 @@ class AppKernel extends Kernel use MicroKernelTrait; private $genIdDefault; + private bool $runtimeResources; public function __construct(string $environment, bool $debug, ?bool $genIdDefault = null) { @@ -63,6 +65,7 @@ public function __construct(string $environment, bool $debug, ?bool $genIdDefaul $this->environment = $_SERVER['APP_ENV'] ?? $environment; $this->genIdDefault = $genIdDefault ?? $_SERVER['GEN_ID_DEFAULT'] ?? null; + $this->runtimeResources = (bool) ($_SERVER['RUNTIME_RESOURCES'] ?? false); } public function registerBundles(): array @@ -88,6 +91,10 @@ public function registerBundles(): array $bundles[] = new TestBundle(); + if ($this->runtimeResources) { + $bundles[] = new RuntimeResourceBundle(); + } + return $bundles; } @@ -98,18 +105,22 @@ public function getProjectDir(): string public function getCacheDir(): string { - return parent::getCacheDir().(null !== $this->genIdDefault ? '_gen_id_'.$this->genIdDefault : ''); + return parent::getCacheDir().(null !== $this->genIdDefault ? '_gen_id_'.$this->genIdDefault : '').($this->runtimeResources ? '_runtime_resources' : ''); } protected function configureRoutes($routes): void { $routes->import(__DIR__."/config/routing_{$this->getEnvironment()}.yml"); + if ($this->runtimeResources) { + $routes->import(__DIR__.'/config/routing_runtime_resources.yml'); + } } protected function configureContainer(ContainerBuilder $c, LoaderInterface $loader): void { $c->setParameter('kernel.project_dir', __DIR__); $c->setParameter('app.gen_id_default', $this->genIdDefault); + $c->setParameter('app.runtime_resources_controller', ($_SERVER['USE_SYMFONY_LISTENERS'] ?? false) ? 'api_platform.action.placeholder' : 'api_platform.symfony.main_controller'); $c->setParameter('app.security.admin_only', 'is_granted("ROLE_ADMIN")'); $loader->load(__DIR__."/config/config_{$this->getEnvironment()}.yml"); @@ -319,6 +330,11 @@ class_exists(NativePasswordHasher::class) ? 'password_hashers' : 'encoders' => [ $loader->load(__DIR__.'/config/phpunit.yml'); } + if ($this->runtimeResources) { + $loader->load(__DIR__.'/config/config_runtime_resources.yml'); + $loader->load(__DIR__.'/config/config_runtime_resources_'.('mongodb' === $this->environment ? 'odm' : 'orm').'.yml'); + } + if ('mongodb' === $this->environment) { $c->prependExtensionConfig('api_platform', [ 'mapping' => [ diff --git a/tests/Fixtures/app/config/config_common.yml b/tests/Fixtures/app/config/config_common.yml index fc1636d8748..7b045076db4 100644 --- a/tests/Fixtures/app/config/config_common.yml +++ b/tests/Fixtures/app/config/config_common.yml @@ -103,6 +103,7 @@ api_platform: - '%kernel.project_dir%/../TestBundle/Model' mercure: include_type: true + resolve_resource_objects: true services: test.client: @@ -431,6 +432,10 @@ services: decorates: api_platform.openapi.factory arguments: ['@ApiPlatform\Tests\Fixtures\TestBundle\OpenApi\Issue8143ResponseComponentFactory.inner'] + ApiPlatform\Tests\Fixtures\TestBundle\State\SharedBackingResourceObjectResolver: + decorates: api_platform.state.resource_object_resolver + arguments: ['@.inner', '@api_platform.object_mapper'] + app.related_dummy_resource.complex_sub_query_filter: class: ApiPlatform\Tests\Fixtures\TestBundle\Filter\ComplexSubQueryFilter arguments: ['@doctrine'] diff --git a/tests/Fixtures/app/config/config_runtime_resources.yml b/tests/Fixtures/app/config/config_runtime_resources.yml new file mode 100644 index 00000000000..5a830059ffc --- /dev/null +++ b/tests/Fixtures/app/config/config_runtime_resources.yml @@ -0,0 +1,52 @@ +services: + _defaults: + autowire: false + + ApiPlatform\Tests\Fixtures\TestBundle\RuntimeResource\RuntimeResources: + public: true + arguments: + - '@ApiPlatform\Tests\Fixtures\TestBundle\RuntimeResource\DefinitionProvider' + - !service_closure '@ApiPlatform\Tests\Fixtures\TestBundle\RuntimeResource\RuntimeResourceNameCollectionFactory.inner' + - !service_closure '@api_platform.metadata.resource.metadata_collection_factory' + tags: [{ name: kernel.event_listener, event: kernel.request, method: onKernelRequest, priority: 4096 }] + + ApiPlatform\Tests\Fixtures\TestBundle\RuntimeResource\RuntimeMapper: + arguments: ['@ApiPlatform\Tests\Fixtures\TestBundle\RuntimeResource\RuntimeResources'] + + ApiPlatform\Tests\Fixtures\TestBundle\RuntimeResource\RuntimeRouter: + decorates: api_platform.router + arguments: ['@.inner', '@ApiPlatform\Tests\Fixtures\TestBundle\RuntimeResource\RuntimeResources'] + tags: [{ name: kernel.event_listener, event: kernel.request, method: onKernelRequest, priority: 31 }] + + ApiPlatform\Tests\Fixtures\TestBundle\RuntimeResource\RuntimeObjectNormalizer: + arguments: ['@api_platform.iri_converter'] + tags: [{ name: serializer.normalizer, priority: -870 }] + + ApiPlatform\Tests\Fixtures\TestBundle\RuntimeResource\RuntimeValidatorLoader: + arguments: ['@ApiPlatform\Tests\Fixtures\TestBundle\RuntimeResource\RuntimeResources'] + + ApiPlatform\Tests\Fixtures\TestBundle\RuntimeResource\RuntimeResourceNameCollectionFactory: + decorates: api_platform.metadata.resource.name_collection_factory + decoration_priority: -20 + arguments: ['@.inner', '@ApiPlatform\Tests\Fixtures\TestBundle\RuntimeResource\RuntimeResources'] + + ApiPlatform\Tests\Fixtures\TestBundle\RuntimeResource\RuntimeResourceMetadataCollectionFactory: + decorates: api_platform.metadata.resource.metadata_collection_factory + decoration_priority: 1500 + arguments: + - '@.inner' + - '@ApiPlatform\Tests\Fixtures\TestBundle\RuntimeResource\RuntimeResources' + - '%runtime_resources.provider%' + - '%runtime_resources.processor%' + - '%runtime_resources.filter%' + - '%api_platform.defaults%' + + ApiPlatform\Tests\Fixtures\TestBundle\RuntimeResource\RuntimePropertyNameCollectionFactory: + decorates: api_platform.metadata.property.name_collection_factory + decoration_priority: 5 + arguments: ['@.inner', '@ApiPlatform\Tests\Fixtures\TestBundle\RuntimeResource\RuntimeResources'] + + ApiPlatform\Tests\Fixtures\TestBundle\RuntimeResource\RuntimePropertyMetadataFactory: + decorates: api_platform.metadata.property.metadata_factory + decoration_priority: 33 + arguments: ['@.inner', '@ApiPlatform\Tests\Fixtures\TestBundle\RuntimeResource\RuntimeResources'] diff --git a/tests/Fixtures/app/config/config_runtime_resources_odm.yml b/tests/Fixtures/app/config/config_runtime_resources_odm.yml new file mode 100644 index 00000000000..56faf6667b9 --- /dev/null +++ b/tests/Fixtures/app/config/config_runtime_resources_odm.yml @@ -0,0 +1,29 @@ +parameters: + runtime_resources.provider: 'ApiPlatform\Tests\Fixtures\TestBundle\RuntimeResource\Odm\DocumentProvider' + runtime_resources.processor: 'ApiPlatform\Tests\Fixtures\TestBundle\RuntimeResource\Odm\DocumentProcessor' + runtime_resources.filter: 'ApiPlatform\Tests\Fixtures\TestBundle\RuntimeResource\Odm\DocumentFilter' + +services: + ApiPlatform\Tests\Fixtures\TestBundle\RuntimeResource\DefinitionProvider: + class: ApiPlatform\Tests\Fixtures\TestBundle\RuntimeResource\Odm\OdmDefinitionProvider + public: true + arguments: ['@doctrine_mongodb'] + + ApiPlatform\Tests\Fixtures\TestBundle\RuntimeResource\Odm\DocumentProvider: + arguments: + - '@api_platform.doctrine_mongodb.odm.state.item_provider' + - '@api_platform.doctrine_mongodb.odm.state.collection_provider' + - '@doctrine_mongodb' + - '@ApiPlatform\Tests\Fixtures\TestBundle\RuntimeResource\RuntimeMapper' + tags: ['api_platform.state_provider'] + + ApiPlatform\Tests\Fixtures\TestBundle\RuntimeResource\Odm\DocumentProcessor: + arguments: + - '@doctrine_mongodb' + - '@ApiPlatform\Tests\Fixtures\TestBundle\RuntimeResource\RuntimeMapper' + - '@ApiPlatform\Tests\Fixtures\TestBundle\RuntimeResource\Odm\DocumentProvider' + tags: ['api_platform.state_processor'] + + ApiPlatform\Tests\Fixtures\TestBundle\RuntimeResource\Odm\DocumentFilter: + arguments: ['@ApiPlatform\Tests\Fixtures\TestBundle\RuntimeResource\RuntimeResources', '@api_platform.iri_converter'] + tags: ['api_platform.filter'] diff --git a/tests/Fixtures/app/config/config_runtime_resources_orm.yml b/tests/Fixtures/app/config/config_runtime_resources_orm.yml new file mode 100644 index 00000000000..42e48caf19b --- /dev/null +++ b/tests/Fixtures/app/config/config_runtime_resources_orm.yml @@ -0,0 +1,26 @@ +parameters: + runtime_resources.provider: 'ApiPlatform\Tests\Fixtures\TestBundle\RuntimeResource\Orm\EavProvider' + runtime_resources.processor: 'ApiPlatform\Tests\Fixtures\TestBundle\RuntimeResource\Orm\EavProcessor' + runtime_resources.filter: 'ApiPlatform\Tests\Fixtures\TestBundle\RuntimeResource\Orm\EavFilter' + +services: + ApiPlatform\Tests\Fixtures\TestBundle\RuntimeResource\DefinitionProvider: + class: ApiPlatform\Tests\Fixtures\TestBundle\RuntimeResource\Orm\OrmDefinitionProvider + public: true + arguments: ['@doctrine'] + + ApiPlatform\Tests\Fixtures\TestBundle\RuntimeResource\Orm\EavProvider: + arguments: + - '@api_platform.doctrine.orm.state.item_provider' + - '@api_platform.doctrine.orm.state.collection_provider' + - '@doctrine' + - '@ApiPlatform\Tests\Fixtures\TestBundle\RuntimeResource\RuntimeMapper' + tags: ['api_platform.state_provider'] + + ApiPlatform\Tests\Fixtures\TestBundle\RuntimeResource\Orm\EavProcessor: + arguments: ['@doctrine', '@ApiPlatform\Tests\Fixtures\TestBundle\RuntimeResource\RuntimeMapper', '@ApiPlatform\Tests\Fixtures\TestBundle\RuntimeResource\Orm\EavProvider'] + tags: ['api_platform.state_processor'] + + ApiPlatform\Tests\Fixtures\TestBundle\RuntimeResource\Orm\EavFilter: + arguments: ['@ApiPlatform\Tests\Fixtures\TestBundle\RuntimeResource\RuntimeResources', '@api_platform.iri_converter'] + tags: ['api_platform.filter'] diff --git a/tests/Fixtures/app/config/routing_common.yml b/tests/Fixtures/app/config/routing_common.yml index 8e1d043fe81..bd8c29c86d4 100644 --- a/tests/Fixtures/app/config/routing_common.yml +++ b/tests/Fixtures/app/config/routing_common.yml @@ -10,3 +10,17 @@ relation_embedded.custom_get: methods: ['GET', 'HEAD'] defaults: _controller: 'ApiPlatform\Tests\Fixtures\TestBundle\Controller\CustomController::customAction' + +shared_static_route: + path: '/shared_static_route' + methods: ['GET', 'HEAD'] + defaults: + _controller: 'api_platform.action.placeholder' + +shared_route_variable_item: + path: '/shared_route_variable/{kind}/{id}' + methods: ['GET', 'HEAD'] + defaults: + _controller: 'api_platform.action.placeholder' + _api_resource_class: 'ApiPlatform\Tests\Fixtures\TestBundle\ApiResource\SharedRouteIri\VariableRouteAlpha' + _api_operation_name: 'shared_route_variable_alpha_get' diff --git a/tests/Fixtures/app/config/routing_runtime_resources.yml b/tests/Fixtures/app/config/routing_runtime_resources.yml new file mode 100644 index 00000000000..5ea1671adcb --- /dev/null +++ b/tests/Fixtures/app/config/routing_runtime_resources.yml @@ -0,0 +1,13 @@ +runtime_collection: + path: /runtime/{resource} + methods: [GET, HEAD, POST] + controller: '%app.runtime_resources_controller%' + defaults: { _format: null } + requirements: { resource: '[a-z][a-z0-9]{0,63}' } + +runtime_item: + path: /runtime/{resource}/{id} + methods: [GET, HEAD, PUT, PATCH, DELETE] + controller: '%app.runtime_resources_controller%' + defaults: { _format: null } + requirements: { resource: '[a-z][a-z0-9]{0,63}', id: '\d+' } diff --git a/tests/Functional/HttpCache/SharedBackingEntityPurgeTest.php b/tests/Functional/HttpCache/SharedBackingEntityPurgeTest.php new file mode 100644 index 00000000000..33caf428b9c --- /dev/null +++ b/tests/Functional/HttpCache/SharedBackingEntityPurgeTest.php @@ -0,0 +1,101 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace ApiPlatform\Tests\Functional\HttpCache; + +use ApiPlatform\Test\ApiTestCase; +use ApiPlatform\Tests\Fixtures\NullPurger; +use ApiPlatform\Tests\Fixtures\TestBundle\ApiResource\SharedBackingGadget; +use ApiPlatform\Tests\Fixtures\TestBundle\ApiResource\SharedBackingThing; +use ApiPlatform\Tests\Fixtures\TestBundle\Entity\SharedBackingEntity; +use ApiPlatform\Tests\RecreateSchemaTrait; +use ApiPlatform\Tests\SetupClassResourcesTrait; +use Doctrine\ORM\EntityManagerInterface; + +final class SharedBackingEntityPurgeTest extends ApiTestCase +{ + use RecreateSchemaTrait; + use SetupClassResourcesTrait; + + protected static ?bool $alwaysBootKernel = false; + + public static function getResources(): array + { + return [SharedBackingThing::class, SharedBackingGadget::class]; + } + + protected function setUp(): void + { + if ('mongodb' === static::getContainer()->getParameter('kernel.environment')) { + $this->markTestSkipped('ORM only.'); + } + + $this->recreateSchema([SharedBackingEntity::class]); + } + + public function testUpdatePurgesResolvedResourceIri(): void + { + $entity = new SharedBackingEntity(); + $entity->kind = 'thing'; + $entity->name = 'before'; + $manager = static::getContainer()->get('doctrine')->getManager(); + \assert($manager instanceof EntityManagerInterface); + $manager->persist($entity); + $manager->flush(); + $this->purger()->clear(); + + self::createClient()->request('PATCH', '/shared_backing_things/'.$entity->id, [ + 'headers' => ['Content-Type' => 'application/merge-patch+json'], + 'json' => ['name' => 'after'], + ]); + + $this->assertResponseStatusCodeSame(200); + $this->assertSame(['/shared_backing_things', '/shared_backing_things/1'], $this->purgedIris()); + } + + public function testUpdatePurgesCollectionsWithUriVariables(): void + { + $entity = new SharedBackingEntity(); + $entity->kind = 'gadget'; + $entity->name = 'before'; + $manager = static::getContainer()->get('doctrine')->getManager(); + \assert($manager instanceof EntityManagerInterface); + $manager->persist($entity); + $manager->flush(); + $this->purger()->clear(); + + self::createClient()->request('PATCH', '/shared_backing_gadgets/'.$entity->id, [ + 'headers' => ['Content-Type' => 'application/merge-patch+json'], + 'json' => ['name' => 'after'], + ]); + + $this->assertResponseStatusCodeSame(200); + $this->assertSame(['/shared_backing_gadgets', '/shared_backing_gadgets/1', '/shared_backing_kinds/gadget/gadgets'], $this->purgedIris()); + } + + private function purgedIris(): array + { + $iris = $this->purger()->getIris(); + sort($iris); + + return $iris; + } + + private function purger(): NullPurger + { + $purger = static::getContainer()->get('test.api_platform.http_cache.purger'); + \assert($purger instanceof NullPurger); + + return $purger; + } +} diff --git a/tests/Functional/Mercure/SharedBackingEntityMercureTest.php b/tests/Functional/Mercure/SharedBackingEntityMercureTest.php new file mode 100644 index 00000000000..287ba3d676a --- /dev/null +++ b/tests/Functional/Mercure/SharedBackingEntityMercureTest.php @@ -0,0 +1,58 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace ApiPlatform\Tests\Functional\Mercure; + +use ApiPlatform\Test\ApiTestCase; +use ApiPlatform\Tests\Fixtures\TestBundle\ApiResource\SharedBackingGadget; +use ApiPlatform\Tests\Fixtures\TestBundle\ApiResource\SharedBackingThing; +use ApiPlatform\Tests\Fixtures\TestBundle\Entity\SharedBackingEntity; +use ApiPlatform\Tests\Fixtures\TestBundle\Mercure\TestHub; +use ApiPlatform\Tests\RecreateSchemaTrait; +use ApiPlatform\Tests\SetupClassResourcesTrait; + +final class SharedBackingEntityMercureTest extends ApiTestCase +{ + use RecreateSchemaTrait; + use SetupClassResourcesTrait; + + protected static ?bool $alwaysBootKernel = false; + + public static function getResources(): array + { + return [SharedBackingThing::class, SharedBackingGadget::class]; + } + + public function testPublishResolvedResourceOnCreate(): void + { + if ('mongodb' === static::getContainer()->getParameter('kernel.environment')) { + $this->markTestSkipped('ORM only.'); + } + + $this->recreateSchema([SharedBackingEntity::class]); + $hub = static::getContainer()->get('mercure.hub.default.test_hub'); + \assert($hub instanceof TestHub); + (new \ReflectionProperty(TestHub::class, 'updates'))->setValue($hub, []); + + self::createClient()->request('POST', '/shared_backing_things', [ + 'headers' => ['Content-Type' => 'application/ld+json'], + 'json' => ['name' => 'created', 'kind' => 'thing'], + ]); + + $this->assertResponseStatusCodeSame(201); + $updates = $hub->getUpdates(); + $this->assertCount(1, $updates); + $this->assertSame(['http://localhost/shared_backing_things/1'], array_values($updates[0]->getTopics())); + $this->assertSame('SharedBackingThing', json_decode($updates[0]->getData(), true, flags: \JSON_THROW_ON_ERROR)['@type']); + } +} diff --git a/tests/Functional/RuntimeResourceEavTest.php b/tests/Functional/RuntimeResourceEavTest.php new file mode 100644 index 00000000000..6b967f8809f --- /dev/null +++ b/tests/Functional/RuntimeResourceEavTest.php @@ -0,0 +1,418 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace ApiPlatform\Tests\Functional; + +use ApiPlatform\Test\ApiTestCase; +use ApiPlatform\Test\Client; +use ApiPlatform\Tests\Fixtures\TestBundle\ApiResource\Headers; +use ApiPlatform\Tests\Fixtures\TestBundle\Entity\RuntimeResource\AttributeDefinition; +use ApiPlatform\Tests\Fixtures\TestBundle\Entity\RuntimeResource\AttributeValue; +use ApiPlatform\Tests\Fixtures\TestBundle\Entity\RuntimeResource\EntityRow; +use ApiPlatform\Tests\Fixtures\TestBundle\Entity\RuntimeResource\Generation; +use ApiPlatform\Tests\Fixtures\TestBundle\Entity\RuntimeResource\ResourceDefinition; +use ApiPlatform\Tests\Fixtures\TestBundle\RuntimeResource\DefinitionProvider; +use ApiPlatform\Tests\Fixtures\TestBundle\RuntimeResource\RuntimeResources; +use ApiPlatform\Tests\RecreateSchemaTrait; +use ApiPlatform\Tests\SetupClassResourcesTrait; +use Doctrine\Bundle\DoctrineBundle\DataCollector\DoctrineDataCollector; +use Doctrine\ORM\EntityManagerInterface; +use PHPUnit\Framework\Attributes\DataProvider; +use Symfony\Component\Cache\DataCollector\CacheDataCollector; + +final class RuntimeResourceEavTest extends ApiTestCase +{ + use RecreateSchemaTrait; + use SetupClassResourcesTrait; + + protected static ?bool $alwaysBootKernel = false; + + private const JSONLD = ['Content-Type' => 'application/ld+json', 'Accept' => 'application/ld+json']; + + public static function getResources(): array + { + return [Headers::class]; + } + + protected function setUp(): void + { + $_SERVER['RUNTIME_RESOURCES'] = '1'; + self::ensureKernelShutdown(); + self::bootKernel(); + if ($this->isMongoDB()) { + $this->markTestSkipped('Doctrine ORM only.'); + } + + $this->recreateSchema([ResourceDefinition::class, AttributeDefinition::class, EntityRow::class, AttributeValue::class, Generation::class]); + static::getContainer()->get(DefinitionProvider::class)->publish(function (EntityManagerInterface $manager): void { + $author = new ResourceDefinition('author', 'Author'); + new AttributeDefinition($author, 'name', 'string', required: true); + new AttributeDefinition($author, 'birthDate', 'datetime'); + new AttributeDefinition($author, 'books', 'reference', collection: true, options: ['target' => 'book']); + $book = new ResourceDefinition('book', 'Book'); + new AttributeDefinition($book, 'title', 'string', required: true, options: ['maxLength' => 255]); + new AttributeDefinition($book, 'isbn', 'string'); + new AttributeDefinition($book, 'price', 'float'); + new AttributeDefinition($book, 'genre', 'enum', options: ['values' => ['novel', 'essay', 'poetry']], filterable: true); + new AttributeDefinition($book, 'available', 'boolean'); + new AttributeDefinition($book, 'author', 'reference', options: ['target' => 'author'], filterable: true); + $manager->persist($author); + $manager->persist($book); + $manager->flush(); + + $this->row($manager, $author, ['name' => 'Ursula K. Le Guin', 'birthDate' => new \DateTimeImmutable('1929-10-21'), 'books' => [3]]); + $this->row($manager, $author, ['name' => 'Italo Calvino', 'birthDate' => new \DateTimeImmutable('1923-10-15'), 'books' => [4]]); + $this->row($manager, $book, ['title' => 'The Dispossessed', 'isbn' => '9780061054884', 'price' => 9.99, 'genre' => 'novel', 'available' => true, 'author' => 1]); + $this->row($manager, $book, ['title' => 'Six Memos for the Next Millennium', 'price' => 14.5, 'genre' => 'essay', 'available' => false, 'author' => 2]); + }); + self::ensureKernelShutdown(); + self::invalidateMetadataPools(); + } + + protected function tearDown(): void + { + self::ensureKernelShutdown(); + unset($_SERVER['RUNTIME_RESOURCES']); + parent::tearDown(); + } + + public function testGetItemEmbedsReference(): void + { + $client = self::createClient(); + $client->request('POST', '/runtime/book', ['headers' => self::JSONLD, 'json' => ['title' => 'The Left Hand of Darkness', 'author' => '/runtime/author/1']]); + $this->assertResponseStatusCodeSame(201); + $client->request('PATCH', '/runtime/author/1', ['headers' => ['Content-Type' => 'application/merge-patch+json', 'Accept' => 'application/ld+json'], 'json' => ['books' => ['/runtime/book/3', '/runtime/book/5']]]); + $this->assertResponseIsSuccessful(); + + $json = $client->request('GET', '/runtime/book/3', ['headers' => self::JSONLD])->toArray(); + + $this->assertResponseIsSuccessful(); + $this->assertSame('/contexts/Book', $json['@context']); + $this->assertSame('/runtime/book/3', $json['@id']); + $this->assertSame('Book', $json['@type']); + $this->assertSame('The Dispossessed', $json['title']); + $this->assertSame('9780061054884', $json['isbn']); + $this->assertSame(9.99, $json['price']); + $this->assertSame('novel', $json['genre']); + $this->assertTrue($json['available']); + $this->assertSame(['@id' => '/runtime/author/1', '@type' => 'Author', 'id' => 1, 'name' => 'Ursula K. Le Guin', 'birthDate' => '1929-10-21T00:00:00+00:00', 'books' => ['/runtime/book/3', '/runtime/book/5']], $json['author']); + } + + public function testGetCollectionIsScopedToResource(): void + { + $json = self::createClient()->request('GET', '/runtime/book', ['headers' => self::JSONLD])->toArray(); + + $this->assertResponseIsSuccessful(); + $this->assertSame('/runtime/book', $json['@id']); + $this->assertSame(2, $json['hydra:totalItems']); + $this->assertSame(['/runtime/book/3', '/runtime/book/4'], array_column($json['hydra:member'], '@id')); + $this->assertSame(['Book', 'Book'], array_column($json['hydra:member'], '@type')); + $this->assertSame(['Ursula K. Le Guin', 'Italo Calvino'], array_column(array_column($json['hydra:member'], 'author'), 'name')); + } + + public function testQueryCountDoesNotDependOnItemCount(): void + { + $client = self::createClient(); + $counts = []; + foreach (['/runtime/book/3', '/runtime/book?itemsPerPage=1', '/runtime/book', '/runtime/author'] as $uri) { + $client->enableProfiler(); + $client->request('GET', $uri, ['headers' => self::JSONLD]); + $this->assertResponseIsSuccessful(); + $collector = $client->getProfile()->getCollector('db'); + $this->assertInstanceOf(DoctrineDataCollector::class, $collector); + $counts[$uri] = \count($collector->getQueries()['default']); + } + + $this->assertSame(['/runtime/book/3' => 5, '/runtime/book?itemsPerPage=1' => 6, '/runtime/book' => 6, '/runtime/author' => 6], $counts); + } + + public function testUnknownResourceIs404(): void + { + $client = self::createClient(); + $client->request('GET', '/runtime/publisher', ['headers' => self::JSONLD]); + $this->assertResponseStatusCodeSame(404); + $client->request('GET', '/runtime/author/3', ['headers' => self::JSONLD]); + $this->assertResponseStatusCodeSame(404); + } + + public function testPost(): void + { + $client = self::createClient(); + $json = $client->request('POST', '/runtime/book', ['headers' => self::JSONLD, 'json' => ['title' => 'The Lathe of Heaven', 'genre' => 'novel', 'price' => 12, 'author' => '/runtime/author/1']])->toArray(); + + $this->assertResponseStatusCodeSame(201); + $this->assertSame('/runtime/book/5', $json['@id']); + $this->assertSame('The Lathe of Heaven', $json['title']); + $this->assertSame(12, $json['price']); + $this->assertNull($json['isbn']); + $this->assertSame('Ursula K. Le Guin', $json['author']['name']); + + $json = $client->request('GET', '/runtime/book/5', ['headers' => self::JSONLD])->toArray(); + $this->assertSame('The Lathe of Heaven', $json['title']); + $this->assertSame('/runtime/author/1', $json['author']['@id']); + } + + public function testPutReplaces(): void + { + $client = self::createClient(); + $json = $client->request('PUT', '/runtime/book/3', ['headers' => self::JSONLD, 'json' => ['title' => 'The Dispossessed: An Ambiguous Utopia', 'genre' => 'novel', 'author' => '/runtime/author/2']])->toArray(); + + $this->assertResponseIsSuccessful(); + $this->assertSame('/runtime/book/3', $json['@id']); + $this->assertSame('The Dispossessed: An Ambiguous Utopia', $json['title']); + $this->assertNull($json['isbn']); + $this->assertSame('/runtime/author/2', $json['author']['@id']); + + $json = $client->request('GET', '/runtime/book/3', ['headers' => self::JSONLD])->toArray(); + $this->assertNull($json['price']); + $this->assertSame('Italo Calvino', $json['author']['name']); + } + + public function testPatchMergesScalar(): void + { + $client = self::createClient(); + $client->request('PATCH', '/runtime/book/3', ['headers' => ['Content-Type' => 'application/merge-patch+json', 'Accept' => 'application/ld+json'], 'json' => ['price' => 12.5]]); + $this->assertResponseIsSuccessful(); + + $json = $client->request('GET', '/runtime/book/3', ['headers' => self::JSONLD])->toArray(); + $this->assertSame(12.5, $json['price']); + $this->assertSame('The Dispossessed', $json['title']); + $this->assertSame('9780061054884', $json['isbn']); + $this->assertSame('novel', $json['genre']); + $this->assertTrue($json['available']); + $this->assertSame('/runtime/author/1', $json['author']['@id']); + } + + public function testDelete(): void + { + $client = self::createClient(); + $client->request('DELETE', '/runtime/book/4'); + $this->assertResponseStatusCodeSame(204); + + $client->request('GET', '/runtime/book/4', ['headers' => self::JSONLD]); + $this->assertResponseStatusCodeSame(404); + $client->request('GET', '/runtime/author/2', ['headers' => self::JSONLD]); + $this->assertResponseIsSuccessful(); + $client->request('DELETE', '/runtime/book/2'); + $this->assertResponseStatusCodeSame(404); + } + + /** + * @param array $book + */ + #[DataProvider('invalidBooks')] + public function testInvalidBookIs422(array $book, string $propertyPath): void + { + $response = self::createClient()->request('POST', '/runtime/book', ['headers' => self::JSONLD, 'json' => $book]); + + $this->assertResponseStatusCodeSame(422); + $this->assertSame([$propertyPath], array_column($response->toArray(false)['violations'], 'propertyPath')); + } + + public static function invalidBooks(): iterable + { + yield 'missing title' => [['genre' => 'novel'], 'title']; + yield 'too long title' => [['title' => str_repeat('a', 256)], 'title']; + yield 'unknown genre' => [['title' => 'Earthsea', 'genre' => 'novella'], 'genre']; + yield 'book IRI whose id is an author' => [['title' => 'Earthsea', 'author' => '/runtime/book/1'], 'author']; + yield 'book IRI in author' => [['title' => 'Earthsea', 'author' => '/runtime/book/3'], 'author']; + yield 'unresolvable IRI' => [['title' => 'Earthsea', 'author' => '/runtime/author/999'], 'author']; + } + + public function testFilterByEnum(): void + { + $json = self::createClient()->request('GET', '/runtime/book?genre=novel', ['headers' => self::JSONLD])->toArray(); + + $this->assertResponseIsSuccessful(); + $this->assertSame(['/runtime/book/3'], array_column($json['hydra:member'], '@id')); + } + + public function testFilterByReference(): void + { + $client = self::createClient(); + $json = $client->request('GET', '/runtime/book?author=/runtime/author/2', ['headers' => self::JSONLD])->toArray(); + $this->assertResponseIsSuccessful(); + $this->assertSame(['/runtime/book/4'], array_column($json['hydra:member'], '@id')); + + $json = $client->request('GET', '/runtime/book?author=/runtime/book/3', ['headers' => self::JSONLD])->toArray(); + $this->assertResponseIsSuccessful(); + $this->assertSame([], $json['hydra:member']); + } + + public function testOpenApi(): void + { + $openApi = self::createClient()->request('GET', '/docs', ['headers' => ['Accept' => 'application/vnd.openapi+json']])->toArray(); + + $this->assertResponseIsSuccessful(); + $this->assertSame(['/runtime/author', '/runtime/author/{id}', '/runtime/book', '/runtime/book/{id}'], $this->runtimePaths($openApi)); + $this->assertSame(['id'], array_column($openApi['paths']['/runtime/book/{id}']['get']['parameters'], 'name')); + $this->assertSame(['page', 'itemsPerPage', 'pagination', 'partial', 'genre', 'author'], array_column($openApi['paths']['/runtime/book']['get']['parameters'], 'name')); + + $book = $openApi['components']['schemas']['Book']; + $this->assertSame(['title'], $book['required']); + $this->assertSame('string', $book['properties']['title']['type']); + $this->assertSame(255, $book['properties']['title']['maxLength']); + $this->assertSame(['number', 'null'], $book['properties']['price']['type']); + $this->assertSame(['boolean', 'null'], $book['properties']['available']['type']); + $this->assertSame(['novel', 'essay', 'poetry'], $book['properties']['genre']['enum']); + $this->assertSame([['$ref' => '#/components/schemas/Author'], ['type' => 'null']], $book['properties']['author']['anyOf']); + $this->assertSame(['name'], $openApi['components']['schemas']['Author']['required']); + $this->assertSame('date-time', $openApi['components']['schemas']['Author']['properties']['birthDate']['format']); + } + + public function testPublishIsPickedUpWithoutReboot(): void + { + $client = self::createClient(); + $client->disableReboot(); + $client->request('GET', '/runtime/book/3', ['headers' => self::JSONLD]); + $this->assertResponseIsSuccessful(); + $definitions = static::getContainer()->get(DefinitionProvider::class); + $resources = static::getContainer()->get(RuntimeResources::class); + + $definitions->publish(static function (EntityManagerInterface $manager): void { + $publisher = new ResourceDefinition('publisher', 'Publisher'); + new AttributeDefinition($publisher, 'name', 'string', required: true); + $manager->persist($publisher); + }); + + $json = $client->request('POST', '/runtime/publisher', ['headers' => self::JSONLD, 'json' => ['name' => 'Harper & Row']])->toArray(); + $this->assertResponseStatusCodeSame(201); + $this->assertSame('Publisher', $json['@type']); + $publisher = $resources->classOf('publisher'); + $book = $resources->classOf('book'); + $client->request('GET', '/docs', ['headers' => ['Accept' => 'application/vnd.openapi+json']]); + $this->assertResponseIsSuccessful(); + + $definitions->publish(static function (EntityManagerInterface $manager): void { + new AttributeDefinition($manager->getRepository(ResourceDefinition::class)->findOneBy(['name' => 'book']), 'pages', 'integer'); + }); + + $json = $client->request('GET', '/runtime/book/3', ['headers' => self::JSONLD])->toArray(); + $this->assertResponseIsSuccessful(); + $this->assertArrayHasKey('pages', $json); + $this->assertNotSame($book, $resources->classOf('book')); + $this->assertSame($publisher, $resources->classOf('publisher')); + $openApi = $client->request('GET', '/docs', ['headers' => ['Accept' => 'application/vnd.openapi+json']])->toArray(); + $this->assertArrayHasKey('pages', $openApi['components']['schemas']['Book']['properties']); + + $this->assertSame(0, $this->metadataCacheMisses($client, '/runtime/publisher/5')); + $this->assertGreaterThan(0, $this->metadataCacheMisses($client, '/runtime/author/1')); + } + + public function testDefinitionSecurity(): void + { + self::bootKernel(); + static::getContainer()->get(DefinitionProvider::class)->publish(static function (EntityManagerInterface $manager): void { + $secret = new ResourceDefinition('secret', 'Secret', security: "is_granted('ROLE_ADMIN')"); + new AttributeDefinition($secret, 'code', 'string'); + $manager->persist($secret); + }); + self::ensureKernelShutdown(); + + $client = self::createClient(); + $client->request('GET', '/runtime/secret', ['headers' => self::JSONLD]); + $this->assertResponseStatusCodeSame(401); + $client->request('GET', '/runtime/secret', ['headers' => self::JSONLD, 'auth_basic' => ['dunglas', 'kevin']]); + $this->assertResponseStatusCodeSame(403); + $client->request('GET', '/runtime/secret', ['headers' => self::JSONLD, 'auth_basic' => ['admin', 'kitten']]); + $this->assertResponseIsSuccessful(); + } + + public function testWorkerModeDoesNotLeakProperties(): void + { + $client = self::createClient(); + $client->disableReboot(); + + foreach (['/runtime/book/3', '/runtime/author/1', '/runtime/book', '/runtime/author/2', '/runtime/book/4'] as $uri) { + $json = $client->request('GET', $uri, ['headers' => self::JSONLD])->toArray(); + $this->assertResponseIsSuccessful(); + foreach ($json['hydra:member'] ?? [$json] as $member) { + unset($member['@context']); + if ('Book' === $member['@type']) { + $this->assertSame(['@id', '@type', 'id', 'title', 'isbn', 'price', 'genre', 'available', 'author'], array_keys($member), $uri); + $member = $member['author']; + } + $this->assertSame(['@id', '@type', 'id', 'name', 'birthDate', 'books'], array_keys($member), $uri); + } + } + } + + public function testInvalidDefinitionsNeverBreakTheApi(): void + { + self::bootKernel(); + static::getContainer()->get(DefinitionProvider::class)->publish(static function (EntityManagerInterface $manager): void { + foreach (['Magazine', 'with_underscore', '1book', 'headers'] as $name) { + $manager->persist(new ResourceDefinition($name)); + } + new AttributeDefinition($manager->getRepository(ResourceDefinition::class)->findOneBy(['name' => 'author']), 'id', 'string'); + new AttributeDefinition($manager->getRepository(ResourceDefinition::class)->findOneBy(['name' => 'author']), 'agent', 'reference', options: ['target' => 'headers']); + }); + self::ensureKernelShutdown(); + + $client = self::createClient(); + $openApi = $client->request('GET', '/docs', ['headers' => ['Accept' => 'application/vnd.openapi+json']])->toArray(); + $this->assertResponseIsSuccessful(); + $this->assertSame(['/runtime/author', '/runtime/author/{id}', '/runtime/book', '/runtime/book/{id}'], $this->runtimePaths($openApi)); + $this->assertSame(['id', 'name', 'birthDate', 'books'], array_keys($openApi['components']['schemas']['Author']['properties'])); + + foreach (['Magazine', 'with_underscore', '1book', 'headers'] as $name) { + $client->request('GET', '/runtime/'.$name, ['headers' => self::JSONLD]); + $this->assertResponseStatusCodeSame(404, $name); + } + $client->request('GET', '/runtime/author/1', ['headers' => self::JSONLD]); + $this->assertResponseIsSuccessful(); + + $client->request('GET', '/redirect_to_foobar'); + $this->assertResponseStatusCodeSame(301); + + $resources = static::getContainer()->get(RuntimeResources::class); + $this->assertNull($resources->classOf('headers')); + $this->assertNull($resources->classOf('with_underscore')); + $this->assertTrue(class_exists((string) $resources->classOf('book'))); + } + + private function metadataCacheMisses(Client $client, string $uri): int + { + $client->enableProfiler(); + $client->request('GET', $uri, ['headers' => self::JSONLD]); + $this->assertResponseIsSuccessful(); + $collector = $client->getProfile()->getCollector('cache'); + $this->assertInstanceOf(CacheDataCollector::class, $collector); + + return array_sum(array_map(static fn (array $statistics): int => $statistics['misses'], array_intersect_key($collector->getStatistics(), array_flip(['api_platform.cache.metadata.resource_collection', 'api_platform.cache.metadata.property'])))); + } + + /** + * @param array $openApi + * + * @return list + */ + private function runtimePaths(array $openApi): array + { + $paths = array_values(array_filter(array_keys($openApi['paths']), static fn (string $path): bool => str_starts_with($path, '/runtime/'))); + sort($paths); + + return $paths; + } + + /** + * @param array $values + */ + private function row(EntityManagerInterface $manager, ResourceDefinition $definition, array $values): void + { + $row = new EntityRow($definition); + $row->replaceValues($values); + $manager->persist($row); + $manager->flush(); + } +} diff --git a/tests/Functional/RuntimeResourceMongoDbTest.php b/tests/Functional/RuntimeResourceMongoDbTest.php new file mode 100644 index 00000000000..36d326e8cfa --- /dev/null +++ b/tests/Functional/RuntimeResourceMongoDbTest.php @@ -0,0 +1,382 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace ApiPlatform\Tests\Functional; + +use ApiPlatform\Test\ApiTestCase; +use ApiPlatform\Test\Client; +use ApiPlatform\Tests\Fixtures\TestBundle\ApiResource\Headers; +use ApiPlatform\Tests\Fixtures\TestBundle\Document\RuntimeResource\Document; +use ApiPlatform\Tests\Fixtures\TestBundle\Document\RuntimeResource\Generation; +use ApiPlatform\Tests\Fixtures\TestBundle\Document\RuntimeResource\ResourceDefinition; +use ApiPlatform\Tests\Fixtures\TestBundle\RuntimeResource\DefinitionProvider; +use ApiPlatform\Tests\Fixtures\TestBundle\RuntimeResource\RuntimeResources; +use ApiPlatform\Tests\RecreateSchemaTrait; +use ApiPlatform\Tests\SetupClassResourcesTrait; +use Doctrine\ODM\MongoDB\DocumentManager; +use MongoDB\BSON\UTCDateTime; +use PHPUnit\Framework\Attributes\DataProvider; +use Symfony\Component\Cache\DataCollector\CacheDataCollector; + +final class RuntimeResourceMongoDbTest extends ApiTestCase +{ + use RecreateSchemaTrait; + use SetupClassResourcesTrait; + + protected static ?bool $alwaysBootKernel = false; + + private const JSONLD = ['Content-Type' => 'application/ld+json', 'Accept' => 'application/ld+json']; + + public static function getResources(): array + { + return [Headers::class]; + } + + protected function setUp(): void + { + $_SERVER['RUNTIME_RESOURCES'] = '1'; + self::ensureKernelShutdown(); + self::bootKernel(); + if (!$this->isMongoDB()) { + $this->markTestSkipped('Doctrine MongoDB ODM only.'); + } + + $this->recreateSchema([ResourceDefinition::class, Document::class, Generation::class]); + static::getContainer()->get(DefinitionProvider::class)->publish(static function (DocumentManager $manager): void { + $manager->persist((new ResourceDefinition('author', 'Author')) + ->addAttribute('name', 'string', required: true) + ->addAttribute('birthDate', 'datetime') + ->addAttribute('books', 'reference', collection: true, options: ['target' => 'book'])); + $manager->persist((new ResourceDefinition('book', 'Book')) + ->addAttribute('title', 'string', required: true, options: ['maxLength' => 255]) + ->addAttribute('isbn', 'string') + ->addAttribute('price', 'float') + ->addAttribute('genre', 'enum', options: ['values' => ['novel', 'essay', 'poetry']], filterable: true) + ->addAttribute('available', 'boolean') + ->addAttribute('author', 'reference', options: ['target' => 'author'], filterable: true)); + $manager->persist(new Document('author', ['name' => 'Ursula K. Le Guin', 'birthDate' => new UTCDateTime((new \DateTimeImmutable('1929-10-21'))->getTimestamp() * 1000), 'books' => [3]])); + $manager->persist(new Document('author', ['name' => 'Italo Calvino', 'birthDate' => new UTCDateTime((new \DateTimeImmutable('1923-10-15'))->getTimestamp() * 1000), 'books' => [4]])); + $manager->persist(new Document('book', ['title' => 'The Dispossessed', 'isbn' => '9780061054884', 'price' => 9.99, 'genre' => 'novel', 'available' => true, 'author' => 1])); + $manager->persist(new Document('book', ['title' => 'Six Memos for the Next Millennium', 'price' => 14.5, 'genre' => 'essay', 'available' => false, 'author' => 2])); + }); + self::ensureKernelShutdown(); + self::invalidateMetadataPools(); + } + + protected function tearDown(): void + { + self::ensureKernelShutdown(); + unset($_SERVER['RUNTIME_RESOURCES']); + parent::tearDown(); + } + + public function testGetItemEmbedsReference(): void + { + $client = self::createClient(); + $client->request('POST', '/runtime/book', ['headers' => self::JSONLD, 'json' => ['title' => 'The Left Hand of Darkness', 'author' => '/runtime/author/1']]); + $this->assertResponseStatusCodeSame(201); + $client->request('PATCH', '/runtime/author/1', ['headers' => ['Content-Type' => 'application/merge-patch+json', 'Accept' => 'application/ld+json'], 'json' => ['books' => ['/runtime/book/3', '/runtime/book/5']]]); + $this->assertResponseIsSuccessful(); + + $json = $client->request('GET', '/runtime/book/3', ['headers' => self::JSONLD])->toArray(); + + $this->assertResponseIsSuccessful(); + $this->assertSame('/contexts/Book', $json['@context']); + $this->assertSame('/runtime/book/3', $json['@id']); + $this->assertSame('Book', $json['@type']); + $this->assertSame('The Dispossessed', $json['title']); + $this->assertSame('9780061054884', $json['isbn']); + $this->assertSame(9.99, $json['price']); + $this->assertSame('novel', $json['genre']); + $this->assertTrue($json['available']); + $this->assertSame(['@id' => '/runtime/author/1', '@type' => 'Author', 'id' => 1, 'name' => 'Ursula K. Le Guin', 'birthDate' => '1929-10-21T00:00:00+00:00', 'books' => ['/runtime/book/3', '/runtime/book/5']], $json['author']); + } + + public function testGetCollectionIsScopedToResource(): void + { + $json = self::createClient()->request('GET', '/runtime/book', ['headers' => self::JSONLD])->toArray(); + + $this->assertResponseIsSuccessful(); + $this->assertSame('/runtime/book', $json['@id']); + $this->assertSame(2, $json['hydra:totalItems']); + $this->assertSame(['/runtime/book/3', '/runtime/book/4'], array_column($json['hydra:member'], '@id')); + $this->assertSame(['Book', 'Book'], array_column($json['hydra:member'], '@type')); + $this->assertSame(['Ursula K. Le Guin', 'Italo Calvino'], array_column(array_column($json['hydra:member'], 'author'), 'name')); + } + + public function testUnknownResourceIs404(): void + { + $client = self::createClient(); + $client->request('GET', '/runtime/publisher', ['headers' => self::JSONLD]); + $this->assertResponseStatusCodeSame(404); + $client->request('GET', '/runtime/author/3', ['headers' => self::JSONLD]); + $this->assertResponseStatusCodeSame(404); + } + + public function testPost(): void + { + $client = self::createClient(); + $json = $client->request('POST', '/runtime/book', ['headers' => self::JSONLD, 'json' => ['title' => 'The Lathe of Heaven', 'genre' => 'novel', 'price' => 12, 'author' => '/runtime/author/1']])->toArray(); + + $this->assertResponseStatusCodeSame(201); + $this->assertSame('/runtime/book/5', $json['@id']); + $this->assertSame('The Lathe of Heaven', $json['title']); + $this->assertSame(12, $json['price']); + $this->assertNull($json['isbn']); + $this->assertSame('Ursula K. Le Guin', $json['author']['name']); + + $json = $client->request('GET', '/runtime/book/5', ['headers' => self::JSONLD])->toArray(); + $this->assertSame('The Lathe of Heaven', $json['title']); + $this->assertSame('/runtime/author/1', $json['author']['@id']); + } + + public function testPutReplaces(): void + { + $client = self::createClient(); + $json = $client->request('PUT', '/runtime/book/3', ['headers' => self::JSONLD, 'json' => ['title' => 'The Dispossessed: An Ambiguous Utopia', 'genre' => 'novel', 'author' => '/runtime/author/2']])->toArray(); + + $this->assertResponseIsSuccessful(); + $this->assertSame('/runtime/book/3', $json['@id']); + $this->assertSame('The Dispossessed: An Ambiguous Utopia', $json['title']); + $this->assertNull($json['isbn']); + $this->assertSame('/runtime/author/2', $json['author']['@id']); + + $json = $client->request('GET', '/runtime/book/3', ['headers' => self::JSONLD])->toArray(); + $this->assertNull($json['price']); + $this->assertSame('Italo Calvino', $json['author']['name']); + } + + public function testPatchMergesScalar(): void + { + $client = self::createClient(); + $client->request('PATCH', '/runtime/book/3', ['headers' => ['Content-Type' => 'application/merge-patch+json', 'Accept' => 'application/ld+json'], 'json' => ['price' => 12.5]]); + $this->assertResponseIsSuccessful(); + + $json = $client->request('GET', '/runtime/book/3', ['headers' => self::JSONLD])->toArray(); + $this->assertSame(12.5, $json['price']); + $this->assertSame('The Dispossessed', $json['title']); + $this->assertSame('9780061054884', $json['isbn']); + $this->assertSame('novel', $json['genre']); + $this->assertTrue($json['available']); + $this->assertSame('/runtime/author/1', $json['author']['@id']); + } + + public function testDelete(): void + { + $client = self::createClient(); + $client->request('DELETE', '/runtime/book/4'); + $this->assertResponseStatusCodeSame(204); + + $client->request('GET', '/runtime/book/4', ['headers' => self::JSONLD]); + $this->assertResponseStatusCodeSame(404); + $client->request('GET', '/runtime/author/2', ['headers' => self::JSONLD]); + $this->assertResponseIsSuccessful(); + $client->request('DELETE', '/runtime/book/2'); + $this->assertResponseStatusCodeSame(404); + } + + /** + * @param array $book + */ + #[DataProvider('invalidBooks')] + public function testInvalidBookIs422(array $book, string $propertyPath): void + { + $response = self::createClient()->request('POST', '/runtime/book', ['headers' => self::JSONLD, 'json' => $book]); + + $this->assertResponseStatusCodeSame(422); + $this->assertSame([$propertyPath], array_column($response->toArray(false)['violations'], 'propertyPath')); + } + + public static function invalidBooks(): iterable + { + yield 'missing title' => [['genre' => 'novel'], 'title']; + yield 'too long title' => [['title' => str_repeat('a', 256)], 'title']; + yield 'unknown genre' => [['title' => 'Earthsea', 'genre' => 'novella'], 'genre']; + yield 'book IRI whose id is an author' => [['title' => 'Earthsea', 'author' => '/runtime/book/1'], 'author']; + yield 'book IRI in author' => [['title' => 'Earthsea', 'author' => '/runtime/book/3'], 'author']; + yield 'unresolvable IRI' => [['title' => 'Earthsea', 'author' => '/runtime/author/999'], 'author']; + } + + public function testFilterByEnum(): void + { + $json = self::createClient()->request('GET', '/runtime/book?genre=novel', ['headers' => self::JSONLD])->toArray(); + + $this->assertResponseIsSuccessful(); + $this->assertSame(['/runtime/book/3'], array_column($json['hydra:member'], '@id')); + } + + public function testFilterByReference(): void + { + $client = self::createClient(); + $json = $client->request('GET', '/runtime/book?author=/runtime/author/2', ['headers' => self::JSONLD])->toArray(); + $this->assertResponseIsSuccessful(); + $this->assertSame(['/runtime/book/4'], array_column($json['hydra:member'], '@id')); + + $json = $client->request('GET', '/runtime/book?author=/runtime/book/3', ['headers' => self::JSONLD])->toArray(); + $this->assertResponseIsSuccessful(); + $this->assertSame([], $json['hydra:member']); + } + + public function testOpenApi(): void + { + $openApi = self::createClient()->request('GET', '/docs', ['headers' => ['Accept' => 'application/vnd.openapi+json']])->toArray(); + + $this->assertResponseIsSuccessful(); + $this->assertSame(['/runtime/author', '/runtime/author/{id}', '/runtime/book', '/runtime/book/{id}'], $this->runtimePaths($openApi)); + $this->assertSame(['id'], array_column($openApi['paths']['/runtime/book/{id}']['get']['parameters'], 'name')); + $this->assertSame(['page', 'itemsPerPage', 'pagination', 'partial', 'genre', 'author'], array_column($openApi['paths']['/runtime/book']['get']['parameters'], 'name')); + + $book = $openApi['components']['schemas']['Book']; + $this->assertSame(['title'], $book['required']); + $this->assertSame('string', $book['properties']['title']['type']); + $this->assertSame(255, $book['properties']['title']['maxLength']); + $this->assertSame(['number', 'null'], $book['properties']['price']['type']); + $this->assertSame(['boolean', 'null'], $book['properties']['available']['type']); + $this->assertSame(['novel', 'essay', 'poetry'], $book['properties']['genre']['enum']); + $this->assertSame([['$ref' => '#/components/schemas/Author'], ['type' => 'null']], $book['properties']['author']['anyOf']); + $this->assertSame(['name'], $openApi['components']['schemas']['Author']['required']); + $this->assertSame('date-time', $openApi['components']['schemas']['Author']['properties']['birthDate']['format']); + } + + public function testPublishIsPickedUpWithoutReboot(): void + { + $client = self::createClient(); + $client->disableReboot(); + $client->request('GET', '/runtime/book/3', ['headers' => self::JSONLD]); + $this->assertResponseIsSuccessful(); + $definitions = static::getContainer()->get(DefinitionProvider::class); + $resources = static::getContainer()->get(RuntimeResources::class); + + $definitions->publish(static function (DocumentManager $manager): void { + $manager->persist((new ResourceDefinition('publisher', 'Publisher'))->addAttribute('name', 'string', required: true)); + }); + + $json = $client->request('POST', '/runtime/publisher', ['headers' => self::JSONLD, 'json' => ['name' => 'Harper & Row']])->toArray(); + $this->assertResponseStatusCodeSame(201); + $this->assertSame('Publisher', $json['@type']); + $publisher = $resources->classOf('publisher'); + $book = $resources->classOf('book'); + $client->request('GET', '/docs', ['headers' => ['Accept' => 'application/vnd.openapi+json']]); + $this->assertResponseIsSuccessful(); + + $definitions->publish(static function (DocumentManager $manager): void { + $manager->getRepository(ResourceDefinition::class)->findOneBy(['name' => 'book'])->addAttribute('pages', 'integer'); + }); + + $json = $client->request('GET', '/runtime/book/3', ['headers' => self::JSONLD])->toArray(); + $this->assertResponseIsSuccessful(); + $this->assertArrayHasKey('pages', $json); + $this->assertNotSame($book, $resources->classOf('book')); + $this->assertSame($publisher, $resources->classOf('publisher')); + $openApi = $client->request('GET', '/docs', ['headers' => ['Accept' => 'application/vnd.openapi+json']])->toArray(); + $this->assertArrayHasKey('pages', $openApi['components']['schemas']['Book']['properties']); + + $this->assertSame(0, $this->metadataCacheMisses($client, '/runtime/publisher/5')); + $this->assertGreaterThan(0, $this->metadataCacheMisses($client, '/runtime/author/1')); + } + + public function testDefinitionSecurity(): void + { + self::bootKernel(); + static::getContainer()->get(DefinitionProvider::class)->publish(static function (DocumentManager $manager): void { + $manager->persist((new ResourceDefinition('secret', 'Secret', security: "is_granted('ROLE_ADMIN')"))->addAttribute('code', 'string')); + }); + self::ensureKernelShutdown(); + + $client = self::createClient(); + $client->request('GET', '/runtime/secret', ['headers' => self::JSONLD]); + $this->assertResponseStatusCodeSame(401); + $client->request('GET', '/runtime/secret', ['headers' => self::JSONLD, 'auth_basic' => ['dunglas', 'kevin']]); + $this->assertResponseStatusCodeSame(403); + $client->request('GET', '/runtime/secret', ['headers' => self::JSONLD, 'auth_basic' => ['admin', 'kitten']]); + $this->assertResponseIsSuccessful(); + } + + public function testWorkerModeDoesNotLeakProperties(): void + { + $client = self::createClient(); + $client->disableReboot(); + + foreach (['/runtime/book/3', '/runtime/author/1', '/runtime/book', '/runtime/author/2', '/runtime/book/4'] as $uri) { + $json = $client->request('GET', $uri, ['headers' => self::JSONLD])->toArray(); + $this->assertResponseIsSuccessful(); + foreach ($json['hydra:member'] ?? [$json] as $member) { + unset($member['@context']); + if ('Book' === $member['@type']) { + $this->assertSame(['@id', '@type', 'id', 'title', 'isbn', 'price', 'genre', 'available', 'author'], array_keys($member), $uri); + $member = $member['author']; + } + $this->assertSame(['@id', '@type', 'id', 'name', 'birthDate', 'books'], array_keys($member), $uri); + } + } + } + + public function testInvalidDefinitionsNeverBreakTheApi(): void + { + self::bootKernel(); + static::getContainer()->get(DefinitionProvider::class)->publish(static function (DocumentManager $manager): void { + foreach (['Book', 'with_underscore', '1book', 'headers'] as $name) { + $manager->persist(new ResourceDefinition($name)); + } + $manager->getRepository(ResourceDefinition::class)->findOneBy(['name' => 'author']) + ->addAttribute('id', 'string') + ->addAttribute('agent', 'reference', options: ['target' => 'headers']); + }); + self::ensureKernelShutdown(); + + $client = self::createClient(); + $openApi = $client->request('GET', '/docs', ['headers' => ['Accept' => 'application/vnd.openapi+json']])->toArray(); + $this->assertResponseIsSuccessful(); + $this->assertSame(['/runtime/author', '/runtime/author/{id}', '/runtime/book', '/runtime/book/{id}'], $this->runtimePaths($openApi)); + $this->assertSame(['id', 'name', 'birthDate', 'books'], array_keys($openApi['components']['schemas']['Author']['properties'])); + + foreach (['Book', 'with_underscore', '1book', 'headers'] as $name) { + $client->request('GET', '/runtime/'.$name, ['headers' => self::JSONLD]); + $this->assertResponseStatusCodeSame(404, $name); + } + $client->request('GET', '/runtime/author/1', ['headers' => self::JSONLD]); + $this->assertResponseIsSuccessful(); + + $client->request('GET', '/redirect_to_foobar'); + $this->assertResponseStatusCodeSame(301); + + $resources = static::getContainer()->get(RuntimeResources::class); + $this->assertNull($resources->classOf('headers')); + $this->assertNull($resources->classOf('with_underscore')); + $this->assertTrue(class_exists((string) $resources->classOf('book'))); + } + + private function metadataCacheMisses(Client $client, string $uri): int + { + $client->enableProfiler(); + $client->request('GET', $uri, ['headers' => self::JSONLD]); + $this->assertResponseIsSuccessful(); + $collector = $client->getProfile()->getCollector('cache'); + $this->assertInstanceOf(CacheDataCollector::class, $collector); + + return array_sum(array_map(static fn (array $statistics): int => $statistics['misses'], array_intersect_key($collector->getStatistics(), array_flip(['api_platform.cache.metadata.resource_collection', 'api_platform.cache.metadata.property'])))); + } + + /** + * @param array $openApi + * + * @return list + */ + private function runtimePaths(array $openApi): array + { + $paths = array_values(array_filter(array_keys($openApi['paths']), static fn (string $path): bool => str_starts_with($path, '/runtime/'))); + sort($paths); + + return $paths; + } +} diff --git a/tests/Functional/Serializer/MergePatchMapsTest.php b/tests/Functional/Serializer/MergePatchMapsTest.php new file mode 100644 index 00000000000..e32878d16f5 --- /dev/null +++ b/tests/Functional/Serializer/MergePatchMapsTest.php @@ -0,0 +1,63 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace ApiPlatform\Tests\Functional\Serializer; + +use ApiPlatform\Test\ApiTestCase; +use ApiPlatform\Tests\Fixtures\TestBundle\ApiResource\Settings; +use ApiPlatform\Tests\SetupClassResourcesTrait; + +final class MergePatchMapsTest extends ApiTestCase +{ + use SetupClassResourcesTrait; + + protected static ?bool $alwaysBootKernel = false; + + public static function getResources(): array + { + return [Settings::class]; + } + + public function testMergePatchMergesMapWhenOptedIn(): void + { + $response = self::createClient()->request('PATCH', '/merge_patch_settings/1', [ + 'headers' => ['Content-Type' => 'application/merge-patch+json'], + 'json' => ['settings' => ['b' => null, 'c' => ['d' => 1]]], + ]); + + $this->assertResponseStatusCodeSame(200); + $this->assertSame(['a' => 1, 'c' => ['e' => 2, 'd' => 1]], $response->toArray()['settings']); + } + + public function testMergePatchValidatesMergedMap(): void + { + self::createClient()->request('PATCH', '/merge_patch_settings/1', [ + 'headers' => ['Content-Type' => 'application/merge-patch+json'], + 'json' => ['settings' => ['x' => 1]], + ]); + + $this->assertResponseStatusCodeSame(422); + $this->assertJsonContains(['violations' => [['propertyPath' => 'settings']]]); + } + + public function testMergePatchReplacesMapWithoutOptIn(): void + { + $response = self::createClient()->request('PATCH', '/merge_patch_settings/1/replace', [ + 'headers' => ['Content-Type' => 'application/merge-patch+json'], + 'json' => ['settings' => ['b' => null, 'c' => ['d' => 1]]], + ]); + + $this->assertResponseStatusCodeSame(200); + $this->assertSame(['b' => null, 'c' => ['d' => 1]], $response->toArray()['settings']); + } +} diff --git a/tests/Functional/Serializer/SharedRouteIriTest.php b/tests/Functional/Serializer/SharedRouteIriTest.php index 4585b40c05b..9790784cca1 100644 --- a/tests/Functional/Serializer/SharedRouteIriTest.php +++ b/tests/Functional/Serializer/SharedRouteIriTest.php @@ -13,10 +13,13 @@ namespace ApiPlatform\Tests\Functional\Serializer; +use ApiPlatform\Metadata\IriConverterInterface; use ApiPlatform\Test\ApiTestCase; use ApiPlatform\Tests\Fixtures\TestBundle\ApiResource\SharedRouteIri\CategoryProjection; use ApiPlatform\Tests\Fixtures\TestBundle\ApiResource\SharedRouteIri\CategoryResource; use ApiPlatform\Tests\Fixtures\TestBundle\ApiResource\SharedRouteIri\TopicResource; +use ApiPlatform\Tests\Fixtures\TestBundle\ApiResource\SharedRouteIri\VariableRouteAlpha; +use ApiPlatform\Tests\Fixtures\TestBundle\ApiResource\SharedRouteIri\VariableRouteBeta; use ApiPlatform\Tests\SetupClassResourcesTrait; final class SharedRouteIriTest extends ApiTestCase @@ -27,7 +30,7 @@ final class SharedRouteIriTest extends ApiTestCase public static function getResources(): array { - return [CategoryResource::class, CategoryProjection::class, TopicResource::class]; + return [CategoryResource::class, CategoryProjection::class, TopicResource::class, VariableRouteAlpha::class, VariableRouteBeta::class]; } public function testBorrowedRouteIriCanBeWrittenBackToTheSameRelation(): void @@ -60,4 +63,12 @@ public function testUnrelatedResourceIriIsRejected(): void self::assertResponseStatusCodeSame(400); self::assertJsonContains(['detail' => 'Invalid IRI "/shared_iri/topics/1".']); } + + public function testRouteSharedAcrossUriTemplatesIsNotBorrowedByTheExpectedClass(): void + { + $iriConverter = static::getContainer()->get('api_platform.iri_converter'); + \assert($iriConverter instanceof IriConverterInterface); + + $this->assertInstanceOf(VariableRouteAlpha::class, $iriConverter->getResourceFromIri('/shared_route_variable/alpha/1', ['resource_class' => VariableRouteBeta::class])); + } } diff --git a/tests/Functional/SharedRouteNameTest.php b/tests/Functional/SharedRouteNameTest.php new file mode 100644 index 00000000000..d3c5f4e325c --- /dev/null +++ b/tests/Functional/SharedRouteNameTest.php @@ -0,0 +1,53 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace ApiPlatform\Tests\Functional; + +use ApiPlatform\Metadata\HttpOperation; +use ApiPlatform\Metadata\IriConverterInterface; +use ApiPlatform\Metadata\Resource\Factory\ResourceMetadataCollectionFactoryInterface; +use ApiPlatform\Test\ApiTestCase; +use ApiPlatform\Tests\Fixtures\TestBundle\ApiResource\SharedRouteAlpha; +use ApiPlatform\Tests\Fixtures\TestBundle\ApiResource\SharedRouteBeta; +use ApiPlatform\Tests\SetupClassResourcesTrait; + +final class SharedRouteNameTest extends ApiTestCase +{ + use SetupClassResourcesTrait; + + protected static ?bool $alwaysBootKernel = false; + + public static function getResources(): array + { + return [SharedRouteAlpha::class, SharedRouteBeta::class]; + } + + public function testOperationsSharingARouteNameKeepDistinctNames(): void + { + $container = static::getContainer(); + $resourceMetadataCollectionFactory = $container->get('api_platform.metadata.resource.metadata_collection_factory'); + \assert($resourceMetadataCollectionFactory instanceof ResourceMetadataCollectionFactoryInterface); + $iriConverter = $container->get('api_platform.iri_converter'); + \assert($iriConverter instanceof IriConverterInterface); + + $alpha = $resourceMetadataCollectionFactory->create(SharedRouteAlpha::class)->getOperation('shared_route_alpha'); + $beta = $resourceMetadataCollectionFactory->create(SharedRouteBeta::class)->getOperation('shared_route_beta'); + + $this->assertInstanceOf(HttpOperation::class, $alpha); + $this->assertInstanceOf(HttpOperation::class, $beta); + $this->assertSame('shared_static_route', $alpha->getRouteName()); + $this->assertSame('shared_static_route', $beta->getRouteName()); + $this->assertSame('/shared_static_route', $iriConverter->getIriFromResource(new SharedRouteAlpha(), operation: $alpha)); + $this->assertSame('/shared_static_route', $iriConverter->getIriFromResource(new SharedRouteBeta(), operation: $beta)); + } +} diff --git a/tests/Symfony/Bundle/DependencyInjection/ConfigurationTest.php b/tests/Symfony/Bundle/DependencyInjection/ConfigurationTest.php index f0b05b72819..6de68695a35 100644 --- a/tests/Symfony/Bundle/DependencyInjection/ConfigurationTest.php +++ b/tests/Symfony/Bundle/DependencyInjection/ConfigurationTest.php @@ -211,6 +211,7 @@ private function runDefaultConfigTests(array $doctrineIntegrationsToLoad = ['orm 'enabled' => true, 'hub_url' => null, 'include_type' => false, + 'resolve_resource_objects' => false, ], 'asset_package' => null, 'openapi' => [