Skip to content
Back to skills

Skmtc Lang Php

ASecurity

The PHP target-language layer for Skmtc generators (@skmtc/lang-php). It covers the projection base factories, PhpSnippet, the register shape with class imports, the five identifier kinds, one folder as one namespace, the head and value render model, methods as members of a class, null for absent values, the declaration and type positions of a schema, the producers for classes, enums, methods, calls, arrays and names, and the conventions of the reference SDK. Use ALONGSIDE skmtc-generator whe...

  • 20 stars
  • 0 votes
  • 0 copies
  • 0 views
  • Added December 3, 2026
developmentgophpexpressgitapi

Works with

  • cli
  • api

Security analysis

A100/100

Scanned December 4, 2026

npx -y skills add skmtc/skmtc --skill skmtc-lang-php --agent claude-code

Installs into .claude/skills of the current project.

Are you the author of Skmtc Lang Php?

Add the live security badge to your README. It updates with every re-scan.

Security grade badge for Skmtc Lang Php
[![Security: A — Skills Directory](https://www.skillsdirectory.com/api/skills/skmtc-skmtc-lang-php/badge)](https://www.skillsdirectory.com/skills/skmtc-skmtc-lang-php)

More formats (shields.io, HTML) on the badges page. Keep it an A: scan every change in CI with Pro.

Download with Pro
SKILL.md
---
name: skmtc-lang-php
version: 0.2.0
description: >
  The PHP target-language layer for Skmtc generators (@skmtc/lang-php). It
  covers the projection base factories, PhpSnippet, the register shape
  with class imports, the five identifier kinds, one folder as one
  namespace, the head and value render model, methods as members of a
  class, null for absent values, the declaration and type positions of a
  schema, the producers for classes, enums, methods, calls, arrays and
  names, and the conventions of the reference SDK. Use ALONGSIDE
  skmtc-generator whenever a generator writes PHP.
metadata:
  internal: true
---

# The PHP layer (@skmtc/lang-php)

Read `skmtc-generator` first. The two worked examples are
`@skmtc/gen-php-dto` (a model generator) and `@skmtc/gen-php-guzzle` (an
SDK: an Index for each service, and an accumulator for the client).
Generated code needs PHP 8.2 or later. The style of both follows
`openai-php/client` (section 13).

Import each module by its own path (`@skmtc/lang-php/PhpList`), and not
from the root of the package. Do the same for core
(`@skmtc/core/OasOperation`).

## 1. Declare the language

The import graph declares the language. `src/base.ts` imports a factory,
and each snippet extends `PhpSnippet`.

```ts fragment
import { PhpName } from '@skmtc/lang-php/PhpName'
import { toPhpModelProjectionBase } from '@skmtc/lang-php/toPhpModelProjectionBase'

export const PhpDtoBase = toPhpModelProjectionBase<EnrichmentSchema>({
  id: denoJson.name,
  toIdentifierName({ ref }) {
    return new PhpName(toModelName(ref)).toClassName()
  },
  toIdentifierType,
  toExportPath({ ref, enrichments, variant }) {
    const name = this.toIdentifierName({ ref, enrichments, variant })

    return `@/Model/${name}.php`
  },
})
```

The factories are `toPhpModelProjectionBase`,
`toPhpOasOperationProjectionBase` and `toPhpOasOperationIndexBase`.

## 2. A folder is a namespace

PSR-4 gives one folder to a namespace prefix, and each folder below it is
one more part of the namespace.

- **`settings.packages` gives a folder its prefix.**
  `{ "rootPath": "Model", "moduleName": "Acme\\Shop\\Model" }` puts
  `@/Model/Order.php` in `Acme\Shop\Model`.
- **A file in no package gets its namespace from its folders.** They are
  the folders below `basePath`: `Model`. A file at the top is in the
  global namespace, and has no `namespace` line.
- **Put the files in a folder.** The workspace root cannot be a package
  root, so a file at the top can never get a prefix.
- **Each folder of an export path must be a PHP name.** `PhpFile` stops
  the run for `@/pet-store/Order.php`.
- **The name of a file is the name of its class.** PSR-4 finds `Order` in
  `Order.php`. The engine adds `.generated` to each file name by default
  (`settings.generatedSuffix`). A project that loads classes by PSR-4
  sets it to `""`. A class map of Composer loads any file name.
- **A file that you register yourself gets the suffix from
  `toGeneratedPath(context, path)`.** The engine adds the suffix to the
  export path of a projection only.
- **Each name is one class in the namespace.** `toNameScope` is the
  folder, so the engine gives the second model that claims a name a
  counter (`Order2`).

## 3. Register

| Caller | Call | File |
|---|---|---|
| Projection | `this.register(args)` | Its own export file |
| Projection | `this.registerInto(path, args)` | The file you name |
| Snippet | `this.register({ ...args, destinationPath })` | The file you name |

`args` is `{ imports?, definitions?, custom? }`. There is no `reExports`.

- An import is the full name of a class:
  `imports: ['JsonException', 'GuzzleHttp\\Client']`. An alias is
  `{ name: 'GuzzleHttp\\Client', alias: 'HttpClient' }`. The file writes a
  `use` line, and the code names the class by its short name.
- **Register a class of PHP too, or write its full name.** In a file with
  a namespace, PHP reads `JsonException` as a class of that namespace.
  The `use` line makes it PHP's own. A backslash before the name does the
  same with no `use` line: `\JsonSerializable`. Use the full name for a
  class that every file names, so no model can have its short name.
- A class that a generator declares itself in another file is
  `{ name: 'OrderGift', path: '@/Model/OrderGift.php' }`. The engine
  registers this form for each model that you insert.
- The file writes no `use` line for a class of its own namespace. In the
  global namespace it writes none for a name with no namespace: PHP
  warns about such a line.
- **One short name is one class in a file.** A `use` line can give the
  name of a class of the file's own namespace to another class. PHP
  reports nothing. The code then reads the other class, and fails when it
  runs. So `PhpFile` fails the run for such an import, and the message
  names both classes.
- With no `custom`, a file starts with `<?php`,
  `// Code generated by Skmtc. DO NOT EDIT.` and
  `declare(strict_types=1);`.

## 4. Identifier kinds

| Kind | Factory | Renders |
|---|---|---|
| `class` | `createClass(name, { modifiers })` | `final readonly class Order` + value |
| `interface` | `createInterface(name)` | `interface HasId` + value |
| `enum` | `createEnum(name)` | `enum OrderStatus` + value |
| `trait` | `createTrait(name)` | `trait ReadsJson` + value |
| `method` | `createMethod(name, { modifiers })` | `public function getPet` + value |

- The modifiers of a `class` are the `typeName` of its identifier. In
  `toIdentifierType`, return `finalReadonlyClass`, which is
  `{ type: 'class', typeName: 'final readonly' }`. The modifiers of a
  `method` are there too: `{ type: 'method', typeName: 'public' }`.
- A `method` is a member of a class. Only an Index holds one (section
  6), and a file has none at its top level.
- **PHP has no second name for a type.** A schema that is a scalar, an
  array, a map or a union has no declaration. A generator leaves it out
  with `isSupported` on its entry. It writes the type of the schema at
  each place that refers to it (section 11).
- No class is private to its file, so `exported` and `noExport` render
  nothing.

## 5. Head and value

The identifier renders the head of a declaration, and the value renders
all that follows. The value of a `class` is a `PhpClassValue`, which
starts with ` implements …`. The value of an `enum` is a `PhpEnumValue`,
which starts with `: string`.

**A doc comment is above its declaration**, where the value cannot write
it. A definition reads the `description` field of its value. The field
holds a string of the document, or a producer that renders the text:

```ts fragment
export class ServiceMethod extends ServiceMethodBase {
  description: MethodDescription
  tags: PhpListItem<PhpDocTag>[]
  value: PhpFunctionValue
  …
}
```

A value with a `tags` field gives the tags of the doc comment too:
`tags: [new PhpDocTag({ name: 'throws', value: 'ApiException' })]`. A
method projection sets it for `@param`, `@return` and `@throws`.

## 6. A method is a member of a class

PHP declares a method inside the braces of its class. An Index is the
class, and its members are the methods:

```ts fragment
this.value = new PhpClassValue({
  members: [
    new PhpMethodSet({ members: [constructor], methods: this.definitions }),
  ],
})
```

`PhpMethodSet` renders the members that the class always has, and then
each method. Give it the `definitions` array of the Index itself: the
methods arrive after the constructor, and the method set reads the array
when it renders. A member projection states `toIndex: () => TheIndex`
and no `toExportPath`. Its value is a `PhpFunctionValue`.

`gen-php-guzzle` keeps the config of both bases in `src/base.ts`. The
base of a member takes the Index as an argument
(`toServiceMethodBase(Service)`), so `base.ts` does not import the class
of the Index.

## 7. `null` is the absent value

PHP has no value for "not there". A property that is not in `required`,
and a value that can be `null`, are both `null`.

- `PhpNullable({ type, nullable })` writes `?Pet`. With `union: true` it
  writes `list<Pet>|null`, the form for a doc comment and for a union
  of types (`Cat|Dog|null`).
- PHP refuses `?mixed` and `?null`. Do not wrap those.
- Decide `null` in one class (`PhpDtoNullability` in `gen-php-dto`). The
  type of a value and the code that reads it both ask it.
- `PhpParameter({ optional: true })` writes the default: ` = null`.
  `defaultValue` gives another default, such as `[]`. A parameter with a
  default must be after each parameter with none. Give `PhpConstructor`
  the properties with no default first.
- `PhpOrNull(value)` reads a key that can be absent:
  `$attributes['note'] ?? null`. `PhpWhenSet({ subject, value })` makes a
  value only when its source is there:
  `isset($attributes['pet']) ? Pet::from($attributes['pet']) : null`.
- A class refers to itself by name. PHP finds a class when the code runs,
  so a reference inside a cycle has no other form.

## 8. Indentation

PSR-12 writes four spaces for each level. A producer renders its own
lines from column 0. `PhpBlock`, `PhpArray`, `PhpArguments`,
`PhpConstructor`, `PhpMatch` and `PhpIndented` are the only code that
writes the spaces, so blocks nest to any depth. Do not write an indent in
a template.

A producer does not wrap a long line. A project sets `settings.formatter`
to its formatter.

## 9. Producers

Only `toString()` writes target code. A constructor stores producers and
facts: a name, a path, a flag. For PHP syntax that two generators share,
use a producer of this package and do not write the syntax in a
generator.

| Producer | Renders |
|---|---|
| `PhpList.toArguments(items)`, `.toLines`, `.toCommaLines`, `.toParagraphs`, `.toUnion` | `a, b`. One item on each line. The same with a comma after each. A blank line between items. `Cat\|Dog` |
| `PhpBlock(items, { separator? })` | `{`, the items one level deeper, `}` |
| `PhpClassValue({ interfaces?, members })` | ` implements \JsonSerializable`, then the members in braces |
| `PhpConstructor({ parameters, statements? })` | `public function __construct(`, one parameter on each line, `) {` and `}` |
| `PhpParameter({ name, type, modifiers?, optional?, defaultValue?, description?, tags? })` | `public ?string $note = null`, with its doc comment above |
| `PhpMethod({ name, modifiers, parameters, returnType, statements, description?, tags? })` | A method with its doc comment above |
| `PhpFunctionValue({ parameters, returnType, statements })` | `(int $petId): Pet`, then the body in braces: the value of a `method` definition |
| `PhpMethodSet({ members, methods })` | The members of a class that is an Index, with a blank line between them |
| `PhpEnumValue({ backing, cases })`, `PhpEnumCase({ name, value, description? })` | `: string` or `: int`, then `case Pending = 'pending';` for each case |
| `PhpArray(items)`, `PhpArrayEntry({ key, value })`, `PhpSpread(value)` | `[`, one item on each line, `]`. `'key' => value`. `...value` |
| `PhpCall({ callee, arguments, lines? })` | `array_map($function, $items)` |
| `PhpNew({ className, arguments, lines? })` | `new PetsService($this->transport)` |
| `PhpStaticCall({ className, method, arguments, lines? })` | `Pet::from($data)` |
| `PhpMethodCall({ object, method, arguments, lines? })` | `$this->transport->request(…)` |
| `PhpNamedArgument({ name, value })` | `id: $attributes['id']` |
| `PhpVariable(name)`, `PhpPropertyAccess({ object?, name })`, `PhpArrayAccess({ array, key })` | `$petId`. `$this->shipTo`. `$attributes['ship_to']` |
| `PhpString(value)` | `'application/json'` |
| `PhpOrNull(value)`, `PhpWhenSet({ subject, value })`, `PhpIsNotNull(value)` | `x ?? null`. `isset(x) ? y : null`. `x !== null` |
| `PhpObjectCast(value)` | `(object) $this->labels`: a JSON object from an array |
| `PhpMatch({ subject, arms })`, `PhpMatchArm({ pattern?, value })`, `PhpThrow(error)` | `match (x) {`, one arm on each line, `}`. `'cat' => y`, or `default => y` with no pattern. `throw new …` |
| `PhpArrowFunction({ parameters, returnType, body })` | `static fn (mixed $item): Pet => Pet::from($item)` |
| `PhpReturn(value)` | `return …;` |
| `PhpPathFormat(path)`, `PhpPathLiteral(format)` | `'pets/%s'`, and `.placeholders`. `'pets'` for a path with no parameter |
| `PhpNullable({ type, nullable, union? })` | `?Pet`, `Pet`, or `list<Pet>\|null` |
| `PhpDocBlock({ description?, tags? })`, `PhpDocTag({ name, value })`, `PhpDocParam({ type, name })` | A doc comment, or nothing. `@var list<Pet>`. `list<Pet> $pets` |
| `PhpDocLines(content)`, `PhpDocText(text)` | The lines of a doc comment, with ` * ` before each. The text of a comment, which cannot end the comment |
| `PhpDocList(items)`, `PhpDocMap(values?)` | `list<Pet>`. `array<string, int>`, or `array<string, mixed>` |

A call writes its arguments on one line. With `lines: true` it writes one
argument on each line, with a comma after each.

An item that is `undefined` or `null` is absent. `PhpBlock`,
`PhpClassValue` and `PhpMethodSet` read their array when they render.

A producer of a generator can extend one of these and give it its parts
in `super(…)`. It then needs no `toString()` of its own:
`class TransportRequest extends PhpMethodCall`.

## 10. Names and literals

- `new PhpName(text).toClassName()` gives the name of a class, an
  interface, an enum and a trait: `order_status` gives `OrderStatus`.
  PHP reads the name of a class in any case. So a keyword and a type of
  PHP get an underscore at the end (`List_`, `String_`).
- `.toCaseName()` gives the name of a case of an enum: `in_transit`
  gives `InTransit`. Of the keywords, only `class` gets an underscore at
  the end.
- `.toVariableName()` gives the name of a property, a parameter and a
  variable, with no `$`: `ship_to` gives `shipTo`. Only `this` gets an
  underscore at the end.
- A PHP name cannot start with a digit. Such a name starts with `_` in
  each of the three forms: the enum value `1st` gives the case `_1st`.
- Lower case letters after digits stay in the word of the digits:
  `2nd line` gives `_2ndLine`, and not `_2NdLine`.
- `.with(text)` adds words to a name: `new PhpName('Order').with('ship_to')`
  is the name of `OrderShipTo`. A part of a declaration that needs a name
  takes the name of its parent first (section 11).
- Each form is a valid PHP name for any text. A text with no letter and
  no digit gets a name from its characters: `Empty`, `U43` for `+`.
- `new PhpVariableNames(reserved).claim(key)` gives each key of one list
  a PHP name of its own. The list is the properties of a class, or the
  parameters of a method. Two keys can give one PHP name (`user-id` and
  `user_id`), and the second one gets a number. `PhpCaseNames` does the
  same for the cases of an enum. `PhpNameScope` takes a name that is
  already a PHP name.
- `PhpClassName.parse('GuzzleHttp\\Client')` has the `namespace` and the
  `short` name of a full name.
- `PhpString(value)` writes a string of the document in single quotes
  when it renders. Use it for each key and enum value, and never write a
  quote in a template. In single quotes, PHP reads no `$`, and only two
  escapes.
- `PhpDocBlock` writes `*/` of the document with a space, so text cannot
  end the comment.

## 11. A declaration and a type position differ

PHP writes one schema in two positions: where a declaration has it, and
where a type refers to it. `gen-php-dto` has one router, `toPhpDtoValue`,
for the second position. `base.ts` says which schemas have a
declaration.

| Function | Gives | For an array of `$ref: Pet` |
|---|---|---|
| `toPhpDtoValue` (the router) | The producer of a schema where it is used. It renders the PHP type | `array` |
| `toPhpDtoDeclarationValue` (`base.ts`) | The declaration of a schema: a class, an enum, or none | None |

The producer of a used schema has three more parts. The place that uses
the schema reads them:

| Field | Holds | For an array of `$ref: Pet` |
|---|---|---|
| `doc` | The type in a doc comment, or `undefined` when the PHP type says all | `list<Pet>` |
| `read` | The code that makes the value from the `expression` that `json_decode` gave | `array_values(array_map(static fn (mixed $item): Pet => Pet::from($item), $attributes['pets']))` |
| `write` | The code that gives the value to `json_encode` | `$this->pets` |

- **Name a function that tests `schema.type` `to<X>Value`.** The lint
  rule `skmtc/single-dispatch` allows the test in a function with such a
  name, and in `toIdentifierType` and `isSupported`.
- **`base.ts` says which schemas have a declaration.**
  `toPhpDtoDeclarationValue` gives a class declaration, an enum
  declaration, or none. A declaration holds the narrowed schema. The
  entry (`isSupported`), the base (`toIdentifierType`), the projection
  and the router all read it. Thus no second function chooses between a
  class and an enum.
- **A `$ref` to a schema with no declaration gets the type of its
  target.** The `ref` case calls the router with the target
  (`PhpDtoRefTarget`). A component that is only a `$ref` is such a
  schema. A reference to it has the type of its target.
- **A cycle of such schemas ends with `mixed`.** The router carries the
  pointer of each component that it writes in place (`inPlace`). A `$ref`
  back to one of them is `PhpDtoUnknown`. Core gives no cycle answer
  here: `toModelRef` needs a projection, and these targets have none.
- **Read a list with `array_values(array_map(…))`.** PHPStan reads
  `array_map` as `array<T>`, and `array_values` makes it `list<T>`. A map
  keeps `array_map` alone, because it needs its keys.
- **An inline object declares a class in a file of its own**, and
  renders the name of that class. The class takes the name of its parent
  first. The router gets an `inlineName` (a `PhpName`). Each producer
  that goes one level down asks `base.ts` for the next name:
  `toPropertyClassName`, `toItemClassName`, `toValueClassName`,
  `toMemberClassName`.
- The first name comes from the caller. A model gives its own name
  (`OrderShipTo`). A component with no declaration gives the name of the
  component (`LinesItem`). An operation generator gives the name of its
  method (`CreateApiPetsBody`).
- Look for that class with `findInlineType`, not with
  `context.findDefinition`:

  ```ts fragment
  findInlineType(context, { name, stackTrail: schema.stackTrail, destinationPath }) ??
    this.defineAndRegister({ identifier: createClass(name), value, destinationPath })
  ```

  A second walk of one schema gets the class of the first. A name that
  is the class of another schema fails the run. Make the value of the
  class with `stackTrail: schema.stackTrail`.

## 12. Pitfalls

| Symptom | Fix |
|---|---|
| `Class "Acme\Model\JsonException" not found` | The producer that writes the name of a class of PHP did not register it. Register `'JsonException'`, or write `\JsonException` |
| `The use statement with non-compound name … has no effect` | A template has a `use` line. Register the import: the file leaves it out in the global namespace |
| `names two classes 'Transport'` | A model has the short name of a class that the file imports (section 3). Give one of them another name: in the document, or in `base.ts` of a clone |
| `Cannot redeclare class` | Two files declare one name, or two names that differ in case only. Give one of them another name in `base.ts` |
| `Optional parameter $a declared before required parameter $b` | Give `PhpConstructor` and `PhpFunctionValue` the parameters with no default first |
| A class renders with no methods | `PhpMethodSet` got a copy of `definitions`. Give it the array itself |
| `this Index does not hold that kind of declaration` | A member of an Index is not a `method`. Return `{ type: 'method', typeName: 'public' }` from its `toIdentifierType` |
| `Type mixed cannot be marked as nullable` | `PhpNullable` got `mixed`. `null` is one of its values |
| `Duplicate type string is redundant` | A union type names one type two times. Give `PhpList.toUnion` each type one time |
| `Cannot use 'String' as class name as it is reserved`, or a parse error at a class name | `PhpName.toClassName()` did not make the name |
| `Undefined array key` | The code reads a key that can be absent with no `PhpOrNull` and no `PhpWhenSet` |
| `cannot be a PHP file: PSR-4 reads each folder as a part of the namespace` | A folder of the export path is not a PHP name. Change it in `toExportPath` |
| Composer does not find a generated class | The file is `Order.generated.php`. Set `settings.generatedSuffix` to `""`, or load the folder with a class map |
| `has two schemas for the class 'OrderShipTo'` | Two inline schemas give one class name, or an inline schema has the name of a component (section 11). Move the inline one to `components.schemas` under its own name, or change the name in a clone of the generator |
| A JSON array `[]` where the API wants `{}` | `json_encode` writes an empty PHP array as `[]`. Give it an object: `PhpObjectCast` |
| PHPStan: `expects list<Pet>, array<Pet> given` | The read of a list has no `array_values` around `array_map` |
| `skmtc/single-dispatch` reports a test of `schema.type` | The test is outside a router. Read the fact from the producer that the router made, or from `toPhpDtoDeclarationValue` |

## 13. The reference SDK

The style of the generated code follows a hand-written SDK:
`openai-php/client`, at commit
`54e5df38bcfc35bcc603db16bfbf3f610517ee28` (2026-11-28, MIT,
<https://github.com/openai-php/client>). It needs PHP 8.2. The second
reference, for typed method signatures, is
`anthropics/anthropic-sdk-php` at commit `bdb40d1`.

### Conventions we follow

1. Each file starts with `declare(strict_types=1);` and has one class.
   The namespace follows the folder (PSR-4).
2. A model is a `final` class whose constructor promotes `public`
   properties. It has no setters and no getters.
3. Property names are camelCase. Wire names stay as they are in the
   JSON, and `from()` has each name. There is no reflection and no
   attribute map.
4. Model class names are PascalCase, and a nested type takes the name of
   its parent as a prefix: `CreateResponseChoice`.
5. A model has `public static function from(array $attributes): self`
   to decode. `from()` calls the constructor with named arguments.
6. Optional and nullable both become a nullable PHP type (`?T`). `from()`
   reads an optional key with `?? null`.
7. The encoded JSON leaves out a `null` value of an optional property.
8. An enum is a native backed enum, `enum Name: string` or
   `enum Name: int`, with PascalCase cases. `Enum::from($value)` decodes
   it.
9. The `from()` of its class decodes a nested object. A nullable one
   uses `isset(…) ? X::from(…) : null`. The reference has a truthiness
   test in one place, which turns an empty object into `null`. Do not
   copy that.
10. An array of objects has the type `array`, with the item type in a doc
    comment. `array_map` and a typed arrow function decode it.
11. A map has the type `array`, with `array<string, V>` in a doc comment.
12. A union with a discriminator is a native union of the member classes
    (`Cat|Dog`). A `match` on the discriminator decodes it, with a
    `default` arm that throws an `\UnexpectedValueException`. A union of
    scalars is a native union too (`string|int`).
13. Dates stay in the wire type: a date string is a `string`.
14. Doc comments are short. A method gets one sentence from the
    document.
15. The client is a `final` class that takes the transport in its
    constructor. It has one method for each resource, which returns a
    new resource object. A resource is a `final` class with one public
    method for each operation.
16. A client method has three steps: build the request, send it, decode
    the result. The return type is the model class.
17. Path parameters are the first arguments, in camelCase.
18. The runtime decodes JSON once
    (`json_decode($contents, true, flags: JSON_THROW_ON_ERROR)`), and
    the `from()` of the model turns the array into objects.
19. Errors are a small set of `final` exception classes. The status
    checks are in the runtime only.
20. A person writes the runtime, once. A generator writes the client,
    the resources, the models and the enums.

### Where we differ, and why

| The reference | Generated code | Why |
|---|---|---|
| `public readonly` on each property | `final readonly class` | The PHP 8.2 form. The reference came from PHP 8.1 |
| A private constructor | A public constructor, properties with no default first | A generated class is a request body too |
| `toArray()`, which calls `toArray()` and `->value` of each nested value | `jsonSerialize()` of `\JsonSerializable`, which gives an object (`\stdClass`) | `json_encode` then writes each nested class and each case of an enum by its own rule. An object with no value is `{}`, where an empty array is `[]` |
| A model gets no prose | A model gets the `description` of the document, above the class and above each property | The document has the text, and an editor shows it |
| A union with no discriminator is a native union, decoded with `match (true)` on `is_string`, `is_array` | `mixed`, when one member is not a scalar | The default generator does not write a test that tells two classes apart |
| An enum for each schema enum | An enum for each component that is an enum. An inline enum is a `string` or an `int` | An inline enum would get the name of its parent, and real documents often have a component with that name. The run then fails |
| A wrapper for the `GuzzleException` of a network failure | The `GuzzleException` itself, with a `@throws` line on each method | A caller of Guzzle knows that exception. A wrapper is one more class to write by hand |
| `array $parameters` for the query and the body | Typed parameters: the ones with no default first, then nullable ones with `= null` and a `@param` line for an array | The document has the types |
| One array for query and body | `query`, `headers` and `body` apart, with the wire name as the key | The document says where each one goes |
| A PSR-18 client and hand-made PSR-7 requests | A Guzzle client, in a hand-written transport | The library choice of `gen-php-guzzle` |
| A model with the name of the call (`RetrieveResponse`) | A model with the name of its component schema. An inline body or response has the name of its method (`CreateApiPetsBody`) | A component has a name already |
| Method names are verbs (`retrieve`) | The name comes from the method and the path (`getApiPetsPetId`) | The rule of every Skmtc operation generator |
| The raw value in the path | Each value goes through `rawurlencode`, in the transport | A value can hold a `/` |
| `array<int, Item>` | `list<Item>`, read with `array_values(array_map(…))` | The current form of PHPStan and Psalm for a JSON array |
| Classes for status 429 and 5xx | One `ApiException` with the status, the body and the response | Enough for a default. The reference also throws nothing for a 4xx body with no `error` key. Generated code throws for each status that is not 2xx |
| `ArrayAccess`, meta information and fakes on a model | None | A DTO is a plain class |
| A contract interface for each resource | None | It serves the test fake only |

### Not for a default generator

The default generators leave these out:

- streams, and the test fake layer;
- meta information from response headers, and a fluent factory;
- webhook signature checks, and multipart uploads;
- special exception classes for a status;
- pagination helpers, retries and telemetry.

A project that needs one of them changes the hand-written transport, or
clones the generator.

### Rules from the language, not from the reference

- **The four kinds of property.**
  - In `required`: `$attributes['k']`, type `T`.
  - In `required` and nullable: `$attributes['k']`, type `?T`. The key is
    always there.
  - Optional: `$attributes['k'] ?? null`, type `?T`, and `= null` in the
    constructor.
  - A class or an enum that can be absent or `null`:
    `isset($attributes['k']) ? X::from($attributes['k']) : null`.
- **An empty object.** `json_encode([])` gives `[]`, not `{}`. So
  `jsonSerialize` of a class gives `(object) […]`, and a property that is
  a map is `(object) $this->labels`. An empty map inside an array or
  inside another map is still `[]`.
- **The other keys of an object.** An object with properties and
  `additionalProperties` has one more property,
  `array $additionalProperties = []`. `from()` reads it with
  `array_diff_key`, and `jsonSerialize` adds it with `array_replace`. A
  spread (`...`) gives a new number to a key that is a number. Thus
  `jsonSerialize` also adds the properties that can be absent with
  `array_replace`, and never with a spread.
- **Unknown enum values.** `Enum::from()` throws `\ValueError`, which is
  an `\Error` and not an exception.
- **Query values.** `http_build_query` writes `true` as `1` and a list
  as `k[0]=a`. The transport writes `true`, the value of an enum, and
  `k=a&k=b`. It tells a list from a map with `array_is_list`: a map is
  one pair for each key.
- **Reserved words.** A class name cannot be `List`, `Array` or
  `Default`. `PhpName.toClassName()` changes those names. A method and a
  case of an enum can have such a name, but a case cannot be `class`.

Attribution

Is this your skill, or is something wrong with this listing? Request removal or report an issue. Author removals are honored within 72 hours.

View all in development →

Comments

Loading comments…

Newsletter

Get the weekly list of safe new skills, and the ones we pulled.