From 75486206a9ac8c6e1f578bc3ca4707f34470a3ca Mon Sep 17 00:00:00 2001 From: Elias Luhr Date: Sat, 10 Oct 2026 00:12:09 +0200 Subject: [PATCH 01/10] fix(openapi): drop property defaults their own schema rejects [*] API Platform derives `default` from the PHP initializer, so `private string $slug = '';` next to a slug Assert\Regex yields `default: ""` that the property's own `pattern` rejects. Form clients start from that default and show a validation error before anyone typed. InvalidDefaultSchemaDecorator removes such defaults (pattern, minLength, maxLength, enum), walking properties, nested objects and allOf/anyOf/oneOf. On by default, switch off with schema_default_cleanup.enabled: false. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 8 +- config/services_schema_default_cleanup.yaml | 17 +++ .../ApiPlatformUtilsExtension.php | 7 + src/DependencyInjection/Configuration.php | 11 ++ src/OpenApi/InvalidDefaultSchemaDecorator.php | 137 ++++++++++++++++++ .../ApiPlatformUtilsExtensionTest.php | 14 ++ .../InvalidDefaultSchemaDecoratorTest.php | 108 ++++++++++++++ 7 files changed, 301 insertions(+), 1 deletion(-) create mode 100644 config/services_schema_default_cleanup.yaml create mode 100644 src/OpenApi/InvalidDefaultSchemaDecorator.php create mode 100644 tests/OpenApi/InvalidDefaultSchemaDecoratorTest.php diff --git a/CHANGELOG.md b/CHANGELOG.md index 069553f..1aadeec 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,7 +1,13 @@ - + # Changelog +## Unreleased + +### Fixed + +- `InvalidDefaultSchemaDecorator` drops a property `default` from the JSON/OpenAPI schemas when the property schema itself rejects it (`pattern`, `minLength`, `maxLength`, `enum`). API Platform derives `default` from the PHP initializer, so `private string $slug = '';` next to a slug `#[Assert\Regex]` produced `default: ""` that its own `pattern` rejects, and form clients showed a validation error before anyone typed. Valid defaults are untouched; a pattern PHP cannot compile keeps its default. On by default, switch off with `schema_default_cleanup.enabled: false`. + ## 0.5.0 (2026-10-09) ### Added diff --git a/config/services_schema_default_cleanup.yaml b/config/services_schema_default_cleanup.yaml new file mode 100644 index 0000000..5c94e15 --- /dev/null +++ b/config/services_schema_default_cleanup.yaml @@ -0,0 +1,17 @@ +# file generated with AI assistance: Claude Code - 2026-10-10 00:15:00 UTC + +services: + _defaults: + autowire: false + autoconfigure: false + public: false + + # Drops property defaults that violate their own pattern/minLength/ + # maxLength/enum (e.g. `default: ""` next to a slug pattern). Priority 5 + # wraps below RelationFieldSchemaDecorator (10); the order does not + # matter for the result, the two touch different keys. + Dmstr\ApiPlatformUtils\OpenApi\InvalidDefaultSchemaDecorator: + decorates: 'api_platform.json_schema.schema_factory' + decoration_priority: 5 + arguments: + $decorated: '@.inner' diff --git a/src/DependencyInjection/ApiPlatformUtilsExtension.php b/src/DependencyInjection/ApiPlatformUtilsExtension.php index 2ea6441..52673de 100644 --- a/src/DependencyInjection/ApiPlatformUtilsExtension.php +++ b/src/DependencyInjection/ApiPlatformUtilsExtension.php @@ -50,6 +50,8 @@ public function load(array $configs, ContainerBuilder $container): void $container->setParameter('dmstr_api_platform_utils.stable_order.enabled', $config['stable_order']['enabled']); + $container->setParameter('dmstr_api_platform_utils.schema_default_cleanup.enabled', $config['schema_default_cleanup']['enabled']); + // Load service definitions $loader = new YamlFileLoader($container, new FileLocator(__DIR__ . '/../../config')); $loader->load('services.yaml'); @@ -75,6 +77,11 @@ public function load(array $configs, ContainerBuilder $container): void if ($config['stable_order']['enabled']) { $loader->load('services_stable_order.yaml'); } + + // On by default: it only removes defaults the schema itself rejects. + if ($config['schema_default_cleanup']['enabled']) { + $loader->load('services_schema_default_cleanup.yaml'); + } } public function getAlias(): string diff --git a/src/DependencyInjection/Configuration.php b/src/DependencyInjection/Configuration.php index 6ba26ae..a30001f 100644 --- a/src/DependencyInjection/Configuration.php +++ b/src/DependencyInjection/Configuration.php @@ -60,6 +60,17 @@ public function getConfigTreeBuilder(): TreeBuilder ->end() ->end() + // Invalid property defaults in JSON schemas + ->arrayNode('schema_default_cleanup') + ->addDefaultsIfNotSet() + ->children() + ->booleanNode('enabled') + ->defaultTrue() + ->info('Drop a property `default` from the JSON/OpenAPI schemas when the property schema itself rejects it (pattern, minLength, maxLength, enum), e.g. `default: ""` derived from `private string $slug = \'\'` next to a slug pattern') + ->end() + ->end() + ->end() + // Hydra Operations Subscriber ->arrayNode('hydra_operations') ->addDefaultsIfNotSet() diff --git a/src/OpenApi/InvalidDefaultSchemaDecorator.php b/src/OpenApi/InvalidDefaultSchemaDecorator.php new file mode 100644 index 0000000..19e4b4e --- /dev/null +++ b/src/OpenApi/InvalidDefaultSchemaDecorator.php @@ -0,0 +1,137 @@ +decorated->buildSchema( + $className, + $format, + $type, + $operation, + $schema, + $serializerContext, + $forceCollection, + ); + + $definitions = $schema->getDefinitions(); + foreach ($definitions as $key => $definition) { + $definitions[$key] = $this->cleanNode($definition); + } + + return $schema; + } + + /** + * Walks `properties` (nested objects included) and `allOf`/`anyOf`/`oneOf` + * branches, the places API Platform puts property schemas. + */ + private function cleanNode(mixed $node): mixed + { + if (!\is_array($node) && !$node instanceof \ArrayObject) { + return $node; + } + + if (isset($node['properties']) && (\is_array($node['properties']) || $node['properties'] instanceof \ArrayObject)) { + $properties = $node['properties']; + foreach ($properties as $name => $property) { + $properties[$name] = $this->cleanNode($this->dropInvalidDefault($property)); + } + $node['properties'] = $properties; + } + + foreach (['allOf', 'anyOf', 'oneOf'] as $keyword) { + if (isset($node[$keyword]) && \is_array($node[$keyword])) { + $branches = $node[$keyword]; + foreach ($branches as $index => $branch) { + $branches[$index] = $this->cleanNode($branch); + } + $node[$keyword] = $branches; + } + } + + return $node; + } + + private function dropInvalidDefault(mixed $property): mixed + { + if ((!\is_array($property) && !$property instanceof \ArrayObject) || !isset($property['default'])) { + return $property; + } + + if (!$this->violates($property, $property['default'])) { + return $property; + } + + unset($property['default']); + + return $property; + } + + private function violates(array|\ArrayObject $property, mixed $default): bool + { + if (isset($property['enum']) && \is_array($property['enum']) && !\in_array($default, $property['enum'], true)) { + return true; + } + + if (!\is_string($default)) { + return false; + } + + $length = mb_strlen($default); + if (isset($property['minLength']) && $length < (int) $property['minLength']) { + return true; + } + if (isset($property['maxLength']) && $length > (int) $property['maxLength']) { + return true; + } + + if (isset($property['pattern']) && \is_string($property['pattern'])) { + // JSON Schema patterns are ECMA-262 and unanchored; the delimiter + // is escaped, everything else is passed through as written. + $regex = '/' . str_replace('/', '\/', $property['pattern']) . '/u'; + $match = @preg_match($regex, $default); + if ($match === 0) { + return true; + } + // false: PHP cannot compile it — keep the default rather than guess + } + + return false; + } +} diff --git a/tests/DependencyInjection/ApiPlatformUtilsExtensionTest.php b/tests/DependencyInjection/ApiPlatformUtilsExtensionTest.php index 10b2484..e99a7d1 100644 --- a/tests/DependencyInjection/ApiPlatformUtilsExtensionTest.php +++ b/tests/DependencyInjection/ApiPlatformUtilsExtensionTest.php @@ -8,6 +8,7 @@ use Dmstr\ApiPlatformUtils\DependencyInjection\ApiPlatformUtilsExtension; use Dmstr\ApiPlatformUtils\Doctrine\Orm\Extension\StableOrderExtension; use Dmstr\ApiPlatformUtils\Metadata\AutoOrderResourceMetadataCollectionFactory; +use Dmstr\ApiPlatformUtils\OpenApi\InvalidDefaultSchemaDecorator; use PHPUnit\Framework\TestCase; use Symfony\Component\Config\Definition\Exception\InvalidConfigurationException; use Symfony\Component\DependencyInjection\ContainerBuilder; @@ -67,6 +68,19 @@ public function testStableOrderServiceTag(): void ); } + public function testSchemaDefaultCleanupIsOnByDefaultAndCanBeSwitchedOff(): void + { + $on = $this->load([self::BASE]); + self::assertTrue($on->hasDefinition(InvalidDefaultSchemaDecorator::class)); + self::assertSame( + 'api_platform.json_schema.schema_factory', + $on->getDefinition(InvalidDefaultSchemaDecorator::class)->getDecoratedService()[0], + ); + + $off = $this->load([self::BASE + ['schema_default_cleanup' => ['enabled' => false]]]); + self::assertFalse($off->hasDefinition(InvalidDefaultSchemaDecorator::class)); + } + public function testLabelCandidatesOfSeveralConfigsAreDeduplicated(): void { $container = $this->load([ diff --git a/tests/OpenApi/InvalidDefaultSchemaDecoratorTest.php b/tests/OpenApi/InvalidDefaultSchemaDecoratorTest.php new file mode 100644 index 0000000..b18b92f --- /dev/null +++ b/tests/OpenApi/InvalidDefaultSchemaDecoratorTest.php @@ -0,0 +1,108 @@ + 'string', 'pattern' => '^([a-z0-9]+(?:-[a-z0-9]+)*)$']; + + public function testDropsDefaultThatViolatesPatternInsideAllOf(): void + { + // the shape of a `.jsonld` read schema: properties inside allOf[1] + $properties = $this->build(['Node.jsonld' => ['allOf' => [ + ['$ref' => '#/definitions/HydraItemBaseSchema'], + ['type' => 'object', 'properties' => ['slug' => self::SLUG + ['default' => '']]], + ]]])['Node.jsonld']['allOf'][1]['properties']; + + self::assertSame(self::SLUG, $properties['slug']); + } + + public function testKeepsDefaultsTheSchemaAccepts(): void + { + $properties = $this->build(['Node' => ['type' => 'object', 'properties' => [ + 'slug' => self::SLUG + ['default' => 'home'], + 'title' => ['type' => 'string', 'default' => ''], + 'status' => ['type' => 'string', 'enum' => ['draft', 'published'], 'default' => 'draft'], + 'position' => ['type' => 'integer', 'minimum' => 0, 'default' => 0], + ]]])['Node']['properties']; + + self::assertSame('home', $properties['slug']['default']); + self::assertSame('', $properties['title']['default']); + self::assertSame('draft', $properties['status']['default']); + self::assertSame(0, $properties['position']['default']); + } + + public function testDropsDefaultsViolatingLengthAndEnum(): void + { + $properties = $this->build(['Node' => ['type' => 'object', 'properties' => [ + 'name' => ['type' => 'string', 'minLength' => 1, 'default' => ''], + 'code' => ['type' => 'string', 'maxLength' => 2, 'default' => 'abc'], + 'status' => ['type' => 'string', 'enum' => ['draft'], 'default' => 'gone'], + ]]])['Node']['properties']; + + self::assertArrayNotHasKey('default', $properties['name']); + self::assertArrayNotHasKey('default', $properties['code']); + self::assertArrayNotHasKey('default', $properties['status']); + } + + public function testWalksNestedObjectProperties(): void + { + $nested = $this->build(['Node' => ['type' => 'object', 'properties' => [ + 'meta' => ['type' => 'object', 'properties' => ['key' => self::SLUG + ['default' => '']]], + ]]])['Node']['properties']['meta']['properties']; + + self::assertArrayNotHasKey('default', $nested['key']); + } + + public function testKeepsDefaultWhenPhpCannotCompileThePattern(): void + { + // ECMA-only syntax PHP's PCRE rejects: keep rather than guess + $properties = $this->build(['Node' => ['type' => 'object', 'properties' => [ + 'odd' => ['type' => 'string', 'pattern' => '(?<=a', 'default' => ''], + ]]])['Node']['properties']; + + self::assertSame('', $properties['odd']['default']); + } + + public function testPatternWithSlashIsEscaped(): void + { + $properties = $this->build(['Node' => ['type' => 'object', 'properties' => [ + 'path' => ['type' => 'string', 'pattern' => '^/[a-z]+$', 'default' => '/home'], + 'bad' => ['type' => 'string', 'pattern' => '^/[a-z]+$', 'default' => ''], + ]]])['Node']['properties']; + + self::assertSame('/home', $properties['path']['default']); + self::assertArrayNotHasKey('default', $properties['bad']); + } + + /** + * @param array $definitions + */ + private function build(array $definitions): \ArrayObject + { + $inner = new class(new \ArrayObject($definitions)) implements SchemaFactoryInterface { + public function __construct(private readonly \ArrayObject $definitions) + { + } + + public function buildSchema(string $className, string $format = 'json', string $type = Schema::TYPE_OUTPUT, ?Operation $operation = null, ?Schema $schema = null, ?array $serializerContext = null, bool $forceCollection = false): Schema + { + $schema = new Schema(); + $schema->setDefinitions($this->definitions); + + return $schema; + } + }; + + return (new InvalidDefaultSchemaDecorator($inner))->buildSchema('Node')->getDefinitions(); + } +} From f2073e6db496be955cb4396be3bc8f624f68b7de Mon Sep 17 00:00:00 2001 From: "t.munk (workhorse)" Date: Thu, 26 Nov 2026 09:02:00 +0000 Subject: [PATCH 02/10] test(openapi): build schema fixtures in the shape API Platform delivers [*] Definitions and properties are ArrayObjects and the stubbed factory writes into the schema it is handed, like the real one. The uncompilable-pattern test uses [^], which ECMA accepts and PCRE rejects. Co-Authored-By: Claude Fable 5.2 --- .../InvalidDefaultSchemaDecoratorTest.php | 119 ++++++++++++++++-- 1 file changed, 110 insertions(+), 9 deletions(-) diff --git a/tests/OpenApi/InvalidDefaultSchemaDecoratorTest.php b/tests/OpenApi/InvalidDefaultSchemaDecoratorTest.php index b18b92f..08f7d60 100644 --- a/tests/OpenApi/InvalidDefaultSchemaDecoratorTest.php +++ b/tests/OpenApi/InvalidDefaultSchemaDecoratorTest.php @@ -65,12 +65,15 @@ public function testWalksNestedObjectProperties(): void public function testKeepsDefaultWhenPhpCannotCompileThePattern(): void { - // ECMA-only syntax PHP's PCRE rejects: keep rather than guess + // `[^]` is valid ECMA-262 (any character) but an unterminated class in + // PCRE: PHP cannot judge it, so the default stays rather than guess + self::assertFalse(@preg_match('/[^]/u', 'x')); + $properties = $this->build(['Node' => ['type' => 'object', 'properties' => [ - 'odd' => ['type' => 'string', 'pattern' => '(?<=a', 'default' => ''], + 'odd' => ['type' => 'string', 'pattern' => '[^]', 'default' => 'x'], ]]])['Node']['properties']; - self::assertSame('', $properties['odd']['default']); + self::assertSame('x', $properties['odd']['default']); } public function testPatternWithSlashIsEscaped(): void @@ -84,25 +87,123 @@ public function testPatternWithSlashIsEscaped(): void self::assertArrayNotHasKey('default', $properties['bad']); } + public function testDropsDefaultInPlainArrayDefinition(): void + { + // definitions may also be plain arrays (e.g. the Hydra base schemas) + $properties = $this->build(['Node' => ['type' => 'object', 'properties' => [ + 'slug' => self::SLUG + ['default' => ''], + 'title' => ['type' => 'string', 'default' => ''], + ]]], plain: true)['Node']['properties']; + + self::assertSame(self::SLUG, $properties['slug']); + self::assertSame('', $properties['title']['default']); + } + + public function testCleansDefinitionsWrittenIntoThePassedSchema(): void + { + $schema = new Schema(); + $definitions = $schema->getDefinitions(); + $inner = $this->innerFactory(['Node' => ['type' => 'object', 'properties' => [ + 'slug' => self::SLUG + ['default' => ''], + ]]]); + + $result = (new InvalidDefaultSchemaDecorator($inner))->buildSchema('Node', schema: $schema); + + self::assertSame($schema, $result); + self::assertSame($definitions, $result->getDefinitions()); + self::assertInstanceOf(\ArrayObject::class, $definitions['Node']); + self::assertInstanceOf(\ArrayObject::class, $definitions['Node']['properties']['slug']); + self::assertSame(self::SLUG, $definitions['Node']['properties']['slug']->getArrayCopy()); + } + /** + * Builds the definitions through the decorator and returns them as plain + * arrays, so assertions can compare with assertSame. + * * @param array $definitions + * + * @return array */ - private function build(array $definitions): \ArrayObject + private function build(array $definitions, bool $plain = false): array { - $inner = new class(new \ArrayObject($definitions)) implements SchemaFactoryInterface { - public function __construct(private readonly \ArrayObject $definitions) + $schema = (new InvalidDefaultSchemaDecorator($this->innerFactory($definitions, $plain)))->buildSchema('Node'); + + return self::toArray($schema->getDefinitions()); + } + + /** + * A stub of the inner factory that behaves like the real one: it writes + * its definitions into the passed `$schema` (a new one when none is + * passed) and returns that schema. + * + * @param array $definitions + */ + private function innerFactory(array $definitions, bool $plain = false): SchemaFactoryInterface + { + $shaped = []; + foreach ($definitions as $name => $definition) { + $shaped[$name] = $plain ? $definition : self::toApiShape($definition); + } + + return new class($shaped) implements SchemaFactoryInterface { + /** + * @param array $definitions + */ + public function __construct(private readonly array $definitions) { } public function buildSchema(string $className, string $format = 'json', string $type = Schema::TYPE_OUTPUT, ?Operation $operation = null, ?Schema $schema = null, ?array $serializerContext = null, bool $forceCollection = false): Schema { - $schema = new Schema(); - $schema->setDefinitions($this->definitions); + $schema ??= new Schema(); + $definitions = $schema->getDefinitions(); + foreach ($this->definitions as $name => $definition) { + $definitions[$name] = $definition; + } return $schema; } }; + } + + /** + * Converts a schema node into the shape API Platform's SchemaFactory + * produces: the node is an ArrayObject, `properties` is a plain array of + * ArrayObjects, and `allOf`/`anyOf`/`oneOf` are plain arrays whose + * `$ref`-only members stay plain arrays (as in the Hydra wrapper). + * + * @param array $node + */ + private static function toApiShape(array $node): \ArrayObject + { + if (isset($node['properties']) && \is_array($node['properties'])) { + foreach ($node['properties'] as $name => $property) { + $node['properties'][$name] = \is_array($property) ? self::toApiShape($property) : $property; + } + } + + foreach (['allOf', 'anyOf', 'oneOf'] as $keyword) { + if (isset($node[$keyword]) && \is_array($node[$keyword])) { + foreach ($node[$keyword] as $index => $branch) { + if (\is_array($branch) && !(1 === \count($branch) && isset($branch['$ref']))) { + $node[$keyword][$index] = self::toApiShape($branch); + } + } + } + } - return (new InvalidDefaultSchemaDecorator($inner))->buildSchema('Node')->getDefinitions(); + return new \ArrayObject($node); + } + + private static function toArray(mixed $node): mixed + { + if ($node instanceof \ArrayObject) { + $node = $node->getArrayCopy(); + } + if (!\is_array($node)) { + return $node; + } + + return array_map(self::toArray(...), $node); } } From f7715fb5c3be7cf1c68249f3e6bdaf718c27d4f8 Mon Sep 17 00:00:00 2001 From: "t.munk (workhorse)" Date: Thu, 26 Nov 2026 09:03:03 +0000 Subject: [PATCH 03/10] refactor(openapi): walk sub-schemas through one generic walker [*] No behaviour change: properties children are still checked and descended into, allOf/anyOf/oneOf branches are still only descended into. Co-Authored-By: Claude Fable 5.2 --- src/OpenApi/InvalidDefaultSchemaDecorator.php | 53 ++++++++++++++----- 1 file changed, 39 insertions(+), 14 deletions(-) diff --git a/src/OpenApi/InvalidDefaultSchemaDecorator.php b/src/OpenApi/InvalidDefaultSchemaDecorator.php index 19e4b4e..3b70ee2 100644 --- a/src/OpenApi/InvalidDefaultSchemaDecorator.php +++ b/src/OpenApi/InvalidDefaultSchemaDecorator.php @@ -25,6 +25,17 @@ */ class InvalidDefaultSchemaDecorator implements SchemaFactoryInterface { + /** + * Keywords whose value is a map of sub-schemas (name => schema); the + * default of each child is checked. + */ + private const SCHEMA_MAPS = ['properties']; + + /** + * Keywords whose value is a list of sub-schemas; the branches are walked. + */ + private const SCHEMA_LISTS = ['allOf', 'anyOf', 'oneOf']; + public function __construct( private readonly SchemaFactoryInterface $decorated, ) { @@ -58,36 +69,50 @@ public function buildSchema( } /** - * Walks `properties` (nested objects included) and `allOf`/`anyOf`/`oneOf` - * branches, the places API Platform puts property schemas. + * Walks a schema node recursively through its sub-schemas: `properties` + * (nested objects included) and `allOf`/`anyOf`/`oneOf` branches, the + * places API Platform puts property schemas. Nodes may be plain arrays or + * ArrayObjects at every level. */ - private function cleanNode(mixed $node): mixed + private function cleanNode(mixed $node, bool $checkDefault = false): mixed { if (!\is_array($node) && !$node instanceof \ArrayObject) { return $node; } - if (isset($node['properties']) && (\is_array($node['properties']) || $node['properties'] instanceof \ArrayObject)) { - $properties = $node['properties']; - foreach ($properties as $name => $property) { - $properties[$name] = $this->cleanNode($this->dropInvalidDefault($property)); + if ($checkDefault) { + $node = $this->dropInvalidDefault($node); + } + + foreach (self::SCHEMA_MAPS as $keyword) { + if (isset($node[$keyword]) && (\is_array($node[$keyword]) || $node[$keyword] instanceof \ArrayObject)) { + $node[$keyword] = $this->cleanChildren($node[$keyword], true); } - $node['properties'] = $properties; } - foreach (['allOf', 'anyOf', 'oneOf'] as $keyword) { + foreach (self::SCHEMA_LISTS as $keyword) { if (isset($node[$keyword]) && \is_array($node[$keyword])) { - $branches = $node[$keyword]; - foreach ($branches as $index => $branch) { - $branches[$index] = $this->cleanNode($branch); - } - $node[$keyword] = $branches; + $node[$keyword] = $this->cleanChildren($node[$keyword], false); } } return $node; } + /** + * @param array|\ArrayObject $children + * + * @return array|\ArrayObject + */ + private function cleanChildren(array|\ArrayObject $children, bool $checkDefault): array|\ArrayObject + { + foreach ($children as $key => $child) { + $children[$key] = $this->cleanNode($child, $checkDefault); + } + + return $children; + } + private function dropInvalidDefault(mixed $property): mixed { if ((!\is_array($property) && !$property instanceof \ArrayObject) || !isset($property['default'])) { From 3f09ddd079b356bc16010f1bbdc42cc598d0fb5b Mon Sep 17 00:00:00 2001 From: "t.munk (workhorse)" Date: Thu, 26 Nov 2026 09:04:42 +0000 Subject: [PATCH 04/10] fix(openapi): check defaults in array items and additionalProperties [*] The cleanup descends into items (single schema and tuple form), prefixItems and additionalProperties, and checks the default of every visited sub-schema, combinator branches and the definition root included. A default next to a $ref is kept, because the reference is not resolved. Co-Authored-By: Claude Fable 5.2 --- src/OpenApi/InvalidDefaultSchemaDecorator.php | 63 ++++++++----- .../InvalidDefaultSchemaDecoratorTest.php | 90 +++++++++++++++++++ 2 files changed, 133 insertions(+), 20 deletions(-) diff --git a/src/OpenApi/InvalidDefaultSchemaDecorator.php b/src/OpenApi/InvalidDefaultSchemaDecorator.php index 3b70ee2..de56248 100644 --- a/src/OpenApi/InvalidDefaultSchemaDecorator.php +++ b/src/OpenApi/InvalidDefaultSchemaDecorator.php @@ -10,7 +10,7 @@ use ApiPlatform\Metadata\Operation; /** - * Drops a property `default` that its own property schema rejects. + * Drops a `default` that its own (sub-)schema rejects. * * API Platform derives `default` from the PHP property initializer, so * `private string $slug = '';` next to `#[Assert\Regex(...)]` yields @@ -26,15 +26,20 @@ class InvalidDefaultSchemaDecorator implements SchemaFactoryInterface { /** - * Keywords whose value is a map of sub-schemas (name => schema); the - * default of each child is checked. + * Keywords whose value is a map of sub-schemas (name => schema). */ private const SCHEMA_MAPS = ['properties']; /** - * Keywords whose value is a list of sub-schemas; the branches are walked. + * Keywords whose value is a list of sub-schemas. */ - private const SCHEMA_LISTS = ['allOf', 'anyOf', 'oneOf']; + private const SCHEMA_LISTS = ['allOf', 'anyOf', 'oneOf', 'prefixItems']; + + /** + * Keywords whose value is a single sub-schema; a boolean (`true`/`false`) + * is not a schema and is skipped. + */ + private const SCHEMA_SINGLES = ['additionalProperties']; public function __construct( private readonly SchemaFactoryInterface $decorated, @@ -69,33 +74,43 @@ public function buildSchema( } /** - * Walks a schema node recursively through its sub-schemas: `properties` - * (nested objects included) and `allOf`/`anyOf`/`oneOf` branches, the - * places API Platform puts property schemas. Nodes may be plain arrays or - * ArrayObjects at every level. + * Walks a schema node recursively and checks the default of every visited + * schema, the definition root included. Sub-schemas are found under + * `properties`, `allOf`/`anyOf`/`oneOf`, `items` (a single schema or the + * tuple form), `prefixItems` and `additionalProperties`. Nodes may be + * plain arrays or ArrayObjects at every level. + * + * A node with `$ref` keeps its default: the referenced schema is not + * resolved, so the default cannot be judged. */ - private function cleanNode(mixed $node, bool $checkDefault = false): mixed + private function cleanNode(mixed $node): mixed { - if (!\is_array($node) && !$node instanceof \ArrayObject) { + if (!self::isArrayLike($node)) { return $node; } - if ($checkDefault) { + if (!isset($node['$ref'])) { $node = $this->dropInvalidDefault($node); } - foreach (self::SCHEMA_MAPS as $keyword) { - if (isset($node[$keyword]) && (\is_array($node[$keyword]) || $node[$keyword] instanceof \ArrayObject)) { - $node[$keyword] = $this->cleanChildren($node[$keyword], true); + foreach ([...self::SCHEMA_MAPS, ...self::SCHEMA_LISTS] as $keyword) { + if (isset($node[$keyword]) && self::isArrayLike($node[$keyword])) { + $node[$keyword] = $this->cleanChildren($node[$keyword]); } } - foreach (self::SCHEMA_LISTS as $keyword) { - if (isset($node[$keyword]) && \is_array($node[$keyword])) { - $node[$keyword] = $this->cleanChildren($node[$keyword], false); + foreach (self::SCHEMA_SINGLES as $keyword) { + if (isset($node[$keyword]) && self::isArrayLike($node[$keyword])) { + $node[$keyword] = $this->cleanNode($node[$keyword]); } } + if (isset($node['items']) && self::isArrayLike($node['items'])) { + $items = $node['items']; + $isTuple = array_is_list($items instanceof \ArrayObject ? $items->getArrayCopy() : $items); + $node['items'] = $isTuple ? $this->cleanChildren($items) : $this->cleanNode($items); + } + return $node; } @@ -104,15 +119,23 @@ private function cleanNode(mixed $node, bool $checkDefault = false): mixed * * @return array|\ArrayObject */ - private function cleanChildren(array|\ArrayObject $children, bool $checkDefault): array|\ArrayObject + private function cleanChildren(array|\ArrayObject $children): array|\ArrayObject { foreach ($children as $key => $child) { - $children[$key] = $this->cleanNode($child, $checkDefault); + $children[$key] = $this->cleanNode($child); } return $children; } + /** + * @phpstan-assert-if-true array|\ArrayObject $node + */ + private static function isArrayLike(mixed $node): bool + { + return \is_array($node) || $node instanceof \ArrayObject; + } + private function dropInvalidDefault(mixed $property): mixed { if ((!\is_array($property) && !$property instanceof \ArrayObject) || !isset($property['default'])) { diff --git a/tests/OpenApi/InvalidDefaultSchemaDecoratorTest.php b/tests/OpenApi/InvalidDefaultSchemaDecoratorTest.php index 08f7d60..84a155e 100644 --- a/tests/OpenApi/InvalidDefaultSchemaDecoratorTest.php +++ b/tests/OpenApi/InvalidDefaultSchemaDecoratorTest.php @@ -87,6 +87,96 @@ public function testPatternWithSlashIsEscaped(): void self::assertArrayNotHasKey('default', $properties['bad']); } + public function testWalksObjectInsideArrayItems(): void + { + $items = $this->build(['Node' => ['type' => 'object', 'properties' => [ + 'tags' => ['type' => 'array', 'items' => ['type' => 'object', 'properties' => [ + 'slug' => self::SLUG + ['default' => ''], + 'label' => ['type' => 'string', 'default' => ''], + ]]], + ]]])['Node']['properties']['tags']['items']['properties']; + + self::assertSame(self::SLUG, $items['slug']); + self::assertSame('', $items['label']['default']); + } + + public function testChecksItemsSchemaAndTupleItems(): void + { + $properties = $this->build(['Node' => ['type' => 'object', 'properties' => [ + 'slugs' => ['type' => 'array', 'items' => self::SLUG + ['default' => '']], + 'pair' => ['type' => 'array', 'items' => [ + self::SLUG + ['default' => ''], + self::SLUG + ['default' => 'ok'], + ]], + ]]])['Node']['properties']; + + self::assertSame(self::SLUG, $properties['slugs']['items']); + self::assertSame(self::SLUG, $properties['pair']['items'][0]); + self::assertSame('ok', $properties['pair']['items'][1]['default']); + } + + public function testChecksPrefixItems(): void + { + $prefixItems = $this->build(['Node' => ['type' => 'object', 'properties' => [ + 'pair' => ['type' => 'array', 'prefixItems' => [ + self::SLUG + ['default' => ''], + self::SLUG + ['default' => 'ok'], + ]], + ]]])['Node']['properties']['pair']['prefixItems']; + + self::assertSame(self::SLUG, $prefixItems[0]); + self::assertSame('ok', $prefixItems[1]['default']); + } + + public function testChecksAdditionalPropertiesSchema(): void + { + // sub-schemas may be ArrayObjects as well as plain arrays + $properties = $this->build(['Node' => ['type' => 'object', 'properties' => [ + 'labels' => ['type' => 'object', 'additionalProperties' => new \ArrayObject(self::SLUG + ['default' => ''])], + ]]])['Node']['properties']; + + self::assertSame(self::SLUG, $properties['labels']['additionalProperties']); + } + + public function testSkipsBooleanAdditionalProperties(): void + { + $properties = $this->build(['Node' => ['type' => 'object', 'additionalProperties' => false, 'properties' => [ + 'open' => ['type' => 'object', 'additionalProperties' => true, 'default' => []], + 'slugs' => ['type' => 'array', 'additionalProperties' => true, 'items' => self::SLUG + ['default' => '']], + ]]])['Node']; + + self::assertFalse($properties['additionalProperties']); + self::assertSame(['type' => 'object', 'additionalProperties' => true, 'default' => []], $properties['properties']['open']); + self::assertSame(self::SLUG, $properties['properties']['slugs']['items']); + } + + public function testChecksCombinatorBranchesAndDefinitionRoot(): void + { + $definitions = $this->build([ + 'Status' => ['type' => 'string', 'enum' => ['draft'], 'default' => 'gone'], + 'Node' => ['type' => 'object', 'properties' => [ + 'slug' => ['anyOf' => [self::SLUG + ['default' => ''], ['type' => 'null']]], + ]], + ]); + + self::assertArrayNotHasKey('default', $definitions['Status']); + self::assertSame(self::SLUG, $definitions['Node']['properties']['slug']['anyOf'][0]); + } + + public function testKeepsDefaultNextToRef(): void + { + // the referenced schema is not resolved, so a default beside `$ref` + // is not judged, even against sibling keywords + $ref = ['$ref' => '#/definitions/Slug', 'pattern' => '^[a-z]+$', 'default' => '']; + $properties = $this->build(['Node' => ['type' => 'object', 'properties' => [ + 'slug' => $ref, + 'tags' => ['type' => 'array', 'items' => $ref], + ]]])['Node']['properties']; + + self::assertSame($ref, $properties['slug']); + self::assertSame($ref, $properties['tags']['items']); + } + public function testDropsDefaultInPlainArrayDefinition(): void { // definitions may also be plain arrays (e.g. the Hydra base schemas) From b3c091e259e5da6d333043a65f6a267f900fca1d Mon Sep 17 00:00:00 2001 From: "t.munk (workhorse)" Date: Thu, 26 Nov 2026 09:06:02 +0000 Subject: [PATCH 05/10] fix(openapi): escape only unescaped slashes in schema patterns [*] A pattern that already contained \/ was escaped twice, no longer compiled, and silently kept its invalid default. Co-Authored-By: Claude Fable 5.2 --- src/OpenApi/InvalidDefaultSchemaDecorator.php | 6 +++-- .../InvalidDefaultSchemaDecoratorTest.php | 24 +++++++++++++++++++ 2 files changed, 28 insertions(+), 2 deletions(-) diff --git a/src/OpenApi/InvalidDefaultSchemaDecorator.php b/src/OpenApi/InvalidDefaultSchemaDecorator.php index de56248..4fd2cd8 100644 --- a/src/OpenApi/InvalidDefaultSchemaDecorator.php +++ b/src/OpenApi/InvalidDefaultSchemaDecorator.php @@ -171,8 +171,10 @@ private function violates(array|\ArrayObject $property, mixed $default): bool if (isset($property['pattern']) && \is_string($property['pattern'])) { // JSON Schema patterns are ECMA-262 and unanchored; the delimiter - // is escaped, everything else is passed through as written. - $regex = '/' . str_replace('/', '\/', $property['pattern']) . '/u'; + // is escaped, everything else is passed through as written. Only + // an unescaped `/` (after an even number of backslashes) gets a + // backslash: `\/` stays `\/`, `\\/` becomes `\\\/`. + $regex = '/' . preg_replace('~(? + */ + public static function slashPatterns(): iterable + { + yield 'escaped slash' => ['^a\/b$', 'a/b', 'ab']; + yield 'unescaped slash' => ['^/[a-z]+$', '/home', '']; + // an escaped backslash followed by a slash: literal `\` then `/` + yield 'escaped backslash before slash' => ['^a\\\\/b$', 'a\\/b', 'a/b']; + } + + #[DataProvider('slashPatterns')] + public function testPatternDelimiterIsEscapedOnlyWhereNeeded(string $pattern, string $valid, string $invalid): void + { + $properties = $this->build(['Node' => ['type' => 'object', 'properties' => [ + 'valid' => ['type' => 'string', 'pattern' => $pattern, 'default' => $valid], + 'invalid' => ['type' => 'string', 'pattern' => $pattern, 'default' => $invalid], + ]]])['Node']['properties']; + + self::assertSame($valid, $properties['valid']['default']); + self::assertArrayNotHasKey('default', $properties['invalid']); + } + public function testWalksObjectInsideArrayItems(): void { $items = $this->build(['Node' => ['type' => 'object', 'properties' => [ From 3e1b3a33e07d13f77fec45052bd2447d9bccb4f6 Mon Sep 17 00:00:00 2001 From: "t.munk (workhorse)" Date: Thu, 26 Nov 2026 09:07:00 +0000 Subject: [PATCH 06/10] fix(openapi): drop a null default its enum does not contain [*] isset() skipped every null default. Presence is now tested with array_key_exists/offsetExists; a null default is judged by enum only. Co-Authored-By: Claude Fable 5.2 --- src/OpenApi/InvalidDefaultSchemaDecorator.php | 12 ++++++++- .../InvalidDefaultSchemaDecoratorTest.php | 25 +++++++++++++++++++ 2 files changed, 36 insertions(+), 1 deletion(-) diff --git a/src/OpenApi/InvalidDefaultSchemaDecorator.php b/src/OpenApi/InvalidDefaultSchemaDecorator.php index 4fd2cd8..685c400 100644 --- a/src/OpenApi/InvalidDefaultSchemaDecorator.php +++ b/src/OpenApi/InvalidDefaultSchemaDecorator.php @@ -138,7 +138,15 @@ private static function isArrayLike(mixed $node): bool private function dropInvalidDefault(mixed $property): mixed { - if ((!\is_array($property) && !$property instanceof \ArrayObject) || !isset($property['default'])) { + // presence, not isset(): a `default: null` is a default as well + if (\is_array($property)) { + $hasDefault = \array_key_exists('default', $property); + } elseif ($property instanceof \ArrayObject) { + $hasDefault = $property->offsetExists('default'); + } else { + return $property; + } + if (!$hasDefault) { return $property; } @@ -157,6 +165,8 @@ private function violates(array|\ArrayObject $property, mixed $default): bool return true; } + // the string keywords below do not judge other types, `null` included: + // a `null` default is only checked against `enum` if (!\is_string($default)) { return false; } diff --git a/tests/OpenApi/InvalidDefaultSchemaDecoratorTest.php b/tests/OpenApi/InvalidDefaultSchemaDecoratorTest.php index 95ebf5f..9b70e90 100644 --- a/tests/OpenApi/InvalidDefaultSchemaDecoratorTest.php +++ b/tests/OpenApi/InvalidDefaultSchemaDecoratorTest.php @@ -111,6 +111,31 @@ public function testPatternDelimiterIsEscapedOnlyWhereNeeded(string $pattern, st self::assertArrayNotHasKey('default', $properties['invalid']); } + /** + * @return iterable + */ + public static function shapes(): iterable + { + yield 'ArrayObject' => [false]; + yield 'plain array' => [true]; + } + + #[DataProvider('shapes')] + public function testNullDefaultIsJudgedByEnumOnly(bool $plain): void + { + $properties = $this->build(['Node' => ['type' => 'object', 'properties' => [ + 'notInEnum' => ['type' => 'string', 'enum' => ['draft', 'published'], 'default' => null], + 'inEnum' => ['type' => ['string', 'null'], 'enum' => ['draft', null], 'default' => null], + 'noEnum' => ['type' => ['string', 'null'], 'pattern' => '^[a-z]+$', 'minLength' => 1, 'maxLength' => 3, 'default' => null], + ]]], $plain)['Node']['properties']; + + self::assertArrayNotHasKey('default', $properties['notInEnum']); + self::assertArrayHasKey('default', $properties['inEnum']); + self::assertNull($properties['inEnum']['default']); + self::assertArrayHasKey('default', $properties['noEnum']); + self::assertNull($properties['noEnum']['default']); + } + public function testWalksObjectInsideArrayItems(): void { $items = $this->build(['Node' => ['type' => 'object', 'properties' => [ From 019d9eee641fa910cde929765791b0af03c0238a Mon Sep 17 00:00:00 2001 From: "t.munk (workhorse)" Date: Thu, 26 Nov 2026 09:07:58 +0000 Subject: [PATCH 07/10] fix(openapi): let $ in a schema pattern match only at the very end [*] PCRE lets $ match before a trailing newline, ECMA-262 does not. The D modifier makes the check follow the ECMA reading. Co-Authored-By: Claude Fable 5.2 --- src/OpenApi/InvalidDefaultSchemaDecorator.php | 6 ++++-- tests/OpenApi/InvalidDefaultSchemaDecoratorTest.php | 13 +++++++++++++ 2 files changed, 17 insertions(+), 2 deletions(-) diff --git a/src/OpenApi/InvalidDefaultSchemaDecorator.php b/src/OpenApi/InvalidDefaultSchemaDecorator.php index 685c400..1585737 100644 --- a/src/OpenApi/InvalidDefaultSchemaDecorator.php +++ b/src/OpenApi/InvalidDefaultSchemaDecorator.php @@ -183,8 +183,10 @@ private function violates(array|\ArrayObject $property, mixed $default): bool // JSON Schema patterns are ECMA-262 and unanchored; the delimiter // is escaped, everything else is passed through as written. Only // an unescaped `/` (after an even number of backslashes) gets a - // backslash: `\/` stays `\/`, `\\/` becomes `\\\/`. - $regex = '/' . preg_replace('~(?build(['Node' => ['type' => 'object', 'properties' => [ + 'newline' => ['type' => 'string', 'pattern' => '^[a-z]+$', 'default' => "abc\n"], + 'plain' => ['type' => 'string', 'pattern' => '^[a-z]+$', 'default' => 'abc'], + ]]])['Node']['properties']; + + self::assertArrayNotHasKey('default', $properties['newline']); + self::assertSame('abc', $properties['plain']['default']); + } + /** * @return iterable */ From 1fbb542d414ca98ca23cfea2c88121dc9cb65e89 Mon Sep 17 00:00:00 2001 From: "t.munk (workhorse)" Date: Thu, 26 Nov 2026 09:11:41 +0000 Subject: [PATCH 08/10] perf(openapi): clean each schema definition once per build [*] Every buildSchema() call walked all definitions collected so far, which is quadratic over one OpenAPI build. Cleaned definition objects are now remembered in a WeakMap per definitions object; replaced definitions and plain-array definitions are still cleaned. Co-Authored-By: Claude Fable 5.2 --- src/OpenApi/InvalidDefaultSchemaDecorator.php | 31 ++++- .../InvalidDefaultSchemaDecoratorTest.php | 130 ++++++++++++++++++ 2 files changed, 160 insertions(+), 1 deletion(-) diff --git a/src/OpenApi/InvalidDefaultSchemaDecorator.php b/src/OpenApi/InvalidDefaultSchemaDecorator.php index 1585737..22f6b8c 100644 --- a/src/OpenApi/InvalidDefaultSchemaDecorator.php +++ b/src/OpenApi/InvalidDefaultSchemaDecorator.php @@ -41,9 +41,20 @@ class InvalidDefaultSchemaDecorator implements SchemaFactoryInterface */ private const SCHEMA_SINGLES = ['additionalProperties']; + /** + * Definition objects already cleaned, per definitions object (one per + * build). Both levels are weak: a finished build releases its entry, and + * an entry of a freed definition disappears, so a new object that reuses + * its object id is never mistaken for it. + * + * @var \WeakMap<\ArrayObject, \WeakMap<\ArrayObject, true>> + */ + private readonly \WeakMap $cleaned; + public function __construct( private readonly SchemaFactoryInterface $decorated, ) { + $this->cleaned = new \WeakMap(); } public function buildSchema( @@ -65,9 +76,27 @@ public function buildSchema( $forceCollection, ); + // The definitions object is shared by all calls of one build and grows + // with each of them; walking all of it every time is quadratic. An + // ArrayObject definition is cleaned in place and remembered, so it is + // walked once per build. A definition replaced under the same name by + // a new object (Hydra wraps definitions in `allOf`) is a new key and + // is cleaned again; plain-array definitions are cleaned every time. + // Remaining risk: a default added later, in place, to an already + // cleaned object is not checked. No schema factory decorator in API + // Platform 4.4 does that. $definitions = $schema->getDefinitions(); + $cleaned = $this->cleaned[$definitions] ??= new \WeakMap(); foreach ($definitions as $key => $definition) { - $definitions[$key] = $this->cleanNode($definition); + if (!$definition instanceof \ArrayObject) { + $definitions[$key] = $this->cleanNode($definition); + continue; + } + if (isset($cleaned[$definition])) { + continue; + } + $this->cleanNode($definition); + $cleaned[$definition] = true; } return $schema; diff --git a/tests/OpenApi/InvalidDefaultSchemaDecoratorTest.php b/tests/OpenApi/InvalidDefaultSchemaDecoratorTest.php index 2e335d3..82e9fda 100644 --- a/tests/OpenApi/InvalidDefaultSchemaDecoratorTest.php +++ b/tests/OpenApi/InvalidDefaultSchemaDecoratorTest.php @@ -268,6 +268,136 @@ public function testCleansDefinitionsWrittenIntoThePassedSchema(): void self::assertSame(self::SLUG, $definitions['Node']['properties']['slug']->getArrayCopy()); } + public function testCleansEachDefinitionOnceAcrossOneBuild(): void + { + // like the real factory, every call adds one definition to the shared + // definitions object; a walk is counted per lookup of `properties` + $walks = new \stdClass(); + $walks->count = 0; + $inner = $this->writingFactory(static function (\ArrayObject $definitions, string $className) use ($walks): void { + $definitions[$className] = new class(['type' => 'object', 'properties' => ['slug' => new \ArrayObject(self::SLUG + ['default' => ''])]], $walks) extends \ArrayObject { + public function __construct(array $array, private readonly \stdClass $walks) + { + parent::__construct($array); + } + + public function offsetExists(mixed $key): bool + { + if ('properties' === $key) { + ++$this->walks->count; + } + + return parent::offsetExists($key); + } + }; + }); + + $decorator = new InvalidDefaultSchemaDecorator($inner); + $schema = new Schema(); + $n = 5; + for ($i = 1; $i <= $n; ++$i) { + $decorator->buildSchema('Node' . $i, schema: $schema); + } + + self::assertSame($n, $walks->count); + foreach ($schema->getDefinitions() as $definition) { + self::assertSame(self::SLUG, $definition['properties']['slug']->getArrayCopy()); + } + } + + public function testCleansDefinitionsArrivingInLaterCalls(): void + { + $inner = $this->writingFactory(static function (\ArrayObject $definitions, string $className): void { + $definitions[$className] = self::toApiShape(['type' => 'object', 'properties' => ['slug' => self::SLUG + ['default' => '']]]); + }); + + $decorator = new InvalidDefaultSchemaDecorator($inner); + $schema = new Schema(); + foreach (['First', 'Second', 'Third'] as $className) { + $decorator->buildSchema($className, schema: $schema); + } + + $definitions = self::toArray($schema->getDefinitions()); + foreach (['First', 'Second', 'Third'] as $className) { + self::assertSame(self::SLUG, $definitions[$className]['properties']['slug']); + } + } + + public function testCleansDefinitionReplacedUnderTheSameName(): void + { + $node = ['type' => 'object', 'properties' => ['slug' => self::SLUG + ['default' => '']]]; + $inner = $this->writingFactory(static function (\ArrayObject $definitions, string $className) use ($node): void { + if ('Wrap' === $className) { + // Hydra-style: the same name now holds an allOf wrapper + $definitions['Node'] = new \ArrayObject(['allOf' => [ + ['$ref' => '#/definitions/HydraItemBaseSchema'], + self::toApiShape($node), + ]]); + + return; + } + // free the old object first and create a single new one, so the + // new object reuses the old object id (a trap for id-based memory) + unset($definitions['Node']); + $definitions['Node'] = new \ArrayObject($node); + }); + + $decorator = new InvalidDefaultSchemaDecorator($inner); + $schema = new Schema(); + + $decorator->buildSchema('Node', schema: $schema); + $decorator->buildSchema('Node', schema: $schema); + self::assertSame(self::SLUG, self::toArray($schema->getDefinitions())['Node']['properties']['slug']); + + $decorator->buildSchema('Wrap', schema: $schema); + self::assertSame(self::SLUG, self::toArray($schema->getDefinitions())['Node']['allOf'][1]['properties']['slug']); + } + + public function testCleansAFreshBuildThroughTheSameDecorator(): void + { + $inner = $this->writingFactory(static function (\ArrayObject $definitions, string $className): void { + // like the real factory: a definition is written once per build + $definitions['Node'] ??= new \ArrayObject(['type' => 'object', 'properties' => ['slug' => self::SLUG + ['default' => '']]]); + // plain-array definitions are cleaned on every call + $definitions['Plain'] ??= ['type' => 'object', 'properties' => ['slug' => self::SLUG + ['default' => '']]]; + }); + + $decorator = new InvalidDefaultSchemaDecorator($inner); + foreach ([1, 2] as $build) { + $schema = new Schema(); + $decorator->buildSchema('Node', schema: $schema); + $decorator->buildSchema('Node', schema: $schema); + + $definitions = self::toArray($schema->getDefinitions()); + self::assertSame(self::SLUG, $definitions['Node']['properties']['slug'], 'build ' . $build); + self::assertSame(self::SLUG, $definitions['Plain']['properties']['slug'], 'build ' . $build); + unset($schema, $definitions); + } + } + + /** + * A stub of the inner factory that lets each test write into the + * definitions of the passed `$schema`, as the real factory does. + * + * @param \Closure(\ArrayObject, string): void $write + */ + private function writingFactory(\Closure $write): SchemaFactoryInterface + { + return new class($write) implements SchemaFactoryInterface { + public function __construct(private readonly \Closure $write) + { + } + + public function buildSchema(string $className, string $format = 'json', string $type = Schema::TYPE_OUTPUT, ?Operation $operation = null, ?Schema $schema = null, ?array $serializerContext = null, bool $forceCollection = false): Schema + { + $schema ??= new Schema(); + ($this->write)($schema->getDefinitions(), $className); + + return $schema; + } + }; + } + /** * Builds the definitions through the decorator and returns them as plain * arrays, so assertions can compare with assertSame. From 64f091d5ef8e881e4c5bbf3e30005d43c61bed25 Mon Sep 17 00:00:00 2001 From: "t.munk (workhorse)" Date: Thu, 26 Nov 2026 09:01:42 +0000 Subject: [PATCH 09/10] docs(openapi): describe the real decoration order of the schema cleanup [*] A higher decoration priority sits further inside: the cleanup (5) wraps the relation field decorator (10) and is wrapped by the Hydra, HAL and JSON:API schema factories (0). Co-Authored-By: Claude Fable 5.2 --- config/services_schema_default_cleanup.yaml | 17 ++++++++++++++--- 1 file changed, 14 insertions(+), 3 deletions(-) diff --git a/config/services_schema_default_cleanup.yaml b/config/services_schema_default_cleanup.yaml index 5c94e15..805a4b7 100644 --- a/config/services_schema_default_cleanup.yaml +++ b/config/services_schema_default_cleanup.yaml @@ -7,9 +7,20 @@ services: public: false # Drops property defaults that violate their own pattern/minLength/ - # maxLength/enum (e.g. `default: ""` next to a slug pattern). Priority 5 - # wraps below RelationFieldSchemaDecorator (10); the order does not - # matter for the result, the two touch different keys. + # maxLength/enum (e.g. `default: ""` next to a slug pattern). + # + # Decoration order of api_platform.json_schema.schema_factory: a higher + # decoration_priority sits further inside, closer to the base factory. + # From outside to inside: + # backward_compatible (-2) + # Hydra, HAL, JSON:API schema factories (0) + # InvalidDefaultSchemaDecorator, this service (5) + # RelationFieldSchemaDecorator (10, config/services.yaml) + # base SchemaFactory + # So the cleanup wraps the relation decorator and runs after it, and the + # Hydra/HAL/JSON:API factories wrap the cleanup. Recursive calls the base + # SchemaFactory makes for nested resources do not pass through the + # cleanup. Dmstr\ApiPlatformUtils\OpenApi\InvalidDefaultSchemaDecorator: decorates: 'api_platform.json_schema.schema_factory' decoration_priority: 5 From 1d78b40bd220261f29002c24865412bd3b1a3687 Mon Sep 17 00:00:00 2001 From: "t.munk (workhorse)" Date: Thu, 26 Nov 2026 09:01:42 +0000 Subject: [PATCH 10/10] docs(openapi): document schema_default_cleanup and date the 0.7.0 changelog [*] README: option, default, checked keywords, descent and known limits. CHANGELOG: the entry moves to Changed and names what consumers must do. Co-Authored-By: Claude Fable 5.2 --- CHANGELOG.md | 7 ++----- README.md | 26 ++++++++++++++++++++++++++ 2 files changed, 28 insertions(+), 5 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 1112850..92e7f91 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,14 +2,11 @@ # Changelog -## Unreleased - -### Fixed - -- `InvalidDefaultSchemaDecorator` drops a property `default` from the JSON/OpenAPI schemas when the property schema itself rejects it (`pattern`, `minLength`, `maxLength`, `enum`). API Platform derives `default` from the PHP initializer, so `private string $slug = '';` next to a slug `#[Assert\Regex]` produced `default: ""` that its own `pattern` rejects, and form clients showed a validation error before anyone typed. Valid defaults are untouched; a pattern PHP cannot compile keeps its default. On by default, switch off with `schema_default_cleanup.enabled: false`. +## 0.7.0 (2026-11-26) ### Changed +- `schema_default_cleanup` (on by default): `InvalidDefaultSchemaDecorator` removes a property `default` from the JSON/OpenAPI schemas when the property's own schema rejects it (`pattern`, `minLength`, `maxLength`, `enum`). API Platform derives `default` from the PHP initializer, so `private string $slug = '';` next to a slug `#[Assert\Regex]` produced `default: ""` that its own `pattern` rejects, and form clients showed a validation error before anyone typed. Valid defaults are untouched. The cleanup descends into `properties`, `items` (single schema and tuple form), `prefixItems`, `additionalProperties` (when it is a schema), `allOf`, `anyOf` and `oneOf`. `default: null` is judged by `enum` only and is removed when an `enum` exists that does not contain `null`. Patterns are evaluated with PHP's PCRE, `$` matching only at the very end (a trailing newline does not match). Limits: `$ref` is not resolved, so a default next to a `$ref` is not checked; a pattern PHP cannot compile keeps its default; ECMA-262 regular expressions are not fully translated to PCRE. Server-side validation is unchanged. Consumers: check forms that rely on a default that is now removed, among them `default: null` on nullable enum properties whose `enum` does not contain `null`, or switch the cleanup off with `schema_default_cleanup.enabled: false`. - Tests and documentation only, no behaviour change: the Hydra operation filter test uses a permission attribute (`is_granted('thing:write')`) instead of a role name in the `security` expression, and a regression test proves the expression reaches the `ResourceAccessChecker` unchanged with `object = null` for collection operations. The filter is expression-neutral; this bundle defines no permissions of its own. README: how to use the filter with permission attributes. ## 0.6.0 (2026-10-15) diff --git a/README.md b/README.md index eab6a5f..d2c9381 100644 --- a/README.md +++ b/README.md @@ -129,6 +129,32 @@ dmstr_api_platform_utils: Only collection operations are affected; item responses keep the plain IRI, because forms edit relations as `iri-reference` strings and API Platform rejects nested documents on write. Each embedded label initialises the related entity, one query per distinct related row and page unless the collection query fetch-joins it. +## Invalid defaults in schemas (`schema_default_cleanup`) + +API Platform derives a property's `default` in the JSON/OpenAPI schema from the PHP property initializer. `private string $slug = '';` next to a slug `#[Assert\Regex]` therefore produces `default: ""` that the property's own `pattern` rejects, and a form client that fills in schema defaults shows a validation error before anyone typed. With `schema_default_cleanup.enabled` (default `true`), `InvalidDefaultSchemaDecorator` decorates `api_platform.json_schema.schema_factory` and removes a `default` that the property's own schema rejects. Valid defaults are untouched. + +Rules: + +- Checked keywords: `pattern`, `minLength`, `maxLength`, `enum`. A `default` that violates one of them is removed. +- The cleanup visits every sub-schema reachable through `properties`, `items` (single schema and tuple form), `prefixItems`, `additionalProperties` (when it is a schema), `allOf`, `anyOf` and `oneOf`. +- `default: null` is judged by `enum` only: it is removed when an `enum` exists that does not contain `null`. The typical case is a nullable enum property whose `enum` lacks `null`. +- Patterns are evaluated with PHP's PCRE, with `$` matching only at the very end of the string (ECMA reading: a trailing newline does not match). + +Known limits: + +- `$ref` is not resolved, so a `default` next to a `$ref` is not checked. +- A pattern PHP cannot compile keeps its default; nothing is removed. +- There is no full translation of ECMA-262 regular expressions to PCRE, so a pattern that relies on ECMA-specific syntax may be judged differently than a browser would judge it. +- Server-side validation is unchanged; only the emitted schema changes. + +To switch the cleanup off: + +```yaml +dmstr_api_platform_utils: + schema_default_cleanup: + enabled: false +``` + ## License MIT © diemeisterei GmbH