This repository has been archived by the owner on Sep 8, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 100
/
Parser.php
213 lines (180 loc) · 5.93 KB
/
Parser.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
<?php
namespace OfxParser;
use SimpleXMLElement;
/**
* An OFX parser library
*
* Heavily refactored from Guillaume Bailleul's grimfor/ofxparser
*
* @author Guillaume BAILLEUL <contact@guillaume-bailleul.fr>
* @author James Titcumb <hello@jamestitcumb.com>
* @author Oliver Lowe <mrtriangle@gmail.com>
*/
class Parser
{
/**
* Factory to extend support for OFX document structures.
* @param SimpleXMLElement $xml
* @return Ofx
*/
protected function createOfx(SimpleXMLElement $xml)
{
return new Ofx($xml);
}
/**
* Load an OFX file into this parser by way of a filename
*
* @param string $ofxFile A path that can be loaded with file_get_contents
* @return Ofx
* @throws \InvalidArgumentException
*/
public function loadFromFile($ofxFile)
{
if (!file_exists($ofxFile)) {
throw new \InvalidArgumentException("File '{$ofxFile}' could not be found");
}
return $this->loadFromString(file_get_contents($ofxFile));
}
/**
* Load an OFX by directly using the text content
*
* @param string $ofxContent
* @return Ofx
*/
public function loadFromString($ofxContent)
{
$ofxContent = str_replace(["\r\n", "\r"], "\n", $ofxContent);
$ofxContent = utf8_encode($ofxContent);
$sgmlStart = stripos($ofxContent, '<OFX>');
$ofxHeader = trim(substr($ofxContent, 0, $sgmlStart));
$header = $this->parseHeader($ofxHeader);
$ofxSgml = trim(substr($ofxContent, $sgmlStart));
if (stripos($ofxHeader, '<?xml') === 0) {
$ofxXml = $ofxSgml;
} else {
$ofxSgml = $this->conditionallyAddNewlines($ofxSgml);
$ofxXml = $this->convertSgmlToXml($ofxSgml);
}
$xml = $this->xmlLoadString($ofxXml);
$ofx = $this->createOfx($xml);
$ofx->buildHeader($header);
return $ofx;
}
/**
* Detect if the OFX file is on one line. If it is, add newlines automatically.
*
* @param string $ofxContent
* @return string
*/
private function conditionallyAddNewlines($ofxContent)
{
if (preg_match('/<OFX>.*<\/OFX>/', $ofxContent) === 1) {
return str_replace('<', "\n<", $ofxContent); // add line breaks to allow XML to parse
}
return $ofxContent;
}
/**
* Load an XML string without PHP errors - throws exception instead
*
* @param string $xmlString
* @throws \RuntimeException
* @return \SimpleXMLElement
*/
private function xmlLoadString($xmlString)
{
libxml_clear_errors();
libxml_use_internal_errors(true);
$xml = simplexml_load_string($xmlString);
if ($errors = libxml_get_errors()) {
throw new \RuntimeException('Failed to parse OFX: ' . var_export($errors, true));
}
return $xml;
}
/**
* Detect any unclosed XML tags - if they exist, close them
*
* @param string $line
* @return string
*/
private function closeUnclosedXmlTags($line)
{
// Special case discovered where empty content tag wasn't closed
$line = trim($line);
if (preg_match('/<MEMO>$/', $line) === 1) {
return '<MEMO></MEMO>';
}
// Matches: <SOMETHING>blah
// Does not match: <SOMETHING>
// Does not match: <SOMETHING>blah</SOMETHING>
if (preg_match(
"/<([A-Za-z0-9.]+)>([\wà-úÀ-Ú0-9\.\-\_\+\, ;:\[\]\'\&\/\\\*\(\)\+\{\|\}\!\£\$\?=@€£#%±§~`\"]+)$/",
$line,
$matches
)) {
return "<{$matches[1]}>{$matches[2]}</{$matches[1]}>";
}
return $line;
}
/**
* Parse the SGML Header to an Array
*
* @param string $ofxHeader
* @param int $sgmlStart
* @return array
*/
private function parseHeader($ofxHeader)
{
$header = [];
$ofxHeader = trim($ofxHeader);
// Remove empty new lines.
$ofxHeader = preg_replace('/^\n+/m', '', $ofxHeader);
// Check if it's an XML file (OFXv2)
if(preg_match('/^<\?xml/', $ofxHeader) === 1) {
// Only parse OFX headers and not XML headers.
$ofxHeader = preg_replace('/<\?xml .*?\?>\n?/', '', $ofxHeader);
$ofxHeader = preg_replace(['/"/', '/\?>/', '/<\?OFX/i'], '', $ofxHeader);
$ofxHeaderLine = explode(' ', trim($ofxHeader));
foreach ($ofxHeaderLine as $value) {
$tag = explode('=', $value);
$header[$tag[0]] = $tag[1];
}
return $header;
}
$ofxHeaderLines = explode("\n", $ofxHeader);
foreach ($ofxHeaderLines as $value) {
$tag = explode(':', $value);
$header[$tag[0]] = $tag[1];
}
return $header;
}
/**
* Convert an SGML to an XML string
*
* @param string $sgml
* @return string
*/
private function convertSgmlToXml($sgml)
{
$sgml = preg_replace('/&(?!#?[a-z0-9]+;)/', '&', $sgml);
$lines = explode("\n", $sgml);
$tags = [];
foreach ($lines as $i => &$line) {
$line = trim($this->closeUnclosedXmlTags($line)) . "\n";
// Matches tags like <SOMETHING> or </SOMETHING>
if (!preg_match("/^<(\/?[A-Za-z0-9.]+)>$/", trim($line), $matches)) {
continue;
}
// If matches </SOMETHING>, looks back and replaces all tags like
// <OTHERTHING> to <OTHERTHING/> until finds the opening tag <SOMETHING>
if ($matches[1][0] == '/') {
$tag = substr($matches[1], 1);
while (($last = array_pop($tags)) && $last[1] != $tag) {
$lines[$last[0]] = "<{$last[1]}/>";
}
} else {
$tags[] = [$i, $matches[1]];
}
}
return implode("\n", array_map('trim', $lines));
}
}