Passed
Push — master ( 137285...61ce3c )
by Caen
03:22 queued 12s
created

BaseXmlGenerator::getXmlElement()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
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 3
rs 10
cc 1
nc 1
nop 0
1
<?php
2
3
/** @noinspection PhpComposerExtensionStubsInspection */
4
5
declare(strict_types=1);
6
7
namespace Hyde\Framework\Features\XmlGenerators;
8
9
use Exception;
10
use function extension_loaded;
11
use function htmlspecialchars;
12
use SimpleXMLElement;
13
use function throw_unless;
14
15
abstract class BaseXmlGenerator implements XmlGeneratorContract
16
{
17
    protected SimpleXMLElement $xmlElement;
18
19
    abstract protected function constructBaseElement(): void;
20
21
    public static function make(): string
22
    {
23
        return (new static)->generate()->getXML();
24
    }
25
26
    public function __construct()
27
    {
28
        throw_unless(extension_loaded('simplexml'),
29
            new Exception('The SimpleXML extension is required to generate RSS feeds and sitemaps.')
30
        );
31
32
        $this->constructBaseElement();
33
    }
34
35
    public function getXml(): string
36
    {
37
        return (string) $this->xmlElement->asXML();
38
    }
39
40
    public function getXmlElement(): SimpleXMLElement
41
    {
42
        return $this->xmlElement;
43
    }
44
45
    protected function escape(string $string): string
46
    {
47
        return htmlspecialchars($string, ENT_XML1 | ENT_COMPAT, 'UTF-8');
48
    }
49
50
    protected function addChild(SimpleXMLElement $element, string $name, string $value): SimpleXMLElement
51
    {
52
        return $element->addChild($name, $this->escape($value));
53
    }
54
}
55