Skip to content

Commit 98bf400

Browse files
committed
Add helper-methods to BooleanValue
1 parent 65516a9 commit 98bf400

File tree

2 files changed

+41
-0
lines changed

2 files changed

+41
-0
lines changed

src/Type/BooleanValue.php

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,10 @@
77
use SimpleSAML\XML\Assert\Assert;
88
use SimpleSAML\XML\Exception\SchemaViolationException;
99

10+
use function boolval;
11+
use function in_array;
12+
use function strval;
13+
1014
/**
1115
* @package simplesaml/xml-common
1216
*/
@@ -40,4 +44,27 @@ protected function validateValue(string $value): void
4044
// Note: value must already be sanitized before validating
4145
Assert::validBoolean($this->sanitizeValue($value), SchemaViolationException::class);
4246
}
47+
48+
49+
/**
50+
* @param boolean $value
51+
* @return static
52+
*/
53+
public static function fromBoolean(bool $value): static
54+
{
55+
return new static(
56+
$value === true ? 'true' : 'false',
57+
);
58+
}
59+
60+
61+
/**
62+
* @return boolean $value
63+
*/
64+
public function toBoolean(): bool
65+
{
66+
return boolval(
67+
in_array($this->getValue(), ['1', 'true']) ? '1' : '0',
68+
);
69+
}
4370
}

tests/Type/BooleanValueTest.php

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,20 @@ public function testBoolean(bool $shouldPass, string $boolean): void
3737
}
3838

3939

40+
/**
41+
* Test helpers
42+
*/
43+
public function testHelpers(): void
44+
{
45+
$x = BooleanValue::fromBoolean(false);
46+
$this->assertFalse($x->toBoolean());
47+
48+
$y = BooleanValue::fromString('1');
49+
$this->assertTrue($y->toBoolean());
50+
}
51+
52+
53+
4054
/**
4155
* @return array<string, array{0: true, 1: string}>
4256
*/

0 commit comments

Comments
 (0)