Enum drift detection
Runtime contract validation only sees enum values your tests actually return. Two failure modes slip through:
- PHP-only values — a case is added to a PHP enum but the spec is not updated. Existing contract tests catch this only if a test exercises a code path that returns the new value. Untested paths drift silently.
- Spec-only values — a value is added to the spec but no PHP case exists. Runtime validation can never observe this — the value cannot be produced by the implementation.
EnumDriftAsserter closes both holes by comparing PHP enum case values against the spec's enum: array statically.
- Binding by component name
EnumDriftAsserter::assertNoDrift()AssertsNoEnumDrift— PHPUnit traitdetectAll()— inspection without throwing- Misconfiguration vs drift
- Auto-discovery via the PHPUnit extension
- Known limitations
Binding by component name
A backed enum binds to the components.schemas entry that carries an enum: array and is named after the enum's short class name. No attribute is needed:
# front.yaml
components:
schemas:
NotificationCode:
type: string
enum: [studioPaymentOld, studioPaymentNew]namespace App\Enums;
enum NotificationCode: string
{
case StudioPaymentOld = 'studioPaymentOld';
case StudioPaymentNew = 'studioPaymentNew';
}An
Enumsuffix on either side is ignored:NotificationCodeEnummatchesNotificationCodeand vice versa. An exact name wins over the suffixed one.Every spec you pass (
spec.namesingesso.php, orspecNames:on the asserter) is searched. The documents come fromOpenApiSpecLoader::load(), so$refs are already resolved.When the component is named differently from the class, bind it explicitly with
#[BoundToOpenApiEnum('Name')](the argument is namedcomponent):phpuse Studio\Gesso\Attribute\BoundToOpenApiEnum; #[BoundToOpenApiEnum('NotificationCode')] enum PushNotificationKind: string { /* ... */ }An attribute that cannot be instantiated (for example, one with no argument) throws
EnumBindingExceptionwith reasonAttributeInvalid.Enum values are read only from the loaded specs. To keep enum values in separate source files,
$refthem fromcomponents.schemas. Gesso 3.0 removed binding to a spec file path. See the upgrade guide.A matched component whose
enumis not an array throwsEnumKeyNotArray.A component name that no configured spec defines with an
enumarray throwsEnumBindingExceptionwith reasonComponentNotFound.If two specs define the same component name with different
enumvalues, an enum that binds to it throwsComponentConflict. Unmatched duplicates are ignored, because unrelated APIs may both defineStatus. The same set in a different order is not a conflict.Auto-discovery skips backed enums that match no component and have no attribute. An explicit list passed to
assertNoDrift()/detectAll()throwsAttributeMissingfor them instead.
Reports and diagnostics name the binding as a JSON pointer, e.g. App\Enums\NotificationCode -> #/components/schemas/NotificationCode.
Auto-discovery also checks any enum in the scanned namespaces whose name matches a spec component. Such an enum fails the bootstrap if its values have drifted from that component, even if you never meant to bind it.
EnumDriftAsserter::assertNoDrift()
Call from any test (or from a dedicated drift-only test) to verify all bound enums match their spec enums. Pass the spec names to search for component bindings as specNames::
use Studio\Gesso\Schema\EnumDriftAsserter;
public function test_no_enum_drift(): void
{
EnumDriftAsserter::assertNoDrift([
\App\Enums\NotificationCodeEnum::class,
\App\Enums\ValidationErrorCodeEnum::class,
], specNames: ['front']);
}Signature: assertNoDrift(array $enumFqcns, bool $failOnDrift = true, array $specNames = []).
When drift is detected the asserter throws EnumDriftException with a structured diagnostic:
[OpenAPI Enum Drift] FATAL: 1 enum binding(s) drift from spec.
App\Enums\NotificationCodeEnum -> #/components/schemas/NotificationCodeEnum
PHP-only (1): "betaFeature"
Spec-only (1): "deprecated"
Action: align the PHP enum cases with the spec, or update the spec's enum array.To downgrade drift to a non-fatal warning (matches the failOnWarning ergonomic), pass failOnDrift: false:
EnumDriftAsserter::assertNoDrift([NotificationCodeEnum::class], failOnDrift: false);The asserter then fires one E_USER_WARNING containing the full drift report (every drifting binding aggregated into a single message) instead of throwing — failOnWarning="true" in phpunit.xml will still fail the run, but explicit warning suppressors will not. For programmatic access without the global error channel, use detectAll() (see below) and inspect the returned EnumDriftReport[] directly.
AssertsNoEnumDrift — PHPUnit trait
EnumDriftAsserter::assertNoDrift() works on a throw-on-failure / return-void-on-success contract, so PHPUnit never sees the call as a real assertion. Under PHPUnit 13's default beStrictAboutTestsThatDoNotTestAnything=true, drift tests that pass get flagged risky:
There was 1 risky test:
1) Tests\Unit\EnumDriftTest::no_drift
This test did not perform any assertionsThe AssertsNoEnumDrift trait wraps the same comparison and bumps PHPUnit's assertion counter on success — drop it into any TestCase:
use PHPUnit\Framework\Attributes\Test;
use PHPUnit\Framework\TestCase;
use Studio\Gesso\PHPUnit\AssertsNoEnumDrift;
class EnumDriftTest extends TestCase
{
use AssertsNoEnumDrift;
#[Test]
public function no_drift(): void
{
$this->assertNoEnumDrift([
\App\Enums\StatusEnum::class,
\App\Enums\RoleEnum::class,
], specNames: ['front']);
}
}Failures throw PHPUnit\Framework\AssertionFailedError with the same [OpenAPI Enum Drift] FATAL block as the static asserter, routed through Assert::fail() so PHPUnit's diff-aware reporter picks it up. Stack frames inside this library are filtered out so the failure points at the consumer's test line.
Misconfiguration (EnumBindingException — an enum that matches no component, an attribute naming an unknown component, a malformed enum array, etc.) is not wrapped — it bubbles unchanged so the structured $reason/$enumFqcn/$specPath properties stay accessible to downstream tooling.
The static EnumDriftAsserter::assertNoDrift() is unchanged. Non-PHPUnit consumers (dedicated drift CI scripts that catch EnumDriftException directly) keep working as before.
detectAll() — inspection without throwing
For dashboards or custom CI summaries that need every report (clean and drifting):
$reports = EnumDriftAsserter::detectAll([NotificationCodeEnum::class], specNames: ['front']);
foreach ($reports as $report) {
echo $report->enumFqcn, ' has drift: ', $report->hasDrift() ? 'yes' : 'no', "\n";
}Signature: detectAll(array $enumFqcns, array $specNames = [], bool $skipUnbound = false). With skipUnbound: true, enums that have no attribute and match no component are left out of the result instead of throwing AttributeMissing (this is what auto-discovery does).
Each EnumDriftReport carries enumFqcn, specPath, phpOnly, and specOnly as readonly properties. specPath is the #/components/schemas/Name pointer of the bound component.
Misconfiguration vs drift
EnumBindingException is thrown when the comparison cannot be performed at all — an enum with neither an attribute nor a matching component (AttributeMissing), an attribute naming a component that no spec defines (ComponentNotFound), a component defined with different values in two specs (ComponentConflict), target is not a backed enum, an enum that is not an array (EnumKeyNotArray), or an enum array entry is non-scalar (null / bool / nested arrays — backed PHP enums can only carry string or int). $reason carries an EnumBindingReason enum so you can branch programmatically. These errors fire regardless of failOnDrift — they are setup mistakes, not drift signals.
Auto-discovery via the PHPUnit extension
Manually enumerating every bound enum in a test method gets stale fast — a new bound enum added by another developer slips by silently until someone remembers to update the list. The PHPUnit extension can scan one or more PSR-4 namespace prefixes at bootstrap and run drift checks before any test executes.
Add the opt-in enum_drift section to the root gesso.php the extension reads (see Shared configuration):
<?php
declare(strict_types=1);
return [
'spec' => [
'base_path' => 'openapi/dist',
'names' => ['front'],
],
'enum_drift' => [
'enabled' => true,
'scan_namespaces' => ['App\\Enums', 'App\\Domain\\Enums'],
'fail_on_drift' => true,
],
];The v2 enum_drift_enabled, enum_drift_scan_namespaces, and enum_drift_fail_on_drift PHPUnit parameters were removed in 3.0; see UPGRADING.md.
gesso.php key | Default | Behaviour |
|---|---|---|
enum_drift.enabled | false | Master opt-in. |
enum_drift.scan_namespaces | none | List of PSR-4 namespace prefixes. Each prefix must match — directly or as a sub-namespace of — an entry in your composer.json autoload.psr-4 map. |
enum_drift.fail_on_drift | true | true aborts the run with a [OpenAPI Enum Drift] FATAL block on stderr (and GITHUB_STEP_SUMMARY when set). false emits a WARNING block but lets PHPUnit continue. |
| misconfiguration | n/a | No namespaces configured, an unresolvable namespace prefix, a missing Composer ClassLoader, or any EnumBindingException raised by a discovered enum always produces a FATAL exit regardless of enum_drift.fail_on_drift. These are setup errors and would otherwise hide a real drift signal. |
Discovery merges results from Composer's classmap (getClassMap()) and a recursive scan of each PSR-4-registered directory, deduplicating across both sources. Production deployments using --optimize-autoloader or --classmap-authoritative are covered by the classmap pass; default dev installs are covered by the PSR-4 directory walk. Every backed enum found is passed to EnumDriftAsserter together with the configured specs. Enums bound by attribute or by component name are checked, and backed enums that match neither are skipped. Pure enums, traits, abstract classes, and plain classes in the same directory are skipped too.
Every run that binds at least one enum first lists what it bound, on stderr and in GITHUB_STEP_SUMMARY. A clean run writes this list too:
[OpenAPI Enum Drift] 3 bound (2 by name, 1 by attribute), 41 unbound.
App\Enums\Color -> #/components/schemas/Color
App\Enums\IdpErrorEnum -> #/components/schemas/IdpAuthorizeErrorCode
App\Enums\OrderStatus -> #/components/schemas/OrderStatusAn enum with a #[BoundToOpenApiEnum] attribute counts as "by attribute", and any other bound enum counts as "by name". "Unbound" is the number of scanned backed enums that matched nothing, so they were skipped. When you rename a component that an enum bound by name, that enum becomes unbound. Nothing fails, but the counts and the list change, and the change shows in the PR's step summary.
A strict-mode (default) drift run then produces the same diagnostic block documented above:
[OpenAPI Enum Drift] FATAL: 1 enum binding(s) drift from spec.
App\Enums\NotificationCodeEnum -> #/components/schemas/NotificationCodeEnum
PHP-only (1): "betaFeature"
Spec-only (1): "deprecated"
Action: align the PHP enum cases with the spec, or update the spec's enum array.In 'fail_on_drift' => false mode the body is identical except for the severity prefix:
[OpenAPI Enum Drift] WARNING: 1 enum binding(s) drift from spec.
App\Enums\NotificationCodeEnum -> #/components/schemas/NotificationCodeEnum
PHP-only (1): "betaFeature"
Spec-only (1): "deprecated"
Action: align the PHP enum cases with the spec, or update the spec's enum array.PHPUnit exits normally in WARNING mode. failOnWarning="true" and failOnPhpunitWarning="true" do not catch this block — both flags only fire for warnings raised during test execution, not bootstrap-time stderr writes from an extension. If you need lenient drift to fail the build, gate on the stderr text in CI directly (e.g. phpunit ... 2>&1 | tee out && ! grep -q '\[OpenAPI Enum Drift\] WARNING' out).
If enum_drift.scan_namespaces resolves but no bound enums are found (none has an attribute and none is named after a spec component), the extension emits one [OpenAPI Enum Drift] NOTE: line to stderr and continues. This surfaces typo'd namespaces ("App\Enum" vs "App\Enums") without failing codebases that are mid-migration.
Under paratest or Pest --parallel the check runs once per run, in the process that starts it (paratest's master, Pest's orchestrator), so drift produces one stderr block and one GITHUB_STEP_SUMMARY block. Workers — processes with TEST_TOKEN set — skip the scan. A sequential run whose environment already sets TEST_TOKEN skips it as well; unset the variable, or use GESSO_SIDECAR_TOKEN for CI shards. See Parallel test runners.
Known limitations
oneOfenum unions (e.g.,code: oneOf: [CommonCode, AdminCode]) are not yet auto-resolved. Bind each PHP enum to its leaf component directly.x-enum-varnames/x-enum-descriptionsare not validated. Only theenumvalue array is compared.