Completed
Push — master ( 7edb4c...18c0ae )
by Nikola
03:09
created

NationalBankOfSerbiaXmlSaxParser::parseXml()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 5
ccs 3
cts 3
cp 1
rs 9.4286
cc 1
eloc 3
nc 1
nop 1
crap 1
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 2
    public function parse($xml)
57
    {
58 2
        $this->rates = array();
59 2
        $this->stack = new \SplStack();
60 2
        $this->currentRate = array();
61 2
        $this->date = new \DateTime('now');
62 2
        $this->rateType = 'default';
63
64 2
        $parser = xml_parser_create();
65
66 2
        xml_set_element_handler(
67 2
            $parser,
68
            \Closure::bind(function($parser, $name, $attributes) {
69 2
                $this->onStart($parser, $name, $attributes);
70 2
            }, $this),
71
            \Closure::bind(function($parser, $name) {
72 2
                $this->onEnd($parser, $name);
73 2
            }, $this)
74 2
        );
75
76 2
        xml_set_character_data_handler(
77 2
            $parser,
78 2
            \Closure::bind(function($parser, $data) {
79 2
                $this->onData($parser, $data);
80 2
            }, $this));
81
82 2
        xml_parse($parser, $xml);
83 2
        xml_parser_free($parser);
84
85 2
        return $this->rates;
86
    }
87
88
    /**
89
     * SAX on tag start callback.
90
     *
91
     * @param $parser
92
     * @param $name
93
     * @param $attributes
94
     */
95 2
    private function onStart($parser, $name, $attributes)
2 ignored issues
show
Unused Code introduced by
The parameter $parser is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Unused Code introduced by
The parameter $attributes is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
96
    {
97 2
        if (!empty($name)) {
98
99 2
            $this->stack->push($name);
100
101 2
            if ($name === 'ITEM') {
102 2
                $this->currentRate = array();
103 2
            }
104 2
        }
105 2
    }
106
107
    /**
108
     * SAX on tag end callback.
109
     *
110
     * @param $parser
111
     * @param $name
112
     */
113 2
    private function onEnd($parser, $name)
1 ignored issue
show
Unused Code introduced by
The parameter $parser is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
114
    {
115 2
        if (!empty($name)) {
116
117 2
            $this->stack->pop();
118
119 2
            if ($name === 'ITEM') {
120
121 2 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...
122
123
                    $this->rates[] = new Rate(
124
                        NationalBankOfSerbiaDomCrawlerSource::NAME,
125
                        $this->currentRate['buyingRate'] / $this->currentRate['unit'],
126
                        $this->currentRate['currencyCode'],
127
                        $this->rateType . '_buying',
128
                        $this->date,
129
                        'RSD',
130
                        new \DateTime('now'),
131
                        new \DateTime('now')
132
                    );
133
                }
134
135 2 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...
136
137
                    $this->rates[] = new Rate(
138
                        NationalBankOfSerbiaDomCrawlerSource::NAME,
139
                        $this->currentRate['sellingRate'] / $this->currentRate['unit'],
140
                        $this->currentRate['currencyCode'],
141
                        $this->rateType . '_selling',
142
                        $this->date,
143
                        'RSD',
144
                        new \DateTime('now'),
145
                        new \DateTime('now')
146
                    );
147
                }
148
149 2 View Code Duplication
                if (array_key_exists('middleRate', $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...
150
151 2
                    $this->rates[] = new Rate(
152 2
                        NationalBankOfSerbiaDomCrawlerSource::NAME,
153 2
                        $this->currentRate['middleRate'] / $this->currentRate['unit'],
154 2
                        $this->currentRate['currencyCode'],
155 2
                        'default',
156 2
                        $this->date,
157 2
                        'RSD',
158 2
                        new \DateTime('now'),
159 2
                        new \DateTime('now')
160 2
                    );
161 2
                }
162
163 2
                $this->currentRate = array();
164 2
            }
165 2
        }
166 2
    }
167
168
    /**
169
     * SAX on data callback.
170
     *
171
     * @param $parser
172
     * @param $data
173
     */
174 2
    private function onData($parser, $data)
1 ignored issue
show
Unused Code introduced by
The parameter $parser is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
175
    {
176 2
        if (!empty($data)) {
177
178 2
            switch ($this->stack->top()) {
179 2
                case 'DATE':
180 2
                    $this->date = \DateTime::createFromFormat('d.m.Y', $data);
1 ignored issue
show
Documentation Bug introduced by
It seems like \DateTime::createFromFormat('d.m.Y', $data) can also be of type false. However, the property $date is declared as type object<DateTime>. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
181 2
                    break;
182 2
                case 'TYPE':
183 2
                    $data = trim($data);
184 2
                    if ($data === 'FOREIGN EXCHANGE') {
185
                        $this->rateType = 'foreign_exchange';
186 2
                    } elseif ($data === 'FOREIGN CASH') {
187
                        $this->rateType = 'foreign_cache';
188
                    }
189 2
                    break;
190 2
                case 'CURRENCY':
191 2
                    $this->currentRate['currencyCode'] = trim($data);
192 2
                    break;
193 2
                case 'UNIT':
194 2
                    $this->currentRate['unit'] = (int) trim($data);
195 2
                    break;
196 2
                case 'BUYING_RATE':
197
                    $this->currentRate['buyingRate'] = (float) trim($data);
198
                    break;
199 2
                case 'SELLING_RATE':
200
                    $this->currentRate['sellingRate'] = (float) trim($data);
201
                    break;
202 2
                case 'MIDDLE_RATE':
203 2
                    $this->currentRate['middleRate'] = (float) trim($data);
204 2
                    break;
205 2
            }
206
207 2
        }
208 2
    }
209
210
    /**
211
     * Parse XML from National bank of Serbia.
212
     *
213
     * @param string $xml
214
     * @return RateInterface[]
215
     */
216 2
    public static function parseXml($xml)
217
    {
218 2
        $parser = new static();
219 2
        return $parser->parse($xml);
220
    }
221
}
222