Completed
Pull Request — master (#95)
by
unknown
05:12
created

MT940::parseToArray()   D

Complexity

Conditions 18
Paths 42

Size

Total Lines 100
Code Lines 64

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 56
CRAP Score 21.0566

Importance

Changes 8
Bugs 3 Features 0
Metric Value
dl 0
loc 100
ccs 56
cts 71
cp 0.7887
rs 4.7996
c 8
b 3
f 0
cc 18
eloc 64
nc 42
nop 0
crap 21.0566

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
namespace Fhp\Parser;
4
5
use Fhp\Parser\Exception\MT940Exception;
6
7
/**
8
 * Class MT940
9
 * @package Fhp\Parser
10
 */
11
class MT940
12
{
13
	const TARGET_ARRAY = 0;
14
15
	const CD_CREDIT = 'credit';
16
	const CD_DEBIT = 'debit';
17
	const CD_CREDIT_CANCELLATION = 'credit_cancellation';
18
	const CD_DEBIT_CANCELLATION = 'debit_cancellation';
19
20
	/** @var string */
21
	protected $rawData;
22
	/** @var string */
23
	protected $soaDate;
24
25
	/**
26
	 * MT940 constructor.
27
	 *
28
	 * @param string $rawData
29
	 */
30 1
	public function __construct($rawData)
31
	{
32 1
		$this->rawData = (string) $rawData;
33 1
	}
34
35
	/**
36
	 * @param string $target
37
	 * @return array
38
	 * @throws MT940Exception
39
	 */
40 1
	public function parse($target)
41
	{
42
		switch ($target) {
43 1
		case static::TARGET_ARRAY:
44 1
			return $this->parseToArray();
45
			break;
0 ignored issues
show
Unused Code introduced by
break is not strictly necessary here and could be removed.

The break statement is not necessary if it is preceded for example by a return statement:

switch ($x) {
    case 1:
        return 'foo';
        break; // This break is not necessary and can be left off.
}

If you would like to keep this construct to be consistent with other case statements, you can safely mark this issue as a false-positive.

Loading history...
46
		default:
47
			throw new MT940Exception('Invalid parse type provided');
48
		}
49
	}
50
51
	/**
52
	 * @return array
53
	 * @throws MT940Exception
54
	 */
55 1
	protected function parseToArray()
56
	{
57
		// The divider can be either \r\n or @@
58
59 1
		$divider = "(@@|\r\n)";
60 1
		$result = array();
61 1
		$days = preg_split('/' . $divider . '-' . $divider . '/', $this->rawData);
62
63 1
		foreach ($days as $day) {
64 1
			$day = preg_split('/' . $divider . ':/', $day);
65 1
			$statement = array();
66 1
			$transactions = array();
67 1
			$cnt = 0;
0 ignored issues
show
Unused Code introduced by
$cnt is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
68 1
			for ($i = 0, $cnt = count($day); $i < $cnt; $i++) {
69
				// handle start balance
70
				// 60F:C160401EUR1234,56
0 ignored issues
show
Unused Code Comprehensibility introduced by
50% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
71 1
				if (preg_match('/^60(F|M):/', $day[$i])) {
72
					// remove 60(F|M): for better parsing
0 ignored issues
show
Unused Code Comprehensibility introduced by
38% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
73 1
					$day[$i] = substr($day[$i], 4);
74 1
					$this->soaDate = $this->getDate(substr($day[$i], 1, 6));
75
76 1
					$amount = str_replace(',', '.', substr($day[$i], 10));
77 1
					$statement['start_balance'] = array(
78 1
						'amount' => $amount,
79 1
						'credit_debit' => (substr($day[$i], 0, 1) == 'C') ? static::CD_CREDIT : static::CD_DEBIT
80 1
					);
81 1
					$statement['date'] = $this->soaDate;
82 1
				} elseif (
83
					// found transaction
84
					// trx:61:1603310331DR637,39N033NONREF
0 ignored issues
show
Unused Code Comprehensibility introduced by
56% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
85 1
					0 === strpos($day[$i], '61:')
86 1
					&& isset($day[$i + 1])
87 1
					&& 0 === strpos($day[$i + 1], '86:')
88 1
				) {
89 1
					$transaction = substr($day[$i], 3);
90 1
					$description = substr($day[$i + 1], 3);
91
92 1
					$currentTrx = array();
93
94 1
					preg_match('/^\d{6}(\d{4})?(C|D|RC|RD)[A-Z]?([^N]+)N/', $transaction, $matches);
95
96 1
					switch($matches[2]) {
97 1
					case 'C':
98 1
						$currentTrx['credit_debit'] = static::CD_CREDIT;
99 1
						break;
100
					case 'D':
101
						$currentTrx['credit_debit'] = static::CD_DEBIT;
102
						break;
103
					case 'RC':
104
						$currentTrx['credit_debit'] = static::CD_CREDIT_CANCELLATION;
105
						break;
106
					case 'RD':
107
						$currentTrx['credit_debit'] = static::CD_DEBIT_CANCELLATION;
108
						break;
109
					default:
110
						throw new MT940Exception('c/d/rc/rd mark not found in: ' . $transaction);
111 1
					}
112
113 1
					$amount = $matches[3];
114 1
					$amount = str_replace(',', '.', $amount);
115 1
					$currentTrx['amount'] = floatval($amount);
116
117 1
					$currentTrx['transaction_code'] = substr($description, 0, 3);
118
119 1
					$description = $this->parseDescription($description);
120 1
					$currentTrx['description'] = $description;
121
122
					// :61:1605110509D198,02NMSCNONREF
0 ignored issues
show
Unused Code Comprehensibility introduced by
67% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
123
					// 16 = year
124
					// 0511 = valuta date
125
					// 0509 = booking date
126 1
					$year = substr($transaction, 0, 2);
127 1
					$valutaDate = $this->getDate($year . substr($transaction, 2, 4));
128
129 1
					$bookingDate = substr($transaction, 6, 4);
130 1
					if (preg_match('/^\d{4}$/', $bookingDate)) {
131
						// if valuta date is earlier than booking date, then it must be in the new year.
132 1
						if (substr($transaction, 2, 2) == '12' && substr($transaction, 6, 2) == '01') {
133
							$year++;
134 1
						} elseif (substr($transaction, 2, 2) == '01' && substr($transaction, 6, 2) == '12') {
135
							$year--;
136
						}
137 1
						$bookingDate = $this->getDate($year . $bookingDate);
138 1
					} else {
139
						// if booking date not set in :61, then we have to take it from :60F
140
						$bookingDate = $this->soaDate;
141
					}
142
143 1
					$currentTrx['booking_date'] = $bookingDate;
144 1
					$currentTrx['valuta_date'] = $valutaDate;
145
146 1
					$transactions[] = $currentTrx;
147 1
				}
148 1
			}
149 1
			$statement['transactions'] = $transactions;
150 1
			if (count($transactions) > 0) $result[] = $statement;
151 1
		}
152
153 1
		return $result;
154
	}
155
156
	/**
157
	 * @param string $descr
158
	 * @return array
159
	 */
160 1
	protected function parseDescription($descr)
161
	{
162 1
		$prepared = array();
163 1
		$result = array();
164
165
		// prefill with empty values
166 1
		for ($i = 0; $i <= 63; $i++) {
167 1
			$prepared[$i] = null;
168 1
		}
169
170 1
		$descr = str_replace("\r\n", '', $descr);
171 1
		$descr = str_replace('? ', '?', $descr);
172 1
		preg_match_all('/\?[\r\n]*(\d{2})([^\?]+)/', $descr, $matches, PREG_SET_ORDER);
173
174 1
		$descriptionLines = array();
175 1
		$description1 = ''; // Legacy, could be removed.
176 1
		$description2 = ''; // Legacy, could be removed.
177 1
		foreach ($matches as $m) {
178 1
			$index = (int) $m[1];
179 1
			if ((20 <= $index && $index <= 29) || (60 <= $index && $index <= 63)) {
180 1
				if (20 <= $index && $index <= 29) {
181 1
					$description1 .= $m[2];
182 1
				} else {
183
					$description2 .= $m[2];
184
				}
185 1
				$m[2] = trim($m[2]);
186 1
				if (!empty($m[2])) {
187 1
					$descriptionLines[] = $m[2];
188 1
				}
189 1
			} else {
190 1
				$prepared[$index] = $m[2];
191
			}
192 1
		}
193
194 1
		$description = array();
195 1
		if (empty($descriptionLines) || strlen($descriptionLines[0]) < 5 || $descriptionLines[0][4] !== '+') {
196
			$description['SVWZ'] = implode('', $descriptionLines);
197
		} else {
198 1
			$lastType = null;
199 1
			foreach ($descriptionLines as $line) {
200 1
				if (strlen($line) > 5 && $line[4] === '+') {
201 1
					if ($lastType != null) {
0 ignored issues
show
Bug introduced by
It seems like you are loosely comparing $lastType of type string|null against null; this is ambiguous if the string can be empty. Consider using a strict comparison !== instead.
Loading history...
202 1
						$description[$lastType] = trim($description[$lastType]);
203 1
					}
204 1
					$lastType = substr($line, 0, 4);
205 1
					$description[$lastType] = substr($line, 5);
206 1
				} else {
207 1
					$description[$lastType] .= $line;
208
				}
209 1
				if (strlen($line) < 27) {
210
					// Usually, lines are 27 characters long. In case characters are missing, then it's either the end
211
					// of the current type or spaces have been trimmed from the end. We want to collapse multiple spaces
212
					// into one and we don't want to leave trailing spaces behind. So add a single space here to make up
213
					// for possibly missing spaces, and if it's the end of the type, it will be trimmed off later.
214 1
					$description[$lastType] .= ' ';
215 1
				}
216 1
			}
217 1
			$description[$lastType] = trim($description[$lastType]);
218
		}
219
220 1
		$result['description']       = $description;
221 1
		$result['booking_text']      = trim($prepared[0]);
222 1
		$result['primanoten_nr']     = trim($prepared[10]);
223 1
		$result['description_1']     = trim($description1);
224 1
		$result['bank_code']         = trim($prepared[30]);
225 1
		$result['account_number']    = trim($prepared[31]);
226 1
		$result['name']              = trim($prepared[32] . $prepared[33]);
227 1
		$result['text_key_addition'] = trim($prepared[34]);
228 1
		$result['description_2']     = trim($description2);
229 1
		return $result;
230
	}
231
232
	/**
233
	 * @param string $val
234
	 * @return string
235
	 */
236 1
	protected function getDate($val)
237
	{
238 1
		$val = '20' . $val;
239 1
		preg_match('/(\d{4})(\d{2})(\d{2})/', $val, $m);
240 1
		return $m[1] . '-' . $m[2] . '-' . $m[3];
241
	}
242
}
243