Skip to content

Commit c4e97eb

Browse files
committed
feature symfony#52946 [HttpClient] Add HttpOptions->addHeader as a shortcut to add an header in an existing options object (Dean151)
This PR was squashed before being merged into the 7.1 branch. Discussion ---------- [HttpClient] Add HttpOptions->addHeader as a shortcut to add an header in an existing options object | Q | A | ------------- | --- | Branch? | 7.1 | Bug fix? | no | New feature? | yes | Deprecations? | no | Issues | | License | MIT Currently, the HttpOptions object only provide a ->setHeaders option that override every existing headers. When we are provided an HttpOptions to customize a request, adding a request header requires to get the whole headers array, update it, and then set it back in the HttpOptions object. This DX improvement brings an addHeader option, allowing to add an header to the set without having to manage the existing ones. When the header option is not yet provided, the ??= operator makes sure the headers is initialized with an empty array (PHP >= 7.4) When a header is already provided, it is overwritten. Commits ------- 266e50f [HttpClient] Add HttpOptions->addHeader as a shortcut to add an header in an existing options object
2 parents 48951a0 + 266e50f commit c4e97eb

File tree

2 files changed

+22
-0
lines changed

2 files changed

+22
-0
lines changed

src/Symfony/Component/HttpClient/HttpOptions.php

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,17 @@ public function setQuery(array $query): static
6363
return $this;
6464
}
6565

66+
/**
67+
* @return $this
68+
*/
69+
public function addHeader(string $key, string $value): static
70+
{
71+
$this->options['headers'] ??= [];
72+
$this->options['headers'][$key] = $value;
73+
74+
return $this;
75+
}
76+
6677
/**
6778
* @return $this
6879
*/

src/Symfony/Component/HttpClient/Tests/HttpOptionsTest.php

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,4 +39,15 @@ public function testSetAuthBearer()
3939
{
4040
$this->assertSame('foobar', (new HttpOptions())->setAuthBearer('foobar')->toArray()['auth_bearer']);
4141
}
42+
43+
public function testAddHeader()
44+
{
45+
$options = new HttpOptions();
46+
$options->addHeader('Accept', 'application/json');
47+
$this->assertSame(['Accept' => 'application/json'], $options->toArray()['headers']);
48+
$options->addHeader('Accept-Language', 'en-US,en;q=0.5');
49+
$this->assertSame(['Accept' => 'application/json', 'Accept-Language' => 'en-US,en;q=0.5'], $options->toArray()['headers']);
50+
$options->addHeader('Accept', 'application/html');
51+
$this->assertSame(['Accept' => 'application/html', 'Accept-Language' => 'en-US,en;q=0.5'], $options->toArray()['headers']);
52+
}
4253
}

0 commit comments

Comments
 (0)