Passed
Pull Request — master (#55)
by Tim
02:39
created

BooleanValue::validateValue()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 1
c 1
b 0
f 0
dl 0
loc 4
rs 10
cc 1
nc 1
nop 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace SimpleSAML\XML\Type;
6
7
use SimpleSAML\XML\Assert\Assert;
8
use SimpleSAML\XML\Exception\SchemaViolationException;
9
10
use function boolval;
11
use function in_array;
12
use function strval;
13
14
/**
15
 * @package simplesaml/xml-common
16
 */
17
class BooleanValue extends AbstractValueType
18
{
19
    /** @var string */
20
    public const SCHEMA_TYPE = 'boolean';
21
22
23
    /**
24
     * Sanitize the value.
25
     *
26
     * @param string $value  The unsanitized value
27
     * @return string
28
     */
29
    protected function sanitizeValue(string $value): string
30
    {
31
        return static::collapseWhitespace(static::normalizeWhitespace($value));
32
    }
33
34
35
    /**
36
     * Validate the value.
37
     *
38
     * @param string $value
39
     * @throws \SimpleSAML\XML\Exception\SchemaViolationException on failure
40
     * @return void
41
     */
42
    protected function validateValue(string $value): void
43
    {
44
        // Note: value must already be sanitized before validating
45
        Assert::validBoolean($this->sanitizeValue($value), SchemaViolationException::class);
46
    }
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
    }
70
}
71