Skip to content
Merged
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
3 changes: 2 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
26 changes: 26 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
28 changes: 28 additions & 0 deletions config/services_schema_default_cleanup.yaml
Original file line number Diff line number Diff line change
@@ -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'
7 changes: 7 additions & 0 deletions src/DependencyInjection/ApiPlatformUtilsExtension.php
Original file line number Diff line number Diff line change
Expand Up @@ -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');
Expand Down Expand Up @@ -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
Expand Down
11 changes: 11 additions & 0 deletions src/DependencyInjection/Configuration.php
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down
228 changes: 228 additions & 0 deletions src/OpenApi/InvalidDefaultSchemaDecorator.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,228 @@
<?php
// file generated with AI assistance: Claude Code - 2026-10-10 00:15:00 UTC

declare(strict_types=1);

namespace Dmstr\ApiPlatformUtils\OpenApi;

use ApiPlatform\JsonSchema\Schema;
use ApiPlatform\JsonSchema\SchemaFactoryInterface;
use ApiPlatform\Metadata\Operation;

/**
* 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
* `{"pattern": "^[a-z0-9-]+$", "default": ""}` — a schema that contradicts
* itself. Form clients start from the default and show a validation error
* before anyone has typed. Removing the default only removes the
* contradiction: the field simply starts empty in the client, and the
* server-side validation is unchanged.
*
* Checked keywords: `pattern`, `minLength`, `maxLength` (strings) and `enum`.
* A pattern PHP cannot compile is treated as "unknown" and keeps the default.
*/
class InvalidDefaultSchemaDecorator implements SchemaFactoryInterface
{
/**
* 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.
*/
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<string, mixed>, \WeakMap<\ArrayObject<array-key, mixed>, 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<array-key, mixed>|\ArrayObject<array-key, mixed> $children
*
* @return array<array-key, mixed>|\ArrayObject<array-key, mixed>
*/
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<array-key, mixed>|\ArrayObject<array-key, mixed> $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('~(?<!\\\\)((?:\\\\\\\\)*)/~', '$1\\/', $property['pattern']) . '/uD';
$match = @preg_match($regex, $default);
if ($match === 0) {
return true;
}
// false: PHP cannot compile it — keep the default rather than guess
}

return false;
}
}
14 changes: 14 additions & 0 deletions tests/DependencyInjection/ApiPlatformUtilsExtensionTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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([
Expand Down
Loading
Loading