Test Failed
Push — master ( eddc49...ac2406 )
by Adelar
01:50
created

OfxParser::loadFromString()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 12
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 2
Bugs 0 Features 0
Metric Value
c 2
b 0
f 0
dl 0
loc 12
ccs 0
cts 12
cp 0
rs 9.4285
cc 2
eloc 9
nc 2
nop 1
crap 6
1
<?php
2
declare(strict_types = 1);
3
namespace Adelarcubs\OFXParser;
4
5
/**
6
 *
7
 * @author Adelar Tiemann Junior <[email protected]>
8
 */
9
class OfxParser
10
{
11
12
    /**
13
     *
14
     * @param mixed $ofx
15
     *            File or File Path
16
     * @return Ofx
17
     */
18
    public static function loadOfx($ofx)
19
    {
20
        if (file_exists($ofx)) {
21
            $ofx = file_get_contents($ofx);
22
        }
23
        return OfxParser::loadFromString($ofx);
24
    }
25
26
    private static function loadFromString($ofxContent)
27
    {
28
        $xml = OfxParser::closeUnclosedXmlTags($ofxContent);
29
        libxml_clear_errors();
30
        libxml_use_internal_errors(true);
31
        $xml = simplexml_load_string($xml);
32
        $errors = libxml_get_errors();
33
        if (! empty($errors)) {
34
            throw new \Exception("Failed to parse OFX: " . var_export($errors, true));
35
        }
36
        return new Ofx($xml);
37
    }
38
39
    private static function closeUnclosedXmlTags($ofxContent)
40
    {
41
        $lines = OfxParser::ofxToPrepareArray($ofxContent);
42
        $xml = "";
43
44
        $lastClosedTag = '';
45
        foreach ($lines as $line) {
46
            if ($line != "") {
47
                $read = $line;
48
                $pos = strpos($read, ">");
49
                $tag = substr($read, 1, $pos);
50
                $value = trim(substr($read, $pos + 1));
51
                $line = '<' . $tag;
52
                if ($value != '') {
53
                    $line .= $value;
54
                    if (strpos($value, '</' . $tag) === false) {
55
                        $lastClosedTag = '/' . $tag;
56
                        $line .= '<' . $lastClosedTag;
57
                    }
58
                } else {
59
                    if ($lastClosedTag == $tag) {
60
                        $line = '';
61
                    }
62
                }
63
                $xml .= $line . "\n";
64
            }
65
        }
66
        return $xml;
67
    }
68
69
    private static function getOfxPart($ofxFileContent)
70
    {
71
        $sgmlStart = stripos($ofxFileContent, '<OFX>');
72
        return trim(substr($ofxFileContent, $sgmlStart));
73
    }
74
75
    private static function ofxToPrepareArray($ofx)
76
    {
77
        $ofxContent = OfxParser::getOfxPart($ofx);
78
79
        $xml = str_replace("\r", "", $ofxContent);
80
        $xml = str_replace("\n", "", $xml);
81
        $xml = str_replace("<", "\n<", $xml);
82
83
        return explode("\n", $xml);
84
    }
85
}
86