Skip to content

Commit

Permalink
feature symfony#52946 [HttpClient] Add HttpOptions->addHeader as a sh…
Browse files Browse the repository at this point in the history
…ortcut 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
  • Loading branch information
fabpot committed Dec 8, 2023
2 parents 48951a0 + 266e50f commit c4e97eb
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 0 deletions.
11 changes: 11 additions & 0 deletions src/Symfony/Component/HttpClient/HttpOptions.php
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,17 @@ public function setQuery(array $query): static
return $this;
}

/**
* @return $this
*/
public function addHeader(string $key, string $value): static
{
$this->options['headers'] ??= [];
$this->options['headers'][$key] = $value;

return $this;
}

/**
* @return $this
*/
Expand Down
11 changes: 11 additions & 0 deletions src/Symfony/Component/HttpClient/Tests/HttpOptionsTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -39,4 +39,15 @@ public function testSetAuthBearer()
{
$this->assertSame('foobar', (new HttpOptions())->setAuthBearer('foobar')->toArray()['auth_bearer']);
}

public function testAddHeader()
{
$options = new HttpOptions();
$options->addHeader('Accept', 'application/json');
$this->assertSame(['Accept' => 'application/json'], $options->toArray()['headers']);
$options->addHeader('Accept-Language', 'en-US,en;q=0.5');
$this->assertSame(['Accept' => 'application/json', 'Accept-Language' => 'en-US,en;q=0.5'], $options->toArray()['headers']);
$options->addHeader('Accept', 'application/html');
$this->assertSame(['Accept' => 'application/html', 'Accept-Language' => 'en-US,en;q=0.5'], $options->toArray()['headers']);
}
}

0 comments on commit c4e97eb

Please sign in to comment.