XMLHelper_Converter::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 1
c 0
b 0
f 0
dl 0
loc 3
rs 10
cc 1
nc 1
nop 1
1
<?php
2
/**
3
 * File containing the {@link XMLHelper_Converter} class.
4
 * 
5
 * @package Application Utils
6
 * @subpackage XMLHelper
7
 * @see XMLHelper_Converter
8
 */
9
10
namespace AppUtils;
11
12
use AppUtils\ConvertHelper\JSONConverter;
13
use AppUtils\ConvertHelper\JSONConverter\JSONConverterException;
14
use DOMElement;
15
use Exception;
16
use SimpleXMLElement;
17
18
/**
19
 * Simple XML converter that can transform an XML document
20
 * to JSON or an associative array.
21
 * 
22
 * It uses a custom JSON decorator to convert a SimpleXMLElement,
23
 * which solves many of the usual issues when trying to convert
24
 * those to JSON. It is not a catch-all, but works well with
25
 * most XML documents.
26
 * 
27
 * Converting an XML file to array:
28
 * 
29
 * <pre>
30
 * $converter = XMLHelper_Converter::fromFile('path/to/xml/file.xml');
31
 * $array = $converter->toArray();
32
 * </pre>
33
 * 
34
 * Converting an XML string to array:
35
 * 
36
 * <pre>
37
 * $converter = XMLHelper_Converter::fromString('<document>XML source here</document>');
38
 * $array = $converter->toArray();
39
 * </pre>
40
 * 
41
 * @package Application Utils
42
 * @subpackage XMLHelper
43
 * @author Sebastian Mordziol <[email protected]>
44
 *
45
 */
46
class XMLHelper_Converter
47
{
48
    public const ERROR_FAILED_CONVERTING_TO_JSON = 37901;
49
    public const ERROR_CANNOT_CREATE_ELEMENT_FROM_STRING = 37902;
50
    public const ERROR_FAILED_CONVERTING_TO_ARRAY = 37902;
51
    
52
    protected SimpleXMLElement $xml;
53
    
54
   /**
55
    * @var string|NULL
56
    */
57
    protected ?string $json;
58
    
59
    protected function __construct(SimpleXMLElement $element)
60
    {
61
        $this->xml = $element;
62
    }
63
64
    /**
65
     * Factory method: creates a converter from an XML file on disk.
66
     *
67
     * @param string $path
68
     * @return XMLHelper_Converter
69
     * @throws FileHelper_Exception
70
     * @throws XMLHelper_Exception
71
     */
72
    public static function fromFile(string $path) : XMLHelper_Converter
73
    {
74
        return self::fromString(FileHelper::readContents($path));
75
    }
76
77
    /**
78
     * Factory method: creates a converter from an XML string.
79
     *
80
     * @param string $xmlString
81
     * @return XMLHelper_Converter
82
     * @throws XMLHelper_Exception
83
     */
84
    public static function fromString(string $xmlString) : XMLHelper_Converter
85
    {
86
        try
87
        {
88
            return self::fromElement(new SimpleXMLElement($xmlString));
89
        }
90
        catch (Exception $e)
91
        {
92
            throw new XMLHelper_Exception(
93
                'Cannot create new element from string.',
94
                '',
95
                self::ERROR_CANNOT_CREATE_ELEMENT_FROM_STRING,
96
                $e
97
            );
98
        }
99
    }
100
    
101
   /**
102
    * Factory method: creates a converter from an existing SimpleXMLElement instance.
103
    * 
104
    * @param SimpleXMLElement $element
105
    * @return XMLHelper_Converter
106
    */
107
    public static function fromElement(SimpleXMLElement $element) : XMLHelper_Converter
108
    {
109
        return new XMLHelper_Converter($element);
110
    }
111
112
   /**
113
    * Factory method: creates a converter from an existing SimpleXMLElement instance.
114
    *
115
    * @param DOMElement $element
116
    * @return XMLHelper_Converter
117
    */
118
    public static function fromDOMElement(DOMElement $element) : XMLHelper_Converter
119
    {
120
        return new XMLHelper_Converter(simplexml_import_dom($element));
121
    }
122
    
123
   /**
124
    * Converts the XML to JSON.
125
    * 
126
    * @return string
127
    * @throws XMLHelper_Exception
128
    */
129
    public function toJSON() : string
130
    {
131
        if (isset($this->json))
132
        {
133
            return $this->json;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $this->json could return the type null which is incompatible with the type-hinted return string. Consider adding an additional type-check to rule them out.
Loading history...
134
        }
135
136
        $decorator = new XMLHelper_Converter_Decorator($this->xml);
137
138
        try
139
        {
140
            $this->json = JSONConverter::var2json($decorator, JSON_PRETTY_PRINT);
141
142
            unset($this->xml);
143
144
            return $this->json;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $this->json returns the type null which is incompatible with the type-hinted return string.
Loading history...
145
        }
146
        catch (JSONConverterException $e)
147
        {
148
            throw new XMLHelper_Exception(
149
                'Could not convert the XML source to JSON.',
150
                sprintf(
151
                    'XML source excerpt: '.PHP_EOL.
152
                    '-----------------------------------------------------------'.
153
                    '%s'.PHP_EOL.
154
                    '-----------------------------------------------------------',
155
                    ConvertHelper::text_cut($this->xml, 300)
156
                ),
157
                self::ERROR_FAILED_CONVERTING_TO_JSON,
158
                $e
159
            );
160
        }
161
    }
162
163
    /**
164
     * Converts the XML to an associative array.
165
     * @return array<mixed>
166
     *
167
     * @throws XMLHelper_Exception
168
     */
169
    public function toArray() : array 
170
    {
171
        try
172
        {
173
            return JSONConverter::json2array($this->toJSON());
174
        }
175
        catch (JSONConverterException $e)
176
        {
177
            throw new XMLHelper_Exception(
178
                'Could not convert the JSON string to an array.',
179
                '',
180
                self::ERROR_FAILED_CONVERTING_TO_ARRAY,
181
                $e
182
            );
183
        }
184
    }
185
}
186