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
16 changes: 16 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
4 changes: 2 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -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",
Expand Down
2 changes: 2 additions & 0 deletions src/generate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
60 changes: 52 additions & 8 deletions src/render-enum.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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 = [
Expand All @@ -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");

Expand Down Expand Up @@ -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,
Expand Down
100 changes: 100 additions & 0 deletions tests/generate.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -549,15 +549,115 @@ 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;",
"use Neutral\\Models\\AddressObject;",
]);
});

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(
Expand Down
Loading