apie / schema-generator
apie库的Composer包:schema生成器
Requires
- php: >=8.1
- apie/core: dev-main
- apie/dateformat-to-regex: dev-main
- cebe/php-openapi: ^1.7
Requires (Dev)
- apie/common-value-objects: dev-main
- apie/date-value-objects: dev-main
- apie/fixtures: dev-main
- apie/text-value-objects: dev-main
- phpspec/prophecy-phpunit: ^2.0
- phpunit/phpunit: ^9.5
This package is auto-updated.
Last update: 2024-09-20 16:54:50 UTC
README
schema-generator
此包是Apie库的一部分。代码保存在一个monorepo中,因此需要向monorepo发送PR。
文档
schema生成器可以从具有类型提示的对象创建JSON Schema。它支持实体、列表、哈希表、DTO(为Apie创建)和价值对象。它返回使用cebe/php-openapi库创建的对象。
此库不会生成整个OpenAPI schema,而是仅创建所有对象的JSON schema部分。
标准用法
通常,您会为多个对象创建多个具有引用的schema。因此,我们基本上创建了一个Components部分
代码示例
<?php use Apie\Fixtures\Enums\Gender; use Apie\CommonValueObjects\Ranges\DateTimeRange; use Apie\SchemaGenerator\ComponentsBuilderFactory; $factory = ComponentsBuilderFactory::createComponentsBuilderFactory(); // $schema = ['type' => 'enum', 'enum' => ['M', 'V']] $schema = $factory->addCreationSchemaFor(Gender::class); /** * $schema = [ * 'type' => 'object', * 'properties' => [ * 'start' => ['$ref' => '#/components/schemas/DateWithTimezone-post'], * 'end' => ['$ref' => '#/components/schemas/DateWithTimezone-post'], * ] * ] */ $schema = $factory->addCreationSchemaFor(DateTimeRange::class); // $components = ['mixed', 'Gender-post', 'DateTimeRange-post', 'DateWithTimezone-post'] $components = array_keys($factory->getComponents()->schemas);
DTO
DTO将被映射为对象,并且所有字段都是必需的,除非它们具有Optional属性或默认值。
<?php use Apie\Core\Attributes\Optional; use Apie\Core\Dto\DtoInterface; class ExampleDto implements DtoInterface { string $example; int $number = 42; #[Optional()] Gender $gender; }
将生成以下schema
ExampleDto-post: required: ['example'] properties: example: type: string number: type: number gender: $ref: "Gender-post"
枚举
枚举将被映射为字符串或int类型,并包含枚举属性中的所有值。
后置枚举将使用枚举的值。没有值的枚举使用名称,并且始终映射为字符串。
实体
实体将通过读取构造函数参数以及所有以set或with开头的方法来映射。
任何构造函数参数都被视为必需选项,除非它具有默认值。
对于所有以set或with开头的方法,它期望最后一个参数是需要的数据类型。其他参数被视为上下文原因(如是否认证或当前区域设置)。
值对象
它试图找出对象中的值对象。例如,如果它使用标准特质之一,则将其映射为对象或字符串,或读取toNative()返回的类型提示。
- 如果它实现了HasRegexValueObjectInterface,则填充模式。
- 如果它实现了StringValueObjectInterface,则类型被填充为字符串,并且格式是类名(不包含命名空间)。
- 如果类使用了CompositeValueObject特质,则将其映射为对象。
完全自定义
您可以在类上添加SchemaMethod属性,并添加一个静态方法类以指定类的OpenAPI schema。
<?php use Apie\Core\ValueObjects\Interfaces\StringValueObjectInterface; use Apie\Core\ValueObjects\IsStringValueObject; #[SchemaMethod('getSchema')] class Example implements StringValueObject { use IsStringValueObject; public static function getSchema(): array { return [ 'type' => 'string', 'format' => 'password', 'max' => 12, ]; } }
此方法可以返回cebe\Openapi\Schema的实例(您需要cebe/php-openapi")或返回schema的数组。