Passed
Push — master ( fc2fbe...67de1a )
by Markus
02:31
created

GetSaldo::getSaldoModel()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 13
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
dl 0
loc 13
ccs 0
cts 9
cp 0
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 8
nc 2
nop 0
crap 6
1
<?php
2
3
namespace Fhp\Response;
4
5
use Fhp\Model\Saldo;
6
7
/**
8
 * Class GetSaldo
9
 * @package Fhp\Response
10
 */
11
class GetSaldo extends Response
12
{
13
    const SEG_ACCOUNT_INFORMATION = 'HISAL';
14
    const SALDO_DEBIT = 'D';
15
    const SALDO_CREDIT = 'C';
16
17
    /**
18
     * Creates a Saldo object from response body.
19
     *
20
     * @return Saldo|null
21
     * @throws \Exception
22
     */
23
    public function getSaldoModel()
24
    {
25
        $model = null;
26
        $saldoSec = $this->findSegment(static::SEG_ACCOUNT_INFORMATION);
27
28
        if (is_string($saldoSec)) {
29
            $saldoSec = $this->splitSegment($saldoSec);
30
            array_shift($saldoSec); // get rid of header
31
            $model = $this->createModelFromArray($saldoSec);
32
        }
33
34
        return $model;
35
    }
36
37
    /**
38
     * Creates a Saldo model from array.
39
     *
40
     * @param array $array
41
     * @return Saldo
42
     * @throws \Exception
43
     */
44
    protected function createModelFromArray(array $array)
45
    {
46
        $model = new Saldo();
47
        $saldoDeg = $this->splitDeg($array[3]);
48
49
        $amount = str_replace(',', '.', $saldoDeg[1]);
50
        $creditDebit = trim($saldoDeg[0]);
51
52
        if (static::SALDO_DEBIT == $creditDebit) {
53
            $amount = - (float) $amount;
54
        } elseif (static::SALDO_CREDIT == $creditDebit) {
55
            $amount = (float) $amount;
56
        } else {
57
            throw new \Exception('Invalid Soll-Haben-Kennzeichen: ' . $creditDebit);
58
        }
59
60
        $model->setAmount($amount);
61
        $model->setCurrency($saldoDeg[2]);
62
63
        $valutaDate = $saldoDeg[3];
64
        preg_match('/(\d{4})(\d{2})(\d{2})/', $valutaDate, $m);
65
        $valutaDate = new \DateTime($m[1] . '-' . $m[2] . '-' . $m[3]);
66
        $model->setValuta($valutaDate);
67
68
        return $model;
69
    }
70
}
71