langsys/swagger-auto-generator

自动Swagger和DTO生成器文档生成器

v1.1.31 2024-09-15 03:31 UTC

This package is auto-updated.

Last update: 2024-09-30 02:54:17 UTC


README

该软件包处于测试阶段,README内容尚不完整。请勿使用。除非您想尝试解决它 :)

该软件包是Spatie的Laravel Data和Darkaonline的L5-Swagger的扩展。它允许您根据Laravel Data软件包生成API的Swagger文档和DTO。

安装

您可以通过composer安装该软件包

composer require langsys/data-swagger

用法

您可以使用以下命令发布配置文件

php artisan vendor:publish --provider="Langsys\SwaggerAutoGenerator\DataSwaggerServiceProvider" --tag="config"

您可以根据需要自定义配置文件。配置文件位于 config/langsys-generator.php

return [
    'paths' => [
        'data_objects' => app_path('DataObjects'),
        'swagger_docs' => app_path('Swagger/Schemas.php')
    ],
];

修改 paths 数组,以便将其指向生成DataObjects和Langsys Schemas的目录。

您可以通过运行以下命令生成Langsys Schemas

php artisan data-swagger:generate

这将根据配置文件生成Swagger Schemas。

要生成数据对象,您可以运行以下命令

php artisan data-swagger:dto --model="App\Models\User"

这将为用户模型生成一个数据对象。

<?php

declare(strict_types=1);

namespace App\DataObjects;

use Spatie\LaravelData\Data;

/** @typescript */
final class UserData extends Data
{
    public function __construct(
        public string $id,       
        public string $firstname,
        public string $lastname,
        public string $email,       
        public ?string $email_verified_at,
        public string $password,       
        public ?string $remember_token,        
        public ?string $created_at,
        public ?string $updated_at,      
    ) {
    }
}

扩展用法

如果您在Schema中具有自定义字段,这些字段在Laravel默认助手或Faker函数中不存在,您可以将自己的自定义函数添加到 config/langsys-generator.php 文件中。

    'faker_attribute_mapper' => [
        'address_1' => 'streetAddress',
        'address_2' => 'buildingNumber',
        'zip' => 'postcode',
        '_at' => 'date',
        '_url' => 'url',
        'locale' => 'locale',
        'phone' => 'phoneNumber',
        '_id' => 'id'
    ],

    //These are examples of custom functions that can be used in the data object, you can add more functions here, or remove them if you don't need them.
    'custom_functions' => [
        'id' => [\Langsys\SwaggerAutoGenerator\Functions\CustomFunctions::class,'id'],
        'locale' => [\Langsys\SwaggerAutoGenerator\Functions\CustomFunctions::class,'locale'],
        'date' => [\Langsys\SwaggerAutoGenerator\Functions\CustomFunctions::class,'date'],
    ],

在上面的示例中,我们添加了一个自定义函数 locale,该函数生成一个随机的区域字符串。以下是自定义函数的示例

<?php

namespace Langsys\SwaggerAutoGenerator\Functions;

use App\Models\Locale;

class CustomFunctions
{  
    public function locale(): string
    {
        $locales = Locale::all();

        return $locales->get(random_int(1, $locales->count()))->code;
    }
}

测试

composer test