Skip to content

Commit 6c87bb3

Browse files
committed
Merge pull request #1 from php-http/implementation
Add mock adapter implementation
2 parents db14937 + 7be0d14 commit 6c87bb3

File tree

2 files changed

+86
-5
lines changed

2 files changed

+86
-5
lines changed

composer.json

+9-5
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,8 @@
1212
],
1313
"require": {
1414
"php": ">=5.4",
15-
"php-http/adapter": "^0.1"
15+
"php-http/httplug": "^1.0@beta",
16+
"php-http/discovery": "^0.5"
1617
},
1718
"require-dev": {
1819
"phpspec/phpspec": "^2.2",
@@ -23,14 +24,17 @@
2324
},
2425
"autoload": {
2526
"psr-4": {
26-
"Http\\Adapter\\": "src/"
27+
"Http\\Adapter\\Mock\\": "src/"
28+
}
29+
},
30+
"autoload-dev": {
31+
"psr-4": {
32+
"Http\\Adapter\\Mock\\Tests\\": "tests/"
2733
}
2834
},
2935
"extra": {
3036
"branch-alias": {
3137
"dev-master": "0.1-dev"
3238
}
33-
},
34-
"prefer-stable": true,
35-
"minimum-stability": "dev"
39+
}
3640
}

src/Client.php

+77
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
<?php
2+
3+
namespace Http\Adapter\Mock;
4+
5+
use Http\Client\Common\HttpAsyncClientEmulator;
6+
use Http\Client\HttpAsyncClient;
7+
use Http\Client\HttpClient;
8+
use Http\Discovery\MessageFactoryDiscovery;
9+
use Psr\Http\Message\RequestInterface;
10+
use Psr\Http\Message\ResponseInterface;
11+
12+
/**
13+
* HTTP client mock
14+
*
15+
* This mock is most useful in tests. It does not send requests but stores them
16+
* for later retrieval. Additionally, you can set an exception to test
17+
* exception handling.
18+
*
19+
* @author David de Boer <[email protected]>
20+
*/
21+
class Client implements HttpClient, HttpAsyncClient
22+
{
23+
use HttpAsyncClientEmulator;
24+
25+
private $requests = [];
26+
private $responses = [];
27+
private $exceptions = [];
28+
29+
/**
30+
* {@inheritdoc}
31+
*/
32+
public function sendRequest(RequestInterface $request)
33+
{
34+
$this->requests[] = $request;
35+
36+
if (count($this->exceptions) > 0) {
37+
throw array_shift($this->exceptions);
38+
}
39+
40+
if (count($this->responses) > 0) {
41+
return array_shift($this->responses);
42+
}
43+
44+
// Return success response by default
45+
return MessageFactoryDiscovery::find()->createResponse();
46+
}
47+
48+
/**
49+
* Add exception that will be thrown
50+
*
51+
* @param \Exception $exception
52+
*/
53+
public function addException(\Exception $exception)
54+
{
55+
$this->exceptions[] = $exception;
56+
}
57+
58+
/**
59+
* Add response that will be returned
60+
*
61+
* @param ResponseInterface $response
62+
*/
63+
public function addResponse(ResponseInterface $response)
64+
{
65+
$this->responses[] = $response;
66+
}
67+
68+
/**
69+
* Get requests that were sent
70+
*
71+
* @return RequestInterface[]
72+
*/
73+
public function getRequests()
74+
{
75+
return $this->requests;
76+
}
77+
}

0 commit comments

Comments
 (0)