PHP code example of webwhales / guzzle-conditional-mock-handler

1. Go to this page and download the library: Download webwhales/guzzle-conditional-mock-handler library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

webwhales / guzzle-conditional-mock-handler example snippets


use GuzzleHttp\Client;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Psr7\Response;
use WebWhales\GuzzleConditionalMockHandler\Handler as MockHandler;

$mockHandler = new MockHandler();

// Create a handler stack to mock the Guzzle Client with
$handler = HandlerStack::create($mockHandler);
$client  = new Client(['handler' => $handler]);

// Add mocked responses
$mockHandler->addResponse('https://example.com', new Response(200, [], 'This is a test'));


// Make a request to a matching URL
$response = $client->request('GET', 'https://example.com');

echo $response->getBody();
// Outputs "This is a test"


// Make a request to a non matching URL
$response = $client->request('GET', 'https://www.example.com');

echo $response->getBody();
// Outputs the actual content of https://www.example.com

// Add mocked responses
$mockHandler->addResponse('^http(s)?://example\.', new Response(200, [], 'This is a test'));


// Make a request to a matching URL
$response = $client->request('GET', 'https://example.com');

echo $response->getBody();
// Outputs "This is a test"


// Make a request to a non matching URL
$response = $client->request('GET', 'https://www.example.com');

echo $response->getBody();
// Outputs the actual content of https://www.example.com

$client      = null;
$mockHandler = MockHandler::initializeWithClient($client);