PHP code example of myoperator / transport

1. Go to this page and download the library: Download myoperator/transport 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/ */

    

myoperator / transport example snippets




use MyOperator\Transport\Transport;

$transport = new Transport('http://localhost/api');

// Making a simple GET request
$response = $transport->get('/users?a=b&c=d');

// More better GET request
$response = $transport->get('/users', ['a' => 'b', 'c' => 'd']); 
// Equivalent to curl -XGET -H 'application/json' http://localhost/api/users?a=b&c=d

// To make a POST
$response = $transport->post('/users', ['a' => 'b']); 
// Equivalent to curl -XPOST -d a=b -H 'application/json' http://localhost/api/users

// Response can be directly cast to string
echo (string) $response; // {"a" : "b"}

//Or json if you like
print_r($response->json()); // ['a' => 'b']

// Or plaintext, same like casting
echo $response->text(); //{"a": "b"}


//Assuming webservice `/getjson` returns {'a': 'b'}
// and '/gettext' returns 'Simple text response'

$response = $transport->get('/getjson');
// assertTrue $response->json() == ['a' => 'b']
// assertTrue $response->text() == '{"a": "b"}'

$response = $transport->get('/gettext');
// assertTrue $response->json() == 'Simple text response'
// assertTrue $response->text() == 'Simple text response'
// assertTrue (string) $response == 'Simple text response'

use MyOperator\Transport\Transport;

$transport = new Transport('http://localhost');

$transport->setHeaders(['X-Auth-key' => 'xyz']);

$transport->post('/login');

use MyOperator\Transport\TransportMock;

// Inititalising a mocker
$transport = new TransportMock();

//Creating custom response. order is createResponse($body, $headers= [], $status_code=200);
$mockResponse = $transport->createResponse(json_encode(['a' => 'b']));

// Creating another GuzzleHttp\Psr7\Response responses
$anotherResponse = new GuzzleHttp\Psr7\Response(201, [], json_encode(['c' => 'd']));

// Queue a valid GuzzleHttp\Psr7\Response
$transport->queue($mockResponse);
$transport->queue($anotherResponse);

// Finally we can start mock
$transport->mock();

// This will return first queued response, doesn't matter whatever the request is
$response = $transport->get('/get');
//assertTrue $response->json() == ['a' => 'b']
//assertTrue $response->getStatus() == 200

$response = $transport->post('/somethingelse');
//assertTrue $response->json() == ['c' => 'd']
//assertTrue $response->getStatus() == 201

// Since at this point we have exhaused our queued response,
// this will throw an \OutOfBoundsException
$response = $transport->get('/status');