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

BaseXmlGenerator   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 38
Duplicated Lines 0 %

Importance

Changes 5
Bugs 0 Features 0
Metric Value
wmc 6
eloc 9
c 5
b 0
f 0
dl 0
loc 38
rs 10

6 Methods

Rating   Name   Duplication   Size   Complexity  
A getXml() 0 3 1
A getXmlElement() 0 3 1
A make() 0 3 1
A __construct() 0 7 1
A escape() 0 3 1
A addChild() 0 3 1
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