bug #31044 [HttpClient] Do not allow setting both json and body (gisostallenberg)

This PR was squashed before being merged into the 4.3-dev branch (closes #31044).

Discussion
----------

[HttpClient] Do not allow setting both json and body

| Q             | A
| ------------- | ---
| Branch?       | master
| Bug fix?      | no
| New feature?  | yes
| BC breaks?    | no
| Deprecations? | no
| Tests pass?   | yes
| Fixed tickets | #30769
| License       | MIT
| Doc PR        | n/a

This will keep developers from using both the options `$options['body']` and `$options['json']`. Using both results in only json being the body of the request, which might lead to unexpected results.

Commits
-------

601adf5de7 [HttpClient] Do not allow setting both json and body
This commit is contained in:
Fabien Potencier 2019-04-10 17:10:52 +02:00
commit b2f8f0d3a2
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']]);