From 02086ee9439c7842acc0e68e37dc021022a122b2 Mon Sep 17 00:00:00 2001 From: Maxim Kerstens Date: Mon, 9 Nov 2026 12:16:09 +0100 Subject: [PATCH] Add readable JSON and binary helpers to generated enums Generated enums now expose toReadableJson(), toBytes() and fromBytes() next to the dense JSON helpers, backed by Skir\Runtime\ReadableJson and Skir\Runtime\BinaryFormat. Both runtime classes are preplanned for every record file so generated records with the same basename are aliased safely. Bumps the package to 0.2.0. --- README.md | 16 +++++++ package-lock.json | 4 +- package.json | 2 +- src/generate.ts | 2 + src/render-enum.ts | 60 +++++++++++++++++++++---- tests/generate.test.ts | 100 +++++++++++++++++++++++++++++++++++++++++ 6 files changed, 173 insertions(+), 11 deletions(-) diff --git a/README.md b/README.md index f0dd932..b8f73ea 100644 --- a/README.md +++ b/README.md @@ -102,6 +102,22 @@ The core passes the complete `NormalizedType` at each target-specific conversion The core uses `manifestObjectClass()` for struct requests and record responses after unwrapping optionals. The manifest remains schema version `SERVER_MANIFEST_VERSION`. +## Shared enum surface + +The core renders every Skir enum as a `final readonly` wrapper around `Skir\Runtime\EnumValue`, independent of the adapter. Besides one named constructor per constant or wrapper variant, `name()`, `payload()` and `skirType()`, each enum exposes these serialization methods: + +| Method | Purpose | +| --- | --- | +| `toSkirValue()` / `fromSkirValue(EnumValue $value)` | Converts to and from the runtime `EnumValue`. | +| `toDenseValue()` / `fromDenseValue(int\|array $value)` | Converts to and from the decoded dense JSON value. | +| `toDenseJson()` / `fromDenseJson(string $json)` | Encodes dense JSON and decodes dense or readable JSON. | +| `toReadableJson()` | Encodes readable JSON. Decode readable JSON with `fromDenseJson()`, which accepts both flavors. | +| `toBytes()` / `fromBytes(string $bytes)` | Encodes and decodes the Skir binary format. | + +Adapters that render structs should expose the same `toReadableJson()`, `toBytes()` and `fromBytes()` names so generated code is consistent across targets. The readable JSON and binary helpers require a `php-skir/runtime` version that provides `Skir\Runtime\ReadableJson` and `Skir\Runtime\BinaryFormat`. + +Compatibility delta in 0.2.0: generated enums gained `toReadableJson()`, `toBytes()` and `fromBytes()`, and the core now preplans `Skir\Runtime\BinaryFormat` and `Skir\Runtime\ReadableJson` for every record file. Generated records named `BinaryFormat` or `ReadableJson` therefore keep their basename while the runtime classes are aliased. + ## Optional validation overlays Validation is an adapter capability, not automatic core behavior. Validation-aware targets can include `ValidationConfig` in their own configuration schema and call `resolveValidationRules(schema, config)` from `prepare()`. The resolver validates exact module, qualified-record, and original Skir field selectors and returns rules grouped by normalized record identity. The target decides how those string rules are rendered and executed. diff --git a/package-lock.json b/package-lock.json index ab24b1b..770ba7e 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "@php-skir/generator-core", - "version": "0.1.1", + "version": "0.2.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@php-skir/generator-core", - "version": "0.1.1", + "version": "0.2.0", "license": "MIT", "dependencies": { "jsonc-parser": "^3.3.1", diff --git a/package.json b/package.json index 63c9cc0..ed3e47d 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@php-skir/generator-core", - "version": "0.1.1", + "version": "0.2.0", "description": "Shared generation core for PHP Skir code generators.", "type": "module", "license": "MIT", diff --git a/src/generate.ts b/src/generate.ts index 9e5d7fa..64f6707 100644 --- a/src/generate.ts +++ b/src/generate.ts @@ -116,9 +116,11 @@ function renderRecord( [className], [ ...plannedImports, + "Skir\\Runtime\\BinaryFormat", "Skir\\Runtime\\DenseJson", "Skir\\Runtime\\EnumValue", "Skir\\Runtime\\Field", + "Skir\\Runtime\\ReadableJson", "Skir\\Runtime\\Type", "Skir\\Runtime\\Variant", ...targetImports, diff --git a/src/render-enum.ts b/src/render-enum.ts index c0b0557..f31c525 100644 --- a/src/render-enum.ts +++ b/src/render-enum.ts @@ -10,6 +10,13 @@ import type { import { toPropertyName } from "./naming.js"; import { indent, renderPhpFile } from "./php.js"; +const BINARY_FORMAT = "Skir\\Runtime\\BinaryFormat"; +const DENSE_JSON = "Skir\\Runtime\\DenseJson"; +const ENUM_VALUE = "Skir\\Runtime\\EnumValue"; +const READABLE_JSON = "Skir\\Runtime\\ReadableJson"; +const TYPE = "Skir\\Runtime\\Type"; +const VARIANT = "Skir\\Runtime\\Variant"; + export function renderEnum( record: NormalizedRecord, context: RenderContext, @@ -21,15 +28,19 @@ export function renderEnum( const className = classNameForRecord(record, context); const runtimeImports = [ - "Skir\\Runtime\\DenseJson", - "Skir\\Runtime\\EnumValue", - "Skir\\Runtime\\Type", - "Skir\\Runtime\\Variant", + BINARY_FORMAT, + DENSE_JSON, + ENUM_VALUE, + READABLE_JSON, + TYPE, + VARIANT, ] as const; - const denseJson = importClass(context.imports, runtimeImports[0]); - const enumValue = importClass(context.imports, runtimeImports[1]); - const typeClass = importClass(context.imports, runtimeImports[2]); - const variant = importClass(context.imports, runtimeImports[3]); + const binaryFormat = importClass(context.imports, BINARY_FORMAT); + const denseJson = importClass(context.imports, DENSE_JSON); + const enumValue = importClass(context.imports, ENUM_VALUE); + const readableJson = importClass(context.imports, READABLE_JSON); + const typeClass = importClass(context.imports, TYPE); + const variant = importClass(context.imports, VARIANT); const constructors = renderEnumConstructors(record, context, adapter, enumValue); const skirType = renderEnumSkirType(record, context, adapter, typeClass, variant); const body = [ @@ -54,6 +65,12 @@ export function renderEnum( indent(renderEnumToDenseJson(denseJson)), "", indent(renderEnumFromDenseJson(className, denseJson)), + "", + indent(renderEnumToReadableJson(readableJson)), + "", + indent(renderEnumToBytes(binaryFormat)), + "", + indent(renderEnumFromBytes(className, binaryFormat)), "}", ].join("\n"); @@ -228,6 +245,33 @@ function renderEnumFromDenseJson(className: string, denseJson: string): string { ].join("\n"); } +function renderEnumToReadableJson(readableJson: string): string { + return [ + "public function toReadableJson(): string", + "{", + ` return ${readableJson}::toJson(self::skirType(), $this->value);`, + "}", + ].join("\n"); +} + +function renderEnumToBytes(binaryFormat: string): string { + return [ + "public function toBytes(): string", + "{", + ` return ${binaryFormat}::encode(self::skirType(), $this->value);`, + "}", + ].join("\n"); +} + +function renderEnumFromBytes(className: string, binaryFormat: string): string { + return [ + `public static function fromBytes(string $bytes): ${className}`, + "{", + ` return new self(${binaryFormat}::decode(self::skirType(), $bytes));`, + "}", + ].join("\n"); +} + function runtimeTypeExpression( type: NormalizedType, context: RenderContext, diff --git a/tests/generate.test.ts b/tests/generate.test.ts index aaca43f..8363c11 100644 --- a/tests/generate.test.ts +++ b/tests/generate.test.ts @@ -549,8 +549,10 @@ describe("generatePhp", () => { const enumFile = files.find((file) => file.path === "Events/StatusObject.php"); expect(useStatements(enumFile?.code)).toEqual([ + "use Skir\\Runtime\\BinaryFormat;", "use Skir\\Runtime\\DenseJson;", "use Skir\\Runtime\\EnumValue;", + "use Skir\\Runtime\\ReadableJson;", "use Skir\\Runtime\\Type;", "use Skir\\Runtime\\Variant;", "use Neutral\\Models\\AccountObject;", @@ -558,6 +560,104 @@ describe("generatePhp", () => { ]); }); + it("renders readable JSON and binary helpers after the dense JSON helpers on enums", () => { + const files = generatePhp({ + namespace: "Neutral", + modules: [{ + path: "events/status.skir", + records: [{ + kind: "record", + name: "Status", + recordType: "enum", + fields: [{ + kind: "field", + name: "expires_at", + number: 2, + type: "timestamp", + }], + }], + }], + adapter: new RecordingAdapter(), + }); + const source = files.find((file) => file.path === "Events/StatusObject.php")?.code ?? ""; + + expect(source).toContain([ + " public static function fromDenseJson(string $json): StatusObject", + " {", + " return new self(DenseJson::fromJson(self::skirType(), $json));", + " }", + "", + " public function toReadableJson(): string", + " {", + " return ReadableJson::toJson(self::skirType(), $this->value);", + " }", + "", + " public function toBytes(): string", + " {", + " return BinaryFormat::encode(self::skirType(), $this->value);", + " }", + "", + " public static function fromBytes(string $bytes): StatusObject", + " {", + " return new self(BinaryFormat::decode(self::skirType(), $bytes));", + " }", + "}", + ].join("\n")); + }); + + it("aliases the runtime serializers when generated records reserve their basenames", () => { + class SerializerCollisionAdapter extends RecordingAdapter { + public override recordClassName(record: NormalizedRecord): string { + this.calls.push(`class:${record.identity}`); + + return ["BinaryFormat", "ReadableJson"].includes(record.qualifiedName) + ? record.qualifiedName + : super.recordClassName(record); + } + } + + const files = generatePhp({ + namespace: "Neutral", + modules: [{ + path: "models/serializers.skir", + records: [{ + kind: "record", + name: "BinaryFormat", + recordType: "struct", + fields: [], + }, { + kind: "record", + name: "ReadableJson", + recordType: "struct", + fields: [], + }, { + kind: "record", + name: "Status", + recordType: "enum", + fields: [{ + kind: "field", + name: "active", + number: 1, + }], + }], + }], + adapter: new SerializerCollisionAdapter(), + }); + const enumFile = files.find((file) => file.path === "Models/StatusObject.php"); + + expect(useStatements(enumFile?.code)).toEqual([ + "use Skir\\Runtime\\BinaryFormat as RuntimeBinaryFormat;", + "use Skir\\Runtime\\DenseJson;", + "use Skir\\Runtime\\EnumValue;", + "use Skir\\Runtime\\ReadableJson as RuntimeReadableJson;", + "use Skir\\Runtime\\Type;", + "use Skir\\Runtime\\Variant;", + ]); + expect(enumFile?.code).toContain("return RuntimeReadableJson::toJson(self::skirType(), $this->value);"); + expect(enumFile?.code).toContain("return RuntimeBinaryFormat::encode(self::skirType(), $this->value);"); + expect(enumFile?.code).toContain("return new self(RuntimeBinaryFormat::decode(self::skirType(), $bytes));"); + }); + it("adapts enum wrapper storage and payload exposure through optional target hooks", () => { class EnumPayloadAdapter extends RecordingAdapter { public enumPayloadToSkirExpression(