diff --git a/CHANGELOG.md b/CHANGELOG.md index b4fab1a..92e7f91 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,10 +2,11 @@ # Changelog -## Unreleased +## 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 diff --git a/config/services_schema_default_cleanup.yaml b/config/services_schema_default_cleanup.yaml new file mode 100644 index 0000000..805a4b7 --- /dev/null +++ b/config/services_schema_default_cleanup.yaml @@ -0,0 +1,28 @@ +# 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). + # + # 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 + arguments: + $decorated: '@.inner' diff --git a/src/DependencyInjection/ApiPlatformUtilsExtension.php b/src/DependencyInjection/ApiPlatformUtilsExtension.php index 7f9a8d5..3b8e5a6 100644 --- a/src/DependencyInjection/ApiPlatformUtilsExtension.php +++ b/src/DependencyInjection/ApiPlatformUtilsExtension.php @@ -51,6 +51,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.relation_labels.enabled', $config['relation_labels']['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'); @@ -82,6 +84,11 @@ public function load(array $configs, ContainerBuilder $container): void if ($config['relation_labels']['enabled']) { $loader->load('services_relation_labels.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 f15ee2a..e56b13b 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..22f6b8c --- /dev/null +++ b/src/OpenApi/InvalidDefaultSchemaDecorator.php @@ -0,0 +1,228 @@ + schema). + */ + private const SCHEMA_MAPS = ['properties']; + + /** + * Keywords whose value is a list of sub-schemas. + */ + 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']; + + /** + * 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( + string $className, + string $format = 'json', + string $type = Schema::TYPE_OUTPUT, + ?Operation $operation = null, + ?Schema $schema = null, + ?array $serializerContext = null, + bool $forceCollection = false, + ): Schema { + $schema = $this->decorated->buildSchema( + $className, + $format, + $type, + $operation, + $schema, + $serializerContext, + $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) { + if (!$definition instanceof \ArrayObject) { + $definitions[$key] = $this->cleanNode($definition); + continue; + } + if (isset($cleaned[$definition])) { + continue; + } + $this->cleanNode($definition); + $cleaned[$definition] = true; + } + + return $schema; + } + + /** + * 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): mixed + { + if (!self::isArrayLike($node)) { + return $node; + } + + if (!isset($node['$ref'])) { + $node = $this->dropInvalidDefault($node); + } + + 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_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; + } + + /** + * @param array|\ArrayObject $children + * + * @return array|\ArrayObject + */ + private function cleanChildren(array|\ArrayObject $children): array|\ArrayObject + { + foreach ($children as $key => $child) { + $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 + { + // 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; + } + + 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; + } + + // 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; + } + + $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. Only + // an unescaped `/` (after an even number of backslashes) gets a + // backslash: `\/` stays `\/`, `\\/` becomes `\\\/`. `D` makes `$` + // match only at the very end, as in ECMA-262, not also before a + // trailing newline. + $regex = '/' . preg_replace('~(?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..82e9fda --- /dev/null +++ b/tests/OpenApi/InvalidDefaultSchemaDecoratorTest.php @@ -0,0 +1,491 @@ + '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 + { + // `[^]` 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' => '[^]', 'default' => 'x'], + ]]])['Node']['properties']; + + self::assertSame('x', $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']); + } + + /** + * @return iterable + */ + 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 testDollarDoesNotMatchBeforeTrailingNewline(): void + { + // ECMA `$` matches only at the very end; PCRE without `D` also + // before a final newline + $properties = $this->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 + */ + 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' => [ + '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) + $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()); + } + + 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. + * + * @param array $definitions + * + * @return array + */ + private function build(array $definitions, bool $plain = false): array + { + $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(); + $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 \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); + } +}