8000 Add getArray method to ParameterBag · symfony/symfony@6fc5b95 · GitHub
[go: up one dir, main page]

Skip to content

Commit 6fc5b95

Browse files
committed
Add getArray method to ParameterBag
1 parent 9aac4f4 commit 6fc5b95

File tree

2 files changed

+30
-0
lines changed

2 files changed

+30
-0
lines changed

src/Symfony/Component/HttpFoundation/ParameterBag.php

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -169,6 +169,21 @@ public function getBoolean(string $key, bool $default = false)
169169
return $this->filter($key, $default, \FILTER_VALIDATE_BOOLEAN);
170170
}
171171

172+
/**
173+
* Returns the parameter value converted to array.
174+
*
175+
* @return array The filtered value
176+
*/
177+
public function getArray(string $key, array $default = [])
178+
{
179+
$value = $this->parameters[$key] ?? $default;
180+
if (!is_array($value)) {
181+
throw new BadRequestException(sprintf('Unexpected value for parameter "%s": expecting "array", got "%s".', $key, get_debug_type($value)));
182+
}
183+
184+
return $value;
185+
}
186+
172187
/**
173188
* Filter key.
174189
*

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

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -141,6 +141,21 @@ public function testGetInt()
141141
$this->assertEquals(0, $bag->getInt('unknown'), '->getInt() returns zero if a parameter is not defined');
142142
}
143143

144+
public function testGetArray()
145+
{
146+
$bag = new ParameterBag(['array' => ['a', 'b', 'c']]);
147+
148+
$this->assertEquals(['a', 'b', 'c'], $bag->getArray('array'), '->getArray() gets a value of parameter as array');
149+
$this->assertEquals([], $bag->getArray('unknown'), '->getArray() returns empty array if a parameter is not defined');
150+
}
151+
152+
public function testArrayThrowsForNonArrayValues()
153+
{
154+
$this->expectException(BadRequestException::class);
155+
$bag = new ParameterBag(['foo' => 'bar']);
156+
$bag->getArray('foo');
157+
}
158+
144159
public function testFilter()
145160
{
146161
$bag = new ParameterBag([

0 commit comments

Comments
 (0)
0