highsidelabs / saloon-sdk-generator
Saloon的简化SDK脚手架
Requires
- php: ^8.2
- ext-zip: *
- cebe/php-openapi: ^1.7
- laravel-zero/phar-updater: ^1.3
- nette/php-generator: ^4.0
- nunomaduro/termwind: ^2.0.1
- saloonphp/laravel-plugin: ^3.0
- saloonphp/saloon: ^3.0
Requires (Dev)
- laravel-zero/framework: ^11.0.1
- laravel/pint: ^1.8
- mockery/mockery: ^1.5.1
- pestphp/pest: ^2.5
This package is auto-updated.
Last update: 2024-09-08 20:30:58 UTC
README
待办事项
- 将响应模式移动到OpenApi响应部分,然后从那里解析它们
- 请求模式也做同样的处理吗?
- 从解析器中移除OpenApiReference检查?
Saloon SDK Generator - 简化的SDK脚手架 🚀
介绍Saloon SDK Generator – 使用强大的Saloon包快速创建PHP SDK基本结构的工具。
请注意:此工具帮助您搭建SDK的基础,但可能不会创建一个完整、可直接使用的解决方案。 🛠️
无论您是使用Postman Collection JSON文件(v2.1)还是OpenAPI规范,Saloon SDK Generator都能简化生成PHP SDK的过程。它为您构建API交互的初始框架提供起点。
请记住,生成的代码可能不适用于所有情况。将其视为快速构建SDK结构的快速方法。虽然您可能需要针对特定情况对其进行自定义,但Saloon SDK Generator通过消除从头创建样板代码的需要来节省您的时间。
您的定制SDK之旅从这里开始 – 使用Saloon SDK Generator。 🌟
安装
您可以使用Composer安装此包
composer global require crescat-io/saloon-sdk-generator
用法
要从API规范文件生成PHP SDK,请运行以下命令
sdkgenerator generate:sdk API_SPEC_FILE.{json|yaml|yml} --type={postman|openapi} [--name=SDK_NAME] [--output=OUTPUT_PATH] [--namespace=Company\\Integration] [--force] [--dry] [--zip]
用适当的值替换占位符
API_SPEC_FILE
:API规范文件的路径(JSON或YAML格式)。--type
:指定API规范类型(postman
或openapi
)。--name
:(可选)指定生成的SDK名称(默认:Unnamed)。--namespace
:(可选)指定SDK的根命名空间(默认:App\\Sdk
)。--output
:(可选)指定生成代码的输出路径(默认:./Generated)。--force
:(可选)强制覆盖现有文件。--dry
:(可选)执行干运行。它不会保存生成的文件,只会显示它们。--zip
:(可选)使用此标志生成包含所有生成文件的zip存档。
注意:由于PHP使用反斜杠\
,在指定--namespace
时,您需要像这样转义任何反斜杠
sdkgenerator generate:sdk ./tests/Samples/paddle.json --force --type=postman --name=Paddle --output ./paddle-sdk/src --namespace=Your\\Sdk\\Namespace # <-- Note the "\\"
通过编程方式使用代码生成器和解析器
- 配置您的生成器
使用所需设置配置CodeGenerator
$generator = new CodeGenerator( namespace: "App\Sdk", baseFilesNamespace: "App\Sdk\Base", namespaceSuffixes: [ 'resource' => 'Resource', 'request' => 'Request', 'dto' => 'Dto', ], connectorName: 'MySDK', // Replace with your desired SDK name outputFolder: './Generated', // Replace with your desired output folder ignoredParams: [ 'query' => ['after', 'order_by', 'per_page'], 'body' => [], 'header' => [], ], );
- 解析和生成
解析您的API规范文件并生成SDK类
$inputPath = 'path/to/api_spec_file.json'; // Replace with your API specification file path $type = 'postman'; // Replace with your API specification type $result = $generator->run(Factory::parse($type, $inputPath));
- 使用生成结果
您可以访问生成的类并对它们执行操作
// Generated Connector Class echo "Generated Connector Class: " . Utils::formatNamespaceAndClass($result->connectorClass) . "\n"; // Generated Base Resource Class echo "Generated Base Resource Class: " . Utils::formatNamespaceAndClass($result->resourceBaseClass) . "\n"; // Generated Resource Classes foreach ($result->resourceClasses as $resourceClass) { echo "Generated Resource Class: " . Utils::formatNamespaceAndClass($resourceClass) . "\n"; } // Generated Request Classes foreach ($result->requestClasses as $requestClass) { echo "Generated Request Class: " . Utils::formatNamespaceAndClass($requestClass) . "\n"; }
工作原理
Saloon SDK Generator通过以下步骤自动化创建PHP SDK
1. 解析API规范
解析器读取并理解不同的API规范格式,包括Postman Collection JSON(v2.1)、OpenAPI规范和自定义格式。执行时
- 读取输入文件。
- 将内容转换为名为
ApiSpecification
的内部格式。 - 此格式提供了对API的全面视图,SDK生成器使用它。
2. 自动生成SDK组件
此组件根据解析的规范自动生成必要的SDK组件
- 请求类
- 资源类
- 数据传输对象(DTOs)
- 连接器
- 基础资源类
3. 可配置的生成器
Saloon SDK 生成器是模块化的,允许您用自定义生成器替换默认生成器,以便根据您的需求定制 SDK 生成过程。以下生成器可以进行自定义:
BaseResourceGenerator
BaseRequestGenerator
BaseResponseGenerator
BaseDtoGenerator
ConnectorGenerator
DtoGenerator
RequestGenerator
ResourceGenerator
SupportingFilesGenerator
核心数据结构
这些基础结构构成了生成的 SDK 输出的基础。
1. ApiSpecification
- 表示整个 API 规范。
- 包含名称、描述、基本 URL 和端点目录等元数据。
2. Config
- SDK 生成器配置的中央存储库。
- 定义命名空间、组件后缀和其他参数。
- 可根据特定要求进行自定义。
3. Endpoint
- 描述单个 API 端点。
- 包括方法类型、路径段和相关参数。
4. GeneratedCode
- 捕获完整的生成 SDK 代码。
- 包括请求类、资源类、DTO、连接器和基础资源类的 PHP 文件。
5. Parameter
- 描述与 API 端点关联的参数。
- 包括类型、名称和可空性等属性。
构建自定义解析器
如果您正在使用 Saloon SDK 生成器原生不支持的自定义 API 规范格式,您可以构建一个自定义解析器来集成它。以下是您可以这样做的步骤:
- 创建您的自定义解析器
首先创建一个自定义解析器类,该类实现了 Crescat\SaloonSdkGenerator\Contracts\Parser
接口。
初始化解析器有两种方式。第一种是通过构造函数,它将在运行 sdkgenerator generate:sdk {FILE_PATH}
时接收指定的 filePath。
示例
<?php namespace YourNamespace\CustomParser; use Crescat\SaloonSdkGenerator\Contracts\Parser; use Crescat\SaloonSdkGenerator\Data\Generator\Endpoint; use Crescat\SaloonSdkGenerator\Data\Generator\ApiSpecification; use Crescat\SaloonSdkGenerator\Data\Generator\Parameter; class CustomParser implements Parser { public function __construct(protected $filePath) {} public function parse(): ApiSpecification { // TODO: Implement parseTheContents($this->filepath) // Implement a parser that will return an ApiSpecification object: return new ApiSpecification( name: 'Custom API', description: 'A custom API specification', baseUrl: 'https://api.example.com', endpoints: [ new Endpoint( name: 'GetUserInfo', method: 'GET', pathSegments: ['users', '{user_id}'], description: 'Get user information by ID', queryParameters: [ new Parameter('string', false, 'user_id', 'User ID'), ], ), new Endpoint( name: 'CreateUser', method: 'POST', pathSegments: ['users'], description: 'Create a new user', bodyParameters: [ new Parameter('string', false, 'username', 'Username'), new Parameter('string', false, 'email', 'Email'), ], ) ], ); } }
或者,如果您需要预处理文件,无论是通过网络还是运行不适合构造函数的第三方代码,您可以添加一个 build
方法,该方法将被调用。
OpenApiParser 中的示例
public static function build($content): static { // Call file readers depending on the filetype provided (supports JSON and YAML) return new static( Str::endsWith($content, '.json') ? Reader::readFromJsonFile(fileName: realpath($content), resolveReferences: ReferenceContext::RESOLVE_MODE_ALL) : Reader::readFromYamlFile(fileName: realpath($content), resolveReferences: ReferenceContext::RESOLVE_MODE_ALL) ); }
- 注册您的自定义解析器
为了使您的自定义解析器在 SDK 生成器中可用,您需要使用 Factory
类的 registerParser
方法进行注册。
use Crescat\SaloonSdkGenerator\Factory; use YourNamespace\CustomParser; // Replace with the actual namespace of your custom parser // Register your custom parser Factory::registerParser('custom', CustomParser::class);
- 使用您的自定义解析器
一旦注册,您就可以像使用任何其他内置解析器一样使用您的自定义解析器。在生成 SDK 时,将 'custom'
作为 --type
选项指定,SDK 生成器将使用您的自定义解析器处理 API 规范。
sdkgenerator generate:sdk API_SPEC_FILE.xxx --type=custom
将 API_SPEC_FILE.xxx
替换为您自定义 API 规范文件的路径。
现在,您的自定义解析器已无缝集成到 Saloon SDK 生成器中,允许您从自定义格式的 API 规范生成 SDK。
替换默认代码生成器
Saloon SDK 生成器旨在具有灵活性。如果您需要定制 SDK 的任何组件的生成过程,您可以轻松地用您自己的自定义实现替换任何默认生成器。
实现自定义生成器
要创建一个自定义生成器
-
创建一个新类,该类实现了
Crescat\SaloonSdkGenerator\Contracts\Generator
接口。此接口需要两个方法
- 一个接受
Config
对象的构造函数。 - 一个返回单个
PhpFile
或PhpFile
对象数组的generate
方法。
- 一个接受
示例
namespace YourNamespace; use Crescat\SaloonSdkGenerator\Contracts\Generator; use Crescat\SaloonSdkGenerator\Data\Generator\ApiSpecification; use Crescat\SaloonSdkGenerator\Data\Generator\Config; use Nette\PhpGenerator\PhpFile; class CustomRequestGenerator implements Generator { public function __construct(Config $config) { // Initialize your generator with the configuration } public function generate(ApiSpecification $specification): PhpFile|array { // Your custom generation logic here } }
使用您的自定义生成器
一旦您创建了您的自定义生成器,您可以通过在创建 CodeGenerator
时传递其实例来使用它。
$customRequestGenerator = new CustomRequestGenerator($config); $codeGenerator = new CodeGenerator( config: $config, requestGenerator: $customRequestGenerator // ... you can pass other custom generators as needed ); $result = $codeGenerator->run($specification);
通过将自定义生成器作为参数传递给 CodeGenerator
,它将替换默认生成器。这允许对 SDK 生成过程进行广泛的自定义,以满足您的特定需求。
使用真实API规范样本进行测试
为了展示Saloon SDK生成器的功能,并确保其与真实世界API规范的兼容性,我们已使用以下API规范进行了测试。
- Paddle (未公开)
- Stripe ( Postman)
- Tableau ( Postman)
- OpenAI (Postman)
- Fiken (OpenApi)
- GoCardless (OpenApi)
- Tripletex (OpenApi)
生成SDK
要从提供的API规范生成SDK,您可以运行以下composer脚本
composer generate:paddle composer generate:stripe composer generate:tableau composer generate:openai composer generate:fiken composer generate:gocardless composer generate:tripletex
生成Zip存档
如果您愿意(部分原因是为了展示它能够做到这一点),您还可以生成SDK的zip存档
composer generate:zip:paddle composer generate:zip:stripe composer generate:zip:tableau composer generate:zip:openai composer generate:zip:fiken composer generate:zip:gocardless composer generate:zip:tripletex
请随意使用这些命令来了解Saloon SDK生成器如何将API规范转换为PHP SDK。虽然这些测试提供了宝贵的见解,但请注意,兼容性可能因您特定API规范复杂性而异。
报告不兼容性
我们理解,当使用Saloon SDK生成器与各种API规范时,可能会出现兼容性问题。虽然我们欢迎关于这些不兼容性的报告,但重要的是要指出,此工具最初是为我们内部使用而开发的,并已开源以与社区分享。
如果在从您的API规范生成SDK时遇到问题或不兼容性,我们鼓励您在我们的GitHub问题跟踪器上报告。您的反馈很有价值,可以帮助我们随着时间的推移改进该工具。
然而,请理解,由于项目的性质和我们的优先事项,我们可能无法立即实施报告的问题的修复。
我们感谢您理解并感谢您使用Saloon SDK生成器。您的贡献、反馈和报告将有助于促进该工具的持续开发和改进,以造福更广泛的社区。
链接和参考
构建二进制文件
要为Packagist上的分发构建二进制文件,请运行以下命令
php ./builds/sdkgenerator app:build sdkgenerator --build-version=1.0
或使用composer脚本
composer build
TODOs
- 创建配置(sdkgenerator --config=sdkgenerator.php/json)文件,允许您覆盖行为,如
- 可配置的冲突解决程序
- (覆盖(与--force相同),
- 新(解析代码并仅添加“新”代码,即新参数、新方法),
- 为每个冲突提示用户(如git在交互模式下)
- 等等...
- 当无法解析POST请求的正文时,应警告用户并在生成的代码中添加TODO。
- 支持旧版swagger API规范
- 使用请求模拟生成所有端点的测试(查看)
- 通过连接器在资源构造函数中注入“路径”变量以实现干净的链式调用
- 示例:
$sdk->resource(userId: 1)->deleteUser();
- 示例:
贡献
欢迎为这个包做出贡献!如果你发现任何问题或想提出改进建议,请在问题追踪器提交拉取请求或打开一个问题。
鸣谢
这个包建立在巨人的肩膀上,特别感谢以下人员为他们开源工作所做的贡献,帮助我们所有人构建更好的软件!❤️
由 Crescat 构建
Crescat.io 是一款为场馆、音乐节和活动专业人士设计的协作软件。
凭借全面的特性,如日结算单、清单、报告和团队成员预订,Crescat 简化了活动管理。现场活动行业的专业人士信任 Crescat 来简化他们的工作流程,减少对多个工具和过时电子表格的需求。
故障排除
修复 未找到命令
错误
你很可能没有在 $PATH
中有 composer 的 vendor/bin
文件夹
# Default config file paths # Zsh: ~/.zshrc # Bash: ~/.bashrc or ~/.bash_profile # Fish: ~/.config/fish/config.fish # Replace 'YOUR_USERNAME' with your actual username # Example: '/Users/john/.composer/vendor/bin' # Zsh echo 'export PATH="/Users/YOUR_USERNAME/.composer/vendor/bin:$PATH"' >> ~/.zshrc source ~/.zshrc # Bash echo 'export PATH="/Users/YOUR_USERNAME/.composer/vendor/bin:$PATH"' >> ~/.bashrc source ~/.bashrc # Fish echo 'set -gx PATH "/Users/YOUR_USERNAME/.composer/vendor/bin" $PATH' >> ~/.config/fish/config.fish source ~/.config/fish/config.fish
许可证
MIT 许可证(MIT)。有关更多信息,请参阅许可证文件。