Initial commit

This commit is contained in:
Alex Wright 2020-08-19 17:27:24 +02:00
commit 97eff2e1f2
4 changed files with 113 additions and 0 deletions

3
README.md Normal file
View File

@ -0,0 +1,3 @@
# A PHP Client for MockServer
Connect to and control a [MockServer](https://www.mock-server.com/) instance to test your API clients and integrations.

22
composer.json Normal file
View File

@ -0,0 +1,22 @@
{
"name": "xeen/mock-server-client",
"description": "A MockServer client",
"type": "library",
"authors": [
{
"name": "Alex Wright",
"email": "alex@xeen.uk"
}
],
"require": {
"guzzlehttp/guzzle": "^7.0"
},
"require-dev": {
"phpunit/phpunit": "^9.3"
},
"autoload": {
"psr-4": {
"Xeen\\MockServerClient\\": "src/"
}
}
}

52
src/Client.php Normal file
View File

@ -0,0 +1,52 @@
<?php
namespace Xeen\MockServerClient;
use GuzzleHttp\Client as HttpClient;
use GuzzleHttp\Psr7\Response;
use GuzzleHttp\Psr7\Uri;
class Client
{
private HttpClient $client;
private Uri $uri;
private Uri $apiUri;
public function __construct($config = [])
{
if (isset($config['uri'])) {
$this->uri = Uri::fromParts(parse_url($config['uri']));
} else {
$this->uri = Uri::fromParts($config);
}
$this->apiUri = $this->uri->withPath('/mockserver/');
$this->client = new HttpClient([
'base_uri' => $this->apiUri,
'http_errors' => false,
]);
}
public function addExpectation($expectation)
{
$uri = 'expectation';
return json_decode(static::handleResponse($this->client->put($uri, ['json' => $expectation]))->getBody()->getContents());
}
/**
* Reset the mock server. Returns true on success.
*/
public function reset(): bool
{
$uri = 'reset';
return $this->client->put($uri)->getStatusCode() == 200;
}
private static function handleResponse(Response $response)
{
if ($response->getStatusCode() >= 400) {
var_dump($response->getBody()->getContents());
exit;
}
return $response;
}
}

View File

@ -0,0 +1,36 @@
<?php
namespace Xeen\MockServerClient\Traits;
use RuntimeException;
use \Xeen\MockServerClient\Client as MockServerClient;
trait MockServerTestCase {
protected MockServerClient $mockServerClient;
/**
* @before
*/
public function setupMockServerClient()
{
$this->mockServerClient = new MockServerClient($this->mockServerConfig());
}
protected function mockServerConfig()
{
if (isset(self::$config) && isset(self::$config['mockserver'])) {
return self::$config['mockserver'];
}
throw new RuntimeException("No config for mockserver");
}
protected function setMockServerExpectation($expectaion)
{
return $this->mockServerClient->addExpectation($expectaion);
}
protected function clearMockServerExpectaions()
{
$this->mockServerClient->reset();
}
}