webclient/fake-http-client

Mock PSR-18 HTTP client

Fund package maintenance!
Other

v1.0.1 2020-11-04 12:26 UTC

This package is auto-updated.

Last update: 2021-09-04 14:16:28 UTC


README

Latest Stable Version Total Downloads License PHP

webclient/fake-http-client

Mock for PSR-18 HTTP client

Install

Add package to project

composer require --dev webclient/fake-http-client:^1.0

Set autoload

<?php

include 'vendor/autoload.php';

Using

<?php

use Webclient\Fake\Client;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Server\RequestHandlerInterface;

/** 
 * @var RequestHandlerInterface $handler your mock handler 
 * @var RequestInterface $request your tested request
 */
$client = new Client($handler);

$response = $client->sendRequest($request);

Routing

This package provides simple routing.

<?php

use Webclient\Fake\Client;
use Webclient\Fake\Handler\SimpleRoutingHandler;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Server\RequestHandlerInterface;

/** 
 * @var RequestHandlerInterface $notFoundHandler default handler, error 404
 * @var RequestHandlerInterface $entityCreatedHandler handler for 201 request (POST /entities) 
 * @var RequestHandlerInterface $entityHandler handler for 200 request (GET /entities/1)
 * @var RequestHandlerInterface $entityDeletedHandler handler for 204 request (DELETE /entities/2)
 * @var RequestInterface $errorRequest request for unused uri (GET /users)
 * @var RequestInterface $entityCreatingRequest request for creating entity (POST /entities)
 * @var RequestInterface $entityRequest request for getting entity (GET /entities/1)
 * @var RequestInterface $entityDeletingRequest request for deleting entity (DELETE /entities/2)
 */

$handler = new SimpleRoutingHandler($notFoundHandler);
$handler
    ->route(['GET', 'HEAD'], '/entities/1', $entityHandler)
    ->route(['POST'], '/entities', $entityCreatedHandler)
    ->route(['DELETED'], '/entities/2', $entityDeletedHandler)
;
$client = new Client($handler);

$response1 = $client->sendRequest($errorRequest); // returns error 404
$response2 = $client->sendRequest($entityCreatingRequest); // returns success response 201
$response3 = $client->sendRequest($entityRequest); // returns success response 200
$response4 = $client->sendRequest($entityDeletingRequest); // returns success response 204

Nuance

If you pass the \Psr\Http\Message\ServerRequestInterface object to client and want the handler to receive it as is, add the attribute \Webclient\Fake\Client::NO_REPLACE_ATTRIBUTE:

<?php

use Webclient\Fake\Client;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;

/** 
 * @var RequestHandlerInterface $handler your mock handler 
 * @var ServerRequestInterface $request your tested request
 */
$client = new Client($handler);

$response = $client->sendRequest($request->withAttribute(Client::NO_REPLACE_ATTRIBUTE, true));