Skip to content

Commit

Permalink
ISSUE #32: Middlewares for v3.x (#39)
Browse files Browse the repository at this point in the history
Co-authored-by: Fabrizio Gargiulo <[email protected]>
  • Loading branch information
doppiogancio and Fabrizio Gargiulo authored Jun 20, 2023
1 parent ab72167 commit 27c00ce
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 46 deletions.
9 changes: 5 additions & 4 deletions src/MockedClient/HandlerBuilder.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,11 @@

use DoppioGancio\MockedClient\Exception\RouteNotFound;
use DoppioGancio\MockedClient\Route\Route;
use GuzzleHttp\Promise\FulfilledPromise;
use GuzzleHttp\Promise\PromiseInterface;
use League\Route\Http\Exception\NotFoundException;
use League\Route\Router;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestFactoryInterface;
use Psr\Log\LoggerInterface;
use Psr\Log\NullLogger;
Expand Down Expand Up @@ -39,11 +40,11 @@ public function addRoute(Route $route): self
}

/**
* @return callable(RequestInterface): ResponseInterface
* @return callable(RequestInterface): PromiseInterface
*/
public function build(): callable
{
return function (RequestInterface $request): ResponseInterface {
return function (RequestInterface $request): PromiseInterface {
$uri = $request->getUri()
->withScheme('')
->withHost('')
Expand Down Expand Up @@ -90,7 +91,7 @@ public function build(): callable
]
);

return $response;
return new FulfilledPromise($response);
} catch (NotFoundException $e) {
$this->logError($e, $request);

Expand Down
50 changes: 10 additions & 40 deletions src/MockedClient/MockedGuzzleClientBuilder.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,24 +5,15 @@
namespace DoppioGancio\MockedClient;

use GuzzleHttp\Client;
use GuzzleHttp\Exception\ClientException;
use GuzzleHttp\Exception\ServerException;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\MessageFormatter;
use GuzzleHttp\Middleware;
use GuzzleHttp\Promise\FulfilledPromise;
use GuzzleHttp\Promise\PromiseInterface;
use GuzzleHttp\Psr7\Response;
use Psr\Http\Message\RequestInterface;
use Psr\Log\LoggerInterface;
use Psr\Log\NullLogger;

use function assert;

class MockedGuzzleClientBuilder
{
private HandlerBuilder $handlerBuilder;
private LoggerInterface $logger;

/** @var array<callable> */
private array $middlewares = [];
Expand All @@ -32,7 +23,10 @@ public function __construct(
?LoggerInterface $logger = null
) {
$this->handlerBuilder = $handlerBuilder;
$this->logger = $logger ?? new NullLogger();
$this->addMiddleware(Middleware::log(
$logger ?? new NullLogger(),
new MessageFormatter()
));
}

public function addMiddleware(callable $middleware): self
Expand All @@ -42,43 +36,19 @@ public function addMiddleware(callable $middleware): self
return $this;
}

public function build(): Client
/** @param array<string,mixed> $options */
public function build(array $options = []): Client
{
$handler = $this->handlerBuilder->build();

$callback = static function (RequestInterface $request, $options) use ($handler): PromiseInterface {
$response = $handler($request);
assert($response instanceof Response);
if ($response->getStatusCode() >= 400 && $response->getStatusCode() < 500) {
throw new ClientException(
$response->getBody()->getContents(),
$request,
$response
);
}

if ($response->getStatusCode() >= 500 && $response->getStatusCode() < 600) {
throw new ServerException(
$response->getBody()->getContents(),
$request,
$response
);
}

return new FulfilledPromise($response);
};

$handlerStack = new HandlerStack($callback);

$handlerStack->push(Middleware::log(
$this->logger,
new MessageFormatter()
));
$handlerStack = HandlerStack::create($handler);

foreach ($this->middlewares as $middleware) {
$handlerStack->push($middleware);
}

return new Client(['handler' => $handlerStack]);
$options['handler'] = $handlerStack;

return new Client($options);
}
}
8 changes: 6 additions & 2 deletions tests/ClientBuilderTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -81,8 +81,12 @@ public function testRouteNotFound(): void

public function testClientWithFullUrl(): void
{
$response = $this->getMockedClient()->request('GET', 'http://user:password@localhost:8099/country/?page=1&code=it');
$body = (string) $response->getBody();
$response = $this->getMockedClient()->request(
'GET',
'http://user:password@localhost:8099/country/?page=1&code=it'
);

$body = (string) $response->getBody();
$this->assertEquals('{"id":"+39","code":"IT","name":"Italy"}', $body);
}

Expand Down

0 comments on commit 27c00ce

Please sign in to comment.