Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions phpstan.neon.dist
Original file line number Diff line number Diff line change
Expand Up @@ -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
8 changes: 7 additions & 1 deletion src/JsonSchema/DefinitionNameFactory.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand All @@ -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) {
Expand Down
12 changes: 12 additions & 0 deletions src/JsonSchema/Tests/DefinitionNameFactoryTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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')));
}
}
9 changes: 7 additions & 2 deletions src/Metadata/IdentifiersExtractor.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand Down Expand Up @@ -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);
Expand All @@ -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);
}
}
Expand Down
42 changes: 42 additions & 0 deletions src/Metadata/Tests/IdentifiersExtractorTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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;
Expand Down Expand Up @@ -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);
Expand Down
9 changes: 8 additions & 1 deletion src/OpenApi/Factory/OpenApiFactory.php
Original file line number Diff line number Diff line change
Expand Up @@ -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() ?? '', '/');
Expand Down Expand Up @@ -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();
Expand Down
87 changes: 85 additions & 2 deletions src/OpenApi/Tests/Factory/OpenApiFactoryTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand Down Expand Up @@ -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),
Expand Down Expand Up @@ -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];
Expand Down Expand Up @@ -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
*/
Expand Down
1 change: 1 addition & 0 deletions src/OpenApi/composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -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": {
Expand Down
62 changes: 62 additions & 0 deletions src/Serializer/AbstractItemNormalizer.php
Original file line number Diff line number Diff line change
Expand Up @@ -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 = [];
Expand Down Expand Up @@ -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)
Expand All @@ -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.
*
Expand Down
Loading
Loading