8000 [HttpFoundation] Update `all` method to handle default value by Korbeil · Pull Request #38891 · symfony/symfony · GitHub
[go: up one dir, main page]

Skip to content

[HttpFoundation] Update all method to handle default value #38891

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Update all method to handle default values
  • Loading branch information
Korbeil committed Nov 2, 2020
commit e1fa45800d5f9aa6fb12c55c09679d62153628c3
9 changes: 7 additions & 2 deletions src/Symfony/Component/HttpFoundation/ParameterBag.php
Original file line number Diff line number Diff line change
Expand Up @@ -37,15 +37,20 @@ public function __construct(array $parameters = [])
*
* @return array An array of parameters
*/
public function all(/*string $key = null*/)
public function all(/*string $key = null, array $default = []*/)
{
$key = \func_num_args() > 0 ? func_get_arg(0) : null;

if (null === $key) {
return $this->parameters;
}

if (!\is_array($value = $this->parameters[$key] ?? [])) {
$default = \func_num_args() > 1 ? func_get_arg(1) : [];
if (!\is_array($default)) {
throw new \TypeError(sprintf('Unexpected value for default value: expecting "array", got "%s".', get_debug_type($default)));
}

if (!\is_array($value = $this->parameters[$key] ?? $default)) {
throw new BadRequestException(sprintf('Unexpected value for parameter "%s": expecting "array", got "%s".', $key, get_debug_type($value)));
}

Expand Down
15 changes: 15 additions & 0 deletions src/Symfony/Component/HttpFoundation/Tests/ParameterBagTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,21 @@ public function testAllThrowsForNonArrayValues()
$bag->all('foo');
}

public function testAllWithDefaultKey()
{
$bag = new ParameterBag(['foo' => ['bar', 'baz'], 'null' => null]);

$this->assertEquals(['bar', 'baz'], $bag->all('foo', ['qux']), '->all() gets the value of a parameter');
$this->assertEquals(['qux'], $bag->all('unknown', ['qux']), '->all() returns an given default array if a parameter is not defined');
}

public function testAllThrowsForNonArrayDefaults()
{
$this->expectException(\TypeError::class);
$bag = new ParameterBag(['foo' => 'bar', 'null' => null]);
$bag->all('foo', 12345);
}

public function testKeys()
{
$bag = new ParameterBag(['foo' => 'bar']);
Expand Down
0