Enums
swagger-php supports both basic and backed enums out of the box.
Enum as OA\Schema
The simples way of using enums is to annotate them as OA\Schema. This allows you to reference them like any other schema in your spec.
Results in:
openapi: 3.1.0
components:
schemas:
Colour:
type: string
enum:
- GREEN
- BLUE
- RED
Product:
properties:
colour:
$ref: '#/components/schemas/Colour'
type: objectEnum as a type
In hybrid and spec mode, an enum without an OA\Schema still describes the property, parameter or request body it types. It becomes a schema named after the enum, as if it carried OA\Schema, and the type references it.
A backed enum's schema lists the backing values, since that is what the enum serializes to. A bare OA\Schema on the enum lists the case names instead, as below explains.
enum Language: string
{
case English = 'en';
case German = 'de';
}
#[OA\Schema]
class Book
{
#[OA\Property]
public Language $language;
}Results in:
openapi: 3.1.0
components:
schemas:
Book:
type: object
properties:
language:
$ref: '#/components/schemas/Language'
required:
- language
Language:
type: string
enum:
- en
- deClassic mode leaves the property untyped.
Enum cases
Enum cases can be used as value in an enum list just like a string, integer or any other primitive type.
Basic enum:
Results in:
openapi: 3.1.0
components:
schemas:
Model:
properties:
someSuits:
type: array
enum:
- Hearts
- Diamonds
type: objectBacked enums
If the enum is a backed enum, the case backing value is used instead of the name.
Backed enums
For backed enums there exist two rules that determine whether the name or backing value is used:
- If no schema type is given, the enum name is used.
- If a schema type is given, and it matches the backing type, the enum backing value is used.
Default behaviour for backed enums
By default, the name of a backed enum case is used.
Example:
Results in:
openapi: 3.1.0
components:
schemas:
Colour:
type: string
enum:
- GREEN
- BLUE
- RED
Product:
properties:
colour:
$ref: '#/components/schemas/Colour'
type: objectUsing the backing value of an enum
To force swagger-php to use the backing value of an enum, you need to set the schema type to match the enum backing type.
Using the backing value (integer:
Results in:
openapi: 3.1.0
components:
schemas:
Colour:
type: integer
enum:
- 1
- 2
- 3
Product:
properties:
colour:
$ref: '#/components/schemas/Colour'
type: object