Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit df7d44a

Browse files
committed
[HttpFoundation] ParameterBag::getEnum()
1 parent f43cd26 commit df7d44a

File tree

3 files changed

+41
-0
lines changed

3 files changed

+41
-0
lines changed

src/Symfony/Component/HttpFoundation/CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ CHANGELOG
55
---
66

77
* Create migration for session table when pdo handler is used
8+
* Add `ParameterBar::getEnum()`
89

910
6.2
1011
---

src/Symfony/Component/HttpFoundation/ParameterBag.php

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -141,6 +141,27 @@ public function getBoolean(string $key, bool $default = false): bool
141141
return $this->filter($key, $default, \FILTER_VALIDATE_BOOL);
142142
}
143143

144+
/**
145+
* Returns the parameter value converted to an enum.
146+
*
147+
* @template T of \BackedEnum
148+
*
149+
* @param class-string<T> $class
150+
* @param ?T $default
151+
*
152+
* @return ?T
153+
*/
154+
public function getEnum(string $key, string $class, ?\BackedEnum $default = null): ?\BackedEnum
155+
{
156+
$value = $this->get($key);
157+
158+
if (null === $value) {
159+
return $default;
160+
}
161+
162+
return $class::tryFrom($value) ?? $default;
163+
}
164+
144165
/**
145166
* Filter key.
146167
*

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

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -226,4 +226,23 @@ public function testGetBoolean()
226226
$this->assertFalse($bag->getBoolean('string_false'), '->getBoolean() gets the string false as boolean false');
227227
$this->assertFalse($bag->getBoolean('unknown'), '->getBoolean() returns false if a parameter is not defined');
228228
}
229+
230+
public function testGetEnum()
231+
{
232+
$parameters = ['valid-value' => 1, 'invalid-value' => 2];
233+
$bag = new ParameterBag($parameters);
234+
235+
$this->assertSame(Foo::Bar, $bag->getEnum('valid-value', Foo::class));
236+
237+
$this->assertNull($bag->getEnum('invalid-value', Foo::class));
238+
$this->assertSame(Foo::Bar, $bag->getEnum('invalid-value', Foo::class, Foo::Bar));
239+
240+
$this->assertNull($bag->getEnum('invalid-key', Foo::class));
241+
$this->assertSame(Foo::Bar, $bag->getEnum('invalid-key', Foo::class, Foo::Bar));
242+
}
243+
}
244+
245+
enum Foo: int
246+
{
247+
case Bar = 1;
229248
}

0 commit comments

Comments
 (0)