saloonphp / saloon

🤠 Build beautiful API integrations and SDKs with Saloon
https://docs.saloon.dev
MIT License
2.04k stars 105 forks source link

Typing of responses with DTO's #358

Closed falko100 closed 7 months ago

falko100 commented 8 months ago

So I have a problem with typing / phpstan / intellij.

$connector = new \App\Http\Integrations\GenericWebshopSoftware();
$request = new \App\Http\Integrations\GenericWebshopSoftware\Requests\GetProductsRequest();
$response = $connector->send($request);
$dto = $response->dto();

The return type of $dto is mixed because $connector->send returns a generic Response instead of my \App\Http\Integrations\GenericWebshopSoftware\Responses\GetProductsResponse.

Is there any way to get this working in Saloon? We want to integrate Saloon into our default stack, but this would be a no-go due to our strict phpstan policy.

Cbrad24 commented 8 months ago

I'm not too familiar with PhpStan but this is how I get around the typing / IntelliJ aspect of it:

$connector = new cPanelConnector();
$response = $connector->send(new GetTenantsRequest);

/** @var \Illuminate\Support\Collection<int, \App\Http\Integrations\cPanel\DataObjects\Tenant> $tenants */
$tenants = $response
    ->dto()
    ->keyBy('id');

By injecting a @var DocBlock IntelliJ now knows what type of variable I am working with and can show the appropriate type hints.

image

image

Not sure if this will override PhpStan but the @var DocBlock has come in handy a few times for me to unwrap some of Laravel's and other packages magic.

Sammyjo20 commented 8 months ago

+1 on the above solution - I will take a look at generics and see if there's a way even with a template that I can allow people to define the types of DTOs being returned.

Sammyjo20 commented 7 months ago

Hey @falko100 @Cbrad24

I have updated the documentation to include a section on improving IntelliJ / Type detection for Saloon's DTOs. I have recommended two solutions - using the suggestion by @Cbrad24 but also using the createDtoFromResponse() which will have direct typed support which might be nicer.

https://docs.saloon.dev/digging-deeper/data-transfer-objects#phpstan-typehinting-dtos

Thanks again for the good discussion!