Skip to content

Commit

Permalink
Merge pull request #202 from Skullbock/feature/laravel-http-client-ad…
Browse files Browse the repository at this point in the history
…apter

Http client adapter
  • Loading branch information
sandervanhooft authored Oct 18, 2022
2 parents f582cc2 + d723389 commit cf8ed66
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 1 deletion.
51 changes: 51 additions & 0 deletions src/MollieLaravelHttpClientAdapter.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
<?php

namespace Mollie\Laravel;

use Illuminate\Http\Client\Response;
use Illuminate\Support\Facades\Http;
use Mollie\Api\Exceptions\ApiException;
use Mollie\Api\HttpAdapter\MollieHttpAdapterInterface;

class MollieLaravelHttpClientAdapter implements MollieHttpAdapterInterface
{
private const HTTP_NO_CONTENT = 204;

public function send($httpMethod, $url, $headers, $httpBody): object
{
$response = Http::withHeaders($headers)
->withBody($httpBody, 'application/json')
->send($httpMethod, $url);

return $this->parseResponseBody($response);
}

private function parseResponseBody(Response $response)
{
$body = $response->body();
if (empty($body)) {
if ($response->status() === self::HTTP_NO_CONTENT) {
return null;
}

throw new ApiException("No response body found.");
}

$object = @json_decode($body);

if (json_last_error() !== JSON_ERROR_NONE) {
throw new ApiException("Unable to decode Mollie response: '{$body}'.");
}

if ($response->status() >= 400) {
throw ApiException::createFromResponse($response->toPsrResponse(), null);
}

return $object;
}

public function versionString(): string
{
return 'Laravel/HttpClient';
}
}
2 changes: 1 addition & 1 deletion src/MollieServiceProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -131,7 +131,7 @@ protected function registerApiAdapter()
protected function registerApiClient()
{
$this->app->singleton('mollie.api.client', function () {
return (new MollieApiClient())->addVersionString('MollieLaravel/'.self::PACKAGE_VERSION);
return (new MollieApiClient(new MollieLaravelHttpClientAdapter()))->addVersionString('MollieLaravel/'.self::PACKAGE_VERSION);
});

$this->app->alias('mollie.api.client', MollieApiClient::class);
Expand Down

0 comments on commit cf8ed66

Please sign in to comment.