PHPackages                             timatic/saloon-sdk-generator - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Utility &amp; Helpers](/categories/utility)
4. /
5. timatic/saloon-sdk-generator

ActiveProject[Utility &amp; Helpers](/categories/utility)

timatic/saloon-sdk-generator
============================

Simplified SDK Scaffolding for Saloon

0511PHP

Since Nov 17Pushed 2mo agoCompare

[ Source](https://github.com/Timatic/saloon-sdk-generator)[ Packagist](https://packagist.org/packages/timatic/saloon-sdk-generator)[ RSS](/packages/timatic-saloon-sdk-generator/feed)WikiDiscussions main Synced 1mo ago

READMEChangelogDependenciesVersions (8)Used By (1)

[![](.github/header.png)](.github/header.png)

Saloon SDK Generator - Simplified SDK Scaffolding 🚀
===================================================

[](#saloon-sdk-generator---simplified-sdk-scaffolding-)

[![Latest Version on Packagist](https://camo.githubusercontent.com/5b024ad2056cd6f371edd19daadcfe4a5af41c8ea41d21fcfc711c00a774375c/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f637265736361742d696f2f73616c6f6f6e2d73646b2d67656e657261746f722e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/crescat-io/saloon-sdk-generator)[![Total Downloads](https://camo.githubusercontent.com/c0291ebeb621330c3477572d9eba051d70612883760ed8a296ca73d59dc3953b/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f637265736361742d696f2f73616c6f6f6e2d73646b2d67656e657261746f722e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/crescat-io/saloon-sdk-generator)

Introducing the Saloon SDK Generator – your tool for quickly creating the basic structure of PHP SDKs using the powerful [Saloon](https://docs.saloon.dev/) package.

Please note: This tool helps you set up the foundation for your SDK, but it might not create a complete, ready-to-use solution. 🛠️

Whether you're using Postman Collection JSON files (v2.1) or OpenAPI specifications, the Saloon SDK Generator simplifies the process of generating PHP SDKs. It provides you with a starting point to build the initial framework for your API interactions.

Keep in mind that the generated code might not be perfect for every situation. Think of it as a speedy way to scaffold your SDK structure. While you might need to customize it for specific cases, the Saloon SDK Generator saves you time by eliminating the need to create boilerplate code from scratch.

Your journey to crafting a tailored SDK starts here – with the Saloon SDK Generator. 🌟

Fork Enhancements
-----------------

[](#fork-enhancements)

This is an enhanced fork of the original [Crescat Saloon SDK Generator](https://github.com/crescat-io/saloon-sdk-generator) with significant additional features focused on production-ready SDK generation, comprehensive testing, and advanced customization capabilities.

### Comprehensive Test Generation

[](#comprehensive-test-generation)

The fork automatically generates **Pest PHP tests** for all your API endpoints, providing a complete test suite out of the box:

- **Automatic test generation** for all request types (GET, POST, PUT, DELETE)
- **Specialized test patterns** for different endpoint types:
    - Collection endpoints (lists/searches)
    - Singular resource endpoints (get by ID)
    - Mutation endpoints (create/update)
    - Delete endpoints
- **Factory generation** for Spatie Laravel Data objects to create realistic test data
- **DTO assertions** with support for nested objects and complex structures
- **Mock response fixtures** for repeatable, isolated tests

**Example generated test:**

```
test('can create user', function () {
    $connector = new MySDKConnector();

    $mockClient = new MockClient([
        CreateUserRequest::class => MockResponse::make([
            'id' => 123,
            'name' => 'John Doe',
            'email' => 'john@example.com'
        ], 201),
    ]);

    $connector->withMockClient($mockClient);

    $request = new CreateUserRequest(
        name: 'John Doe',
        email: 'john@example.com'
    );

    $response = $connector->send($request);
    $dto = $response->dto();

    expect($dto)->toBeInstanceOf(UserDto::class)
        ->and($dto->id)->toBe(123)
        ->and($dto->name)->toBe('John Doe')
        ->and($dto->email)->toBe('john@example.com');
});
```

### Enhanced DTO Support

[](#enhanced-dto-support)

Rich Data Transfer Object generation with modern PHP features:

- **Spatie Laravel Data integration** - Generated DTOs extend `Spatie\LaravelData\Data` for automatic validation, transformation, and serialization
- **Nested DTO support** - Automatically handles complex object hierarchies with recursive generation
- **Response hydration methods** - Each request includes a `createDtoFromResponse()` method for easy response parsing
- **Union type support** - Handles OpenAPI `anyOf`, `oneOf`, and `allOf` schemas
- **DateTime detection** - Automatically generates `Carbon` types for OpenAPI `date-time` format fields

**Example generated DTO:**

```
class UserDto extends Data
{
    public function __construct(
        public int $id,
        public string $name,
        public ?Carbon $created_at,
        public AddressDto $address,
    ) {}
}
```

**Response hydration:**

```
public function createDtoFromResponse(Response $response): UserDto
{
    return UserDto::from($response->json());
}
```

### Extensive Customization Hooks

[](#extensive-customization-hooks)

The fork provides a powerful hook system allowing you to customize every aspect of code generation:

- Request Generator Hooks
- Resource Generator Hooks
- DTO Generator Hooks
- Test Generator Hooks

**Example: Customizing request class names**

```
class MyRequestGenerator extends RequestGenerator
{
    protected function getRequestClassName(Endpoint $endpoint): string
    {
        // Remove version prefixes from endpoint names
        $name = preg_replace('/^v\d+/', '', $endpoint->name);
        return $name . 'Request';
    }
}

$generator = new CodeGenerator(
    config: $config,
    requestGenerator: new MyRequestGenerator($config)
);
```

### Configuration Enhancements

[](#configuration-enhancements)

Additional configuration options for fine-tuned control:

- **`requestClassSuffix`** - Customize the suffix for request classes (default: 'Request')
- **OpenAPI as default** - No need to specify `--type=openapi` when generating from OpenAPI specs
- **Test path customization** - Configure where test files are generated
- **Factory namespace configuration** - Control factory class namespaces

### Summary

[](#summary)

These enhancements make the SDK Generator suitable for production use with:

- Complete test coverage out of the box
- Type-safe DTOs with validation and transformation
- Full customization through hooks
- Modern PHP 8.2+ features
- Spatie Laravel Data integration

All features are backward-compatible with the original package and can be adopted incrementally.

Installation
------------

[](#installation)

> **Note:** This is an enhanced fork with additional features. See the [Fork Enhancements](#fork-enhancements) section above for details on what's been added beyond the original package.

You can install this package using Composer:

```
composer global require crescat-io/saloon-sdk-generator
```

Usage
-----

[](#usage)

### Generate SDK from OpenAPI or Postman Collection

[](#generate-sdk-from-openapi-or-postman-collection)

To generate the PHP SDK from an API specification file, run the following command:

```
sdkgenerator generate:sdk API_SPEC_FILE.{json|yaml|yml}
     --type={postman|openapi}
    [--name=SDK_NAME]
    [--output=OUTPUT_PATH]
    [--namespace=Company\\Integration]
    [--force]
    [--dry]
    [--zip]
```

Replace the placeholders with the appropriate values:

- `API_SPEC_FILE`: Path to the API specification file (JSON or YAML format).
- `--type`: Specify the type of API specification (`postman` or `openapi`).
- `--name`: (Optional) Specify the name of the generated SDK (default: Unnamed).
- `--namespace`: (Optional) Specify the root namespace for the SDK (default: `App\\Sdk`).
- `--output`: (Optional) Specify the output path where the generated code will be created (default: ./Generated).
- `--force`: (Optional) Force overwriting existing files.
- `--dry`: (Optional) Perform a dry run. It will not save generated files, only show a list of them.
- `--zip`: (Optional) Use this flag to generate a zip archive containing all the generated files.

**Note:** Due to PHP using Backslashes `\`, when specifying the `--namespace`, you need to escape any backslashes like so:

```
sdkgenerator generate:sdk ./tests/Samples/paddle.json
  --force
  --type=postman
  --name=Paddle
  --output ./paddle-sdk/src
  --namespace=Your\\Sdk\\Namespace #
