Completed
Push — master ( 4a992e...75438f )
by Nikola
03:21
created

NationalBankOfSerbiaXmlSaxParser   A

Complexity

Total Complexity 20

Size/Duplication

Total Lines 194
Duplicated Lines 9.28 %

Coupling/Cohesion

Components 1
Dependencies 1

Test Coverage

Coverage 0%

Importance

Changes 2
Bugs 0 Features 0
Metric Value
wmc 20
c 2
b 0
f 0
lcom 1
cbo 1
dl 18
loc 194
ccs 0
cts 111
cp 0
rs 10

5 Methods

Rating   Name   Duplication   Size   Complexity  
B parse() 0 31 1
A onStart() 0 8 2
B onEnd() 18 53 5
C onData() 0 34 11
A parseXml() 0 5 1

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

1
<?php
2
/*
3
 * This file is part of the Exchange Rate package, an RunOpenCode project.
4
 *
5
 * (c) 2016 RunOpenCode
6
 *
7
 * For the full copyright and license information, please view the LICENSE
8
 * file that was distributed with this source code.
9
 */
10
namespace RunOpenCode\ExchangeRate\Source\Api;
11
use RunOpenCode\ExchangeRate\Contract\RateInterface;
12
use RunOpenCode\ExchangeRate\Model\Rate;
13
use RunOpenCode\ExchangeRate\Source\NationalBankOfSerbiaDomCrawlerSource;
14
15
/**
16
 * Class NationalBankOfSerbiaXmlSaxParser
17
 *
18
 * Parses XML files from National bank of Serbia.
19
 *
20
 * @package RunOpenCode\ExchangeRate\Source\Api
21
 * @internal
22
 */
23
class NationalBankOfSerbiaXmlSaxParser
24
{
25
    /**
26
     * @var RateInterface[]
27
     */
28
    private $rates;
29
30
    /**
31
     * @var \SplStack
32
     */
33
    private $stack;
34
35
    /**
36
     * @var array
37
     */
38
    private $currentRate;
39
40
    /**
41
     * @var \DateTime
42
     */
43
    private $date;
44
45
    /**
46
     * @var string
47
     */
48
    private $rateType;
49
50
    /**
51
     * Parse XML from National bank of Serbia.
52
     *
53
     * @param string $xml
54
     * @return RateInterface[]
55
     */
56
    public function parse($xml)
57
    {
58
        $this->rates = array();
59
        $this->stack = new \SplStack();
60
        $this->currentRate = array();
61
        $this->date = new \DateTime('now');
62
        $this->rateType = 'default';
63
64
        $parser = xml_parser_create();
65
66
        xml_set_element_handler(
67
            $parser,
68
            \Closure::bind(function($parser, $name, $attributes) {
69
                $this->onStart($parser, $name, $attributes);
70
            }, $this),
71
            \Closure::bind(function($parser, $name) {
72
                $this->onEnd($parser, $name);
73
            }, $this)
74
        );
75
76
        xml_set_character_data_handler(
77
            $parser,
78
            \Closure::bind(function($parser, $data) {
79
                $this->onData($parser, $data);
80
            }, $this));
81
82
        xml_parse($parser, $xml);
83
        xml_parser_free($parser);
84
85
        return $this->rates;
86
    }
87
88
    /**
89
     * SAX on tag start callback.
90
     *
91
     * @param $parser
92
     * @param $name
93
     * @param $attributes
94
     */
95
    private function onStart($parser, $name, $attributes)
96
    {
97
        $this->stack->push($name);
98
99
        if ($name === 'ITEM') {
100
            $this->currentRate = array();
101
        }
102
    }
103
104
    /**
105
     * SAX on tag end callback.
106
     *
107
     * @param $parser
108
     * @param $name
109
     */
110
    private function onEnd($parser, $name)
111
    {
112
        $this->stack->pop();
113
114
        $buildRate = function($value, $currencyCode, $rateType, $date) {
115
116
            return new Rate(
117
                NationalBankOfSerbiaDomCrawlerSource::NAME,
118
                $value,
119
                $currencyCode,
120
                $rateType,
121
                $date,
122
                'RSD',
123
                new \DateTime('now'),
124
                new \DateTime('now')
125
            );
126
        };
127
128
        if ($name === 'ITEM') {
129
130 View Code Duplication
            if (array_key_exists('buyingRate', $this->currentRate)) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
131
132
                $this->rates[] = $buildRate(
133
                    $this->currentRate['buyingRate'] / $this->currentRate['unit'],
134
                    $this->currentRate['currencyCode'],
135
                    $this->rateType . '_buying',
136
                    $this->date
137
                );
138
            }
139
140 View Code Duplication
            if (array_key_exists('sellingRate', $this->currentRate)) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
141
142
                $this->rates[] = $buildRate(
143
                    $this->currentRate['sellingRate'] / $this->currentRate['unit'],
144
                    $this->currentRate['currencyCode'],
145
                    $this->rateType . '_selling',
146
                    $this->date
147
                );
148
            }
149
150
            if (array_key_exists('middleRate', $this->currentRate)) {
151
152
                $this->rates[] = $buildRate(
153
                    $this->currentRate['middleRate'] / $this->currentRate['unit'],
154
                    $this->currentRate['currencyCode'],
155
                    'default',
156
                    $this->date
157
                );
158
            }
159
160
            $this->currentRate = array();
161
        }
162
    }
163
164
    /**
165
     * SAX on data callback.
166
     *
167
     * @param $parser
168
     * @param $data
169
     */
170
    private function onData($parser, $data)
171
    {
172
        if (!empty($data)) {
173
174
            switch ($this->stack->top()) {
175
                case 'DATE':
176
                    $this->date = \DateTime::createFromFormat('d.m.Y', $data);
177
                    break;
178
                case 'TYPE':
179
                    $data = trim($data);
180
                    if ($data === 'FOREIGN EXCHANGE') {
181
                        $this->rateType = 'foreign_exchange';
182
                    } elseif ($data === 'FOREIGN CASH') {
183
                        $this->rateType = 'foreign_cache';
184
                    }
185
                    break;
186
                case 'CURRENCY':
187
                    $this->currentRate['currencyCode'] = trim($data);
188
                    break;
189
                case 'UNIT':
190
                    $this->currentRate['unit'] = (int) trim($data);
191
                    break;
192
                case 'BUYING_RATE':
193
                    $this->currentRate['buyingRate'] = (float) trim($data);
194
                    break;
195
                case 'SELLING_RATE':
196
                    $this->currentRate['sellingRate'] = (float) trim($data);
197
                    break;
198
                case 'MIDDLE_RATE':
199
                    $this->currentRate['middleRate'] = (float) trim($data);
200
                    break;
201
            }
202
        }
203
    }
204
205
    /**
206
     * Parse XML from National bank of Serbia.
207
     *
208
     * @param string $xml
209
     * @return RateInterface[]
210
     */
211
    public static function parseXml($xml)
212
    {
213
        $parser = new static();
214
        return $parser->parse($xml);
215
    }
216
}
217