Skip to content

Commit

Permalink
[HttpFoundation] ParameterBag::getEnum()
Browse files Browse the repository at this point in the history
  • Loading branch information
nikophil committed Dec 29, 2022
1 parent f43cd26 commit ed20671
Show file tree
Hide file tree
Showing 3 changed files with 41 additions and 0 deletions.
1 change: 1 addition & 0 deletions src/Symfony/Component/HttpFoundation/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ CHANGELOG
---

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

6.2
---
Expand Down
21 changes: 21 additions & 0 deletions src/Symfony/Component/HttpFoundation/ParameterBag.php
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,27 @@ public function getBoolean(string $key, bool $default = false): bool
return $this->filter($key, $default, \FILTER_VALIDATE_BOOL);
}

/**
* Returns the parameter value converted to an enum.
*
* @template T of \BackedEnum
*
* @param class-string<T> $class
* @param ?T $default
*
* @return ?T
*/
public function getEnum(string $key, string $class, \BackedEnum $default = null): ?\BackedEnum
{
$value = $this->get($key);

if (null === $value) {
return $default;
}

return $class::tryFrom($value) ?? $default;
}

/**
* Filter key.
*
Expand Down
19 changes: 19 additions & 0 deletions src/Symfony/Component/HttpFoundation/Tests/ParameterBagTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -226,4 +226,23 @@ public function testGetBoolean()
$this->assertFalse($bag->getBoolean('string_false'), '->getBoolean() gets the string false as boolean false');
$this->assertFalse($bag->getBoolean('unknown'), '->getBoolean() returns false if a parameter is not defined');
}

public function testGetEnum()
{
$parameters = ['valid-value' => 1, 'invalid-value' => 2];
$bag = new ParameterBag($parameters);

$this->assertSame(Foo::Bar, $bag->getEnum('valid-value', Foo::class));

$this->assertNull($bag->getEnum('invalid-value', Foo::class));
$this->assertSame(Foo::Bar, $bag->getEnum('invalid-value', Foo::class, Foo::Bar));

$this->assertNull($bag->getEnum('invalid-key', Foo::class));
$this->assertSame(Foo::Bar, $bag->getEnum('invalid-key', Foo::class, Foo::Bar));
}
}

enum Foo: int
{
case Bar = 1;
}

0 comments on commit ed20671

Please sign in to comment.