[HttpClient] Do not allow setting both json and body

This commit is contained in:
Giso Stallenberg 2019-04-09 23:54:10 +02:00 committed by Fabien Potencier
parent 4d9f5ee823
commit 601adf5de7
3 changed files with 16 additions and 1 deletions

View File

@ -45,7 +45,11 @@ trait HttpClientTrait
$options = self::mergeDefaultOptions($options, $defaultOptions, $allowExtraOptions);
if (isset($options['json'])) {
if (isset($options['body']) && '' !== $options['body']) {
throw new InvalidArgumentException('Define either the "json" or the "body" option, setting both is not supported.');
}
$options['body'] = self::jsonEncode($options['json']);
unset($options['json']);
$options['headers']['content-type'] = $options['headers']['content-type'] ?? ['application/json'];
}

View File

@ -199,6 +199,15 @@ class HttpClientTraitTest extends TestCase
self::prepareRequest('POST', 'http://example.com', ['auth_bearer' => 'foo', 'auth_basic' => 'foo:bar'], HttpClientInterface::OPTIONS_DEFAULTS);
}
/**
* @expectedException \Symfony\Component\HttpClient\Exception\InvalidArgumentException
* @expectedExceptionMessage Define either the "json" or the "body" option, setting both is not supported
*/
public function testSetJSONAndBodyOptions()
{
self::prepareRequest('POST', 'http://example.com', ['json' => ['foo' => 'bar'], 'body' => '<html/>'], HttpClientInterface::OPTIONS_DEFAULTS);
}
public function providePrepareAuthBasic()
{
yield ['foo:bar', 'Zm9vOmJhcg=='];

View File

@ -73,7 +73,9 @@ class ScopingHttpClientTest extends TestCase
$response = $client->request('GET', 'http://example.com/foo-bar', ['json' => ['url' => 'http://example.com']]);
$requestOptions = $response->getRequestOptions();
$this->assertEquals($requestOptions['json']['url'], 'http://example.com');
$this->assertEquals($requestOptions['headers']['content-type'][0], 'application/json');
$requestJson = json_decode($requestOptions['body'], true);
$this->assertEquals($requestJson['url'], 'http://example.com');
$this->assertEquals($requestOptions['headers']['x-app'][0], $defaultOptions['.*/foo-bar']['headers']['x-app']);
$response = $client->request('GET', 'http://example.com/bar-foo', ['headers' => ['x-app' => 'unit-test']]);