Passed
Push — master ( cb463c...b11a9d )
by Jesse
01:56
created

XmlFormatter::__construct()   A

Complexity

Conditions 2
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 2
c 1
b 0
f 0
nc 1
nop 2
dl 0
loc 4
rs 10
1
<?php declare(strict_types=1);
2
3
namespace Stratadox\RestResource;
4
5
use SimpleXMLElement;
6
use Throwable;
7
use function sprintf;
8
9
abstract class XmlFormatter implements ResourceFormatter
10
{
11
    use LinkRetrieval;
12
13
    /** @var string */
14
    private $baseUri;
15
    /** @var Singularizer */
16
    protected $singularizer;
17
18
    public function __construct(string $baseUri, Singularizer $singularizer = null)
19
    {
20
        $this->baseUri = $baseUri;
21
        $this->singularizer = $singularizer ?: BoogieSingularizer::default();
22
    }
23
24
    public static function in(
25
        string $locale,
26
        string $baseUri
27
    ): ResourceFormatter {
28
        return new static($baseUri, BoogieSingularizer::in($locale));
29
    }
30
31
    public function from(RestResource $resource): string
32
    {
33
        $xml = new SimpleXMLElement(sprintf(
34
            '<?xml version="1.0"?><%s />',
35
            $resource->name()
36
        ));
37
        try {
38
            $this->toSimpleXML(
39
                $resource->body() + $this->linksOf($resource, $this->baseUri),
40
                $xml
41
            );
42
            return (string) $xml->asXML();
43
        } catch (Throwable $exception) {
44
            throw CannotFormatXml::because($resource, $exception);
45
        }
46
    }
47
48
    // @todo inject serializer instead
49
    abstract protected function toSimpleXML(
50
        array $input,
51
        SimpleXMLElement $parent,
52
        bool $alreadySingularized = false
53
    ): void;
54
}
55