8000 Update all method to handle default values · symfony/symfony@e1fa458 · GitHub
[go: up one dir, main page]

Skip to content

Commit e1fa458

Browse files
committed
Update all method to handle default values
1 parent 9aac4f4 commit e1fa458

File tree

2 files changed

+22
-2
lines changed

2 files changed

+22
-2
lines changed

src/Symfony/Component/HttpFoundation/ParameterBag.php

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -37,15 +37,20 @@ public function __construct(array $parameters = [])
3737
*
3838
* @return array An array of parameters
3939
*/
40-
public function all(/*string $key = null*/)
40+
public function all(/*string $key = null, array $default = []*/)
4141
{
4242
$key = \func_num_args() > 0 ? func_get_arg(0) : null;
4343

4444
if (null === $key) {
4545
return $this->parameters;
4646
}
4747

48-
if (!\is_array($value = $this->parameters[$key] ?? [])) {
48+
$default = \func_num_args() > 1 ? func_get_arg(1) : [];
49+
if (!\is_array($default)) {
50+
throw new \TypeError(sprintf('Unexpected value for default value: expecting "array", got "%s".', get_debug_type($default)));
51+
}
52+
53+
if (!\is_array($value = $this->parameters[$key] ?? $default)) {
4954
throw new BadRequestException(sprintf('Unexpected value for parameter "%s": expecting "array", got "%s".', $key, get_debug_type($value)));
5055
}
5156

src/Symfony/Component/HttpFoundation/Tests/ParameterBagTest.php

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,21 @@ public function testAllThrowsForNonArrayValues()
4343
$bag->all('foo');
4444
}
4545

46+
public function testAllWithDefaultKey()
47+
{
48+
$bag = new ParameterBag(['foo' => ['bar', 'baz'], 'null' => null]);
49+
50+
$this->assertEquals(['bar', 'baz'], $bag->all('foo', ['qux']), '->all() gets the value of a parameter');
51+
$this->assertEquals(['qux'], $bag->all('unknown', ['qux']), '->all() returns an given default array if a parameter is not defined');
52+
}
53+
54+
public function testAllThrowsForNonArrayDefaults()
55+
{
56+
$this->expectException(\TypeError::class);
57+
$bag = new ParameterBag(['foo' => 'bar', 'null' => null]);
58+
$bag->all('foo', 12345);
59+
}
60+
4661
public function testKeys()
4762
{
4863
$bag = new ParameterBag(['foo' => 'bar']);

0 commit comments

Comments
 (0)
0