|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +namespace SimpleSAML\XML; |
| 6 | + |
| 7 | +use DOMElement; |
| 8 | +use SimpleSAML\Assert\Assert; |
| 9 | +use SimpleSAML\XML\Exception\InvalidDOMElementException; |
| 10 | +use SimpleSAML\XML\Exception\SchemaViolationException; |
| 11 | + |
| 12 | +/** |
| 13 | + * Trait grouping common functionality for simple boolean elements |
| 14 | + * |
| 15 | + * @package simplesamlphp/xml-common |
| 16 | + */ |
| 17 | +trait BooleanElementTrait |
| 18 | +{ |
| 19 | + use StringElementTrait; |
| 20 | + |
| 21 | + /** |
| 22 | + * Validate the content of the element. |
| 23 | + * |
| 24 | + * @param string $content The value to go in the XML textContent |
| 25 | + * @throws \Exception on failure |
| 26 | + * @return void |
| 27 | + */ |
| 28 | + protected function validateContent(string $content): void |
| 29 | + { |
| 30 | + Assert::oneOf( |
| 31 | + $content, |
| 32 | + ['0', '1', 'false', 'true'], |
| 33 | + sprintf('The value of %s must be a boolean, "%s" given.', $this->getQualifiedName(), $content), |
| 34 | + SchemaViolationException::class, |
| 35 | + ); |
| 36 | + } |
| 37 | + |
| 38 | + |
| 39 | + /** |
| 40 | + * Convert XML into a class instance |
| 41 | + * |
| 42 | + * @param \DOMElement $xml The XML element we should load |
| 43 | + * @return static |
| 44 | + * |
| 45 | + * @throws \SimpleSAML\XML\Exception\InvalidDOMElementException |
| 46 | + * If the qualified name of the supplied element is wrong |
| 47 | + */ |
| 48 | + public static function fromXML(DOMElement $xml): static |
| 49 | + { |
| 50 | + Assert::same($xml->localName, static::getLocalName(), InvalidDOMElementException::class); |
| 51 | + Assert::same($xml->namespaceURI, static::NS, InvalidDOMElementException::class); |
| 52 | + |
| 53 | + return new static($xml->textContent); |
| 54 | + } |
| 55 | + |
| 56 | + |
| 57 | + /** |
| 58 | + * @param \DOMElement|null $parent |
| 59 | + * @return \DOMElement |
| 60 | + */ |
| 61 | + final public function toXML(DOMElement $parent = null): DOMElement |
| 62 | + { |
| 63 | + $e = $this->instantiateParentElement($parent); |
| 64 | + $e->textContent = $this->getContent(); |
| 65 | + |
| 66 | + return $e; |
| 67 | + } |
| 68 | +} |
0 commit comments