To handle the JSON webhook body received from Stripe and ensure that PHPStan understands the structure of the data, you can create a DTO (Data Transfer Object) that represents the structure of the Stripe event. This DTO can then be used to type-hint the $stripe_event property in your PaymentWebhook class.
Here's how you can create a DTO and use it in your Laravel job:
- Create a DTO class that represents the structure of the Stripe event:
class StripeEventDTO
{
public string $id;
public string $object;
public string $api_version;
public int $created;
public array $data;
public bool $livemode;
public int $pending_webhooks;
public array $request;
public string $type;
// Add more properties as needed, based on the Stripe event structure
public function __construct(array $stripeEventData)
{
// Map the array data to the properties of this DTO
// You can use a library like spatie/data-transfer-object for automatic mapping
// or manually assign the values as shown below:
$this->id = $stripeEventData['id'];
$this->object = $stripeEventData['object'];
$this->api_version = $stripeEventData['api_version'];
$this->created = $stripeEventData['created'];
$this->data = $stripeEventData['data'];
$this->livemode = $stripeEventData['livemode'];
$this->pending_webhooks = $stripeEventData['pending_webhooks'];
$this->request = $stripeEventData['request'];
$this->type = $stripeEventData['type'];
}
}
- Update your
PaymentWebhookclass to use theStripeEventDTO:
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\Queueable;
class PaymentWebhook implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
protected StripeEventDTO $stripe_event;
public function __construct(StripeEventDTO $stripe_event)
{
$this->stripe_event = $stripe_event;
}
public function handle(): void
{
// Do something here with $this->stripe_event...
}
}
- When dispatching the job, convert the JSON payload to an array and instantiate the
StripeEventDTO:
$stripeEventData = json_decode($jsonPayload, true);
$stripeEventDTO = new StripeEventDTO($stripeEventData);
PaymentWebhook::dispatch($stripeEventDTO);
By using a DTO, you provide PHPStan with a clear structure of the expected data, which allows for better static analysis and type checking. Additionally, this approach makes your code more maintainable and easier to understand.