Completed
Push — master ( e3be67...2f9429 )
by Adelar
02:35
created

OfxParser::ofxToPrepareArray()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 10
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

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