[BrowserKit] Add jsonRequest function to the browser-kit client

This commit is contained in:
Alexander Schranz 2020-10-16 11:59:17 +02:00 committed by Robin Chalas
parent abbb3d0546
commit c2fa2cb376
3 changed files with 34 additions and 0 deletions

View File

@ -161,6 +161,24 @@ abstract class AbstractBrowser
} }
} }
/**
* Converts the request parameters into a JSON string and uses it as request content.
*/
public function jsonRequest(string $method, string $uri, array $parameters = [], array $server = [], bool $changeHistory = true): Crawler
{
$content = json_encode($parameters);
$this->setServerParameter('CONTENT_TYPE', 'application/json');
$this->setServerParameter('HTTP_ACCEPT', 'application/json');
try {
return $this->request($method, $uri, [], [], $server, $content, $changeHistory);
} finally {
unset($this->server['CONTENT_TYPE']);
unset($this->server['HTTP_ACCEPT']);
}
}
/** /**
* Returns the History instance. * Returns the History instance.
* *

View File

@ -1,6 +1,11 @@
CHANGELOG CHANGELOG
========= =========
5.3.0
-----
* Added `jsonRequest` method to `AbstractBrowser`
4.3.0 4.3.0
----- -----

View File

@ -60,6 +60,17 @@ class AbstractBrowserTest extends TestCase
$this->assertFalse($client->getServerParameter('HTTP_X_REQUESTED_WITH', false)); $this->assertFalse($client->getServerParameter('HTTP_X_REQUESTED_WITH', false));
} }
public function testJsonRequest()
{
$client = $this->getBrowser();
$client->jsonRequest('GET', 'http://example.com/', ['param' => 1], [], true);
$this->assertSame('application/json', $client->getRequest()->getServer()['CONTENT_TYPE']);
$this->assertSame('application/json', $client->getRequest()->getServer()['HTTP_ACCEPT']);
$this->assertFalse($client->getServerParameter('CONTENT_TYPE', false));
$this->assertFalse($client->getServerParameter('HTTP_ACCEPT', false));
$this->assertSame('{"param":1}', $client->getRequest()->getContent());
}
public function testGetRequestWithIpAsHttpHost() public function testGetRequestWithIpAsHttpHost()
{ {
$client = $this->getBrowser(); $client = $this->getBrowser();