Passed
Pull Request — master (#95)
by
unknown
08:12
created

MT940   B

Complexity

Total Complexity 40

Size/Duplication

Total Lines 237
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1

Test Coverage

Coverage 85.11%

Importance

Changes 12
Bugs 5 Features 0
Metric Value
wmc 40
c 12
b 5
f 0
lcom 1
cbo 1
dl 0
loc 237
ccs 120
cts 141
cp 0.8511
rs 8.2608

5 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A parse() 0 10 2
D parseToArray() 0 101 18
C parseDescription() 0 72 18
A getDate() 0 6 1

How to fix   Complexity   

Complex Class

Complex classes like MT940 often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use MT940, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
namespace Fhp\Parser;
4
5
use Fhp\Parser\Exception\MT940Exception;
6
7
/**
8
 * Class MT940
9
 * 
10
 * See https://www.kontopruef.de/mt940s.shtml for field documentation
11
 * 
12
 * @package Fhp\Parser
13
 */
14
class MT940
15
{
16
	const TARGET_ARRAY = 0;
17
18
	const CD_CREDIT = 'credit';
19
	const CD_DEBIT = 'debit';
20
	const CD_CREDIT_CANCELLATION = 'credit_cancellation';
21
	const CD_DEBIT_CANCELLATION = 'debit_cancellation';
22
23
	// The divider can be either \r\n or @@
24
	const LINE_DIVIDER = "(@@|\r\n)";
25
26
	/** @var string */
27
	protected $rawData;
28
	/** @var string */
29
	protected $soaDate;
30
31
	/**
32
	 * MT940 constructor.
33
	 *
34
	 * @param string $rawData
35
	 */
36 1
	public function __construct($rawData)
37
	{
38 1
		$this->rawData = (string) $rawData;
39 1
	}
40
41
	/**
42
	 * @param string $target
43
	 * @return array
44
	 * @throws MT940Exception
45
	 */
46 1
	public function parse($target)
47
	{
48
		switch ($target) {
49 1
		case static::TARGET_ARRAY:
50 1
			return $this->parseToArray();
51
			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...
52
		default:
53
			throw new MT940Exception('Invalid parse type provided');
54
		}
55
	}
56
57
	/**
58
	 * @return array
59
	 * @throws MT940Exception
60
	 */
61 1
	protected function parseToArray()
62
	{
63
		
64 1
		$result = array();
65
66
		// split at every :20: ("Die Felder ":20:" bis ":28:" müssen vor jedem Zwischensaldo ausgegeben werden.")
0 ignored issues
show
Unused Code Comprehensibility introduced by
64% 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...
67 1
		$statementBlocks = preg_split('/' . self::LINE_DIVIDER . ':20:.*?' . self::LINE_DIVIDER . '/', $this->rawData);
68
69 1
		foreach ($statementBlocks as $statementBlock) {
70 1
			$parts = preg_split('/' . self::LINE_DIVIDER . ':/', $statementBlock);
71 1
			$statement = array();
72 1
			$transactions = array();
73 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...
74 1
			for ($i = 0, $cnt = count($parts); $i < $cnt; $i++) {
75
				// handle start balance
76
				// 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...
77 1
				if (preg_match('/^60[FM]:/', $parts[$i])) {
78 1
					$parts[$i] = substr($parts[$i], 4);
79 1
					$this->soaDate = $this->getDate(substr($parts[$i], 1, 6));
80
81 1
					$amount = str_replace(',', '.', substr($parts[$i], 10));
82 1
					$statement['start_balance'] = array(
83 1
									'amount' => $amount,
84 1
									'credit_debit' => (substr($parts[$i], 0, 1) == 'C') ? static::CD_CREDIT : static::CD_DEBIT
85 1
							);
86 1
					$statement['date'] = $this->soaDate;
87 1
				} elseif (
88
							// found transaction
89
							// 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...
90 1
							0 === strpos($parts[$i], '61:')
91 1
							&& isset($parts[$i + 1])
92 1
							&& 0 === strpos($parts[$i + 1], '86:')
93 1
					) {
94 1
					$transaction = substr($parts[$i], 3);
95 1
					$description = substr($parts[$i + 1], 3);
96
97 1
					$currentTrx = array();
98
99 1
					preg_match('/^\d{6}(\d{4})?(C|D|RC|RD)[A-Z]?([^N]+)N/', $transaction, $matches);
100
101 1
					switch ($matches[2]) {
102 1
							case 'C':
103 1
									$currentTrx['credit_debit'] = static::CD_CREDIT;
104 1
									break;
105
							case 'D':
106
									$currentTrx['credit_debit'] = static::CD_DEBIT;
107
									break;
108
							case 'RC':
109
									$currentTrx['credit_debit'] = static::CD_CREDIT_CANCELLATION;
110
									break;
111
							case 'RD':
112
									$currentTrx['credit_debit'] = static::CD_DEBIT_CANCELLATION;
113
									break;
114
							default:
115
									throw new MT940Exception('c/d/rc/rd mark not found in: ' . $transaction);
116 1
							}
117
118 1
					$amount = $matches[3];
119 1
					$amount = str_replace(',', '.', $amount);
120 1
					$currentTrx['amount'] = floatval($amount);
121
122 1
					$currentTrx['transaction_code'] = substr($description, 0, 3);
123
124 1
					$description = $this->parseDescription($description);
125 1
					$currentTrx['description'] = $description;
126
127
					// :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...
128
					// 16 = year
129
					// 0511 = valuta date
130
					// 0509 = booking date
131 1
					$year = substr($transaction, 0, 2);
132 1
					$valutaDate = $this->getDate($year . substr($transaction, 2, 4));
133
134 1
					$bookingDate = substr($transaction, 6, 4);
135 1
					if (preg_match('/^\d{4}$/', $bookingDate)) {
136
						// if valuta date is earlier than booking date, then it must be in the new year.
137 1
						if (substr($transaction, 2, 2) == '12' && substr($transaction, 6, 2) == '01') {
138
							$year++;
139 1
						} elseif (substr($transaction, 2, 2) == '01' && substr($transaction, 6, 2) == '12') {
140
							$year--;
141
						}
142 1
						$bookingDate = $this->getDate($year . $bookingDate);
143 1
					} else {
144
						// if booking date not set in :61, then we have to take it from :60F
145
						$bookingDate = $this->soaDate;
146
					}
147
148 1
					$currentTrx['booking_date'] = $bookingDate;
149 1
					$currentTrx['valuta_date'] = $valutaDate;
150
151 1
					$transactions[] = $currentTrx;
152 1
				}
153 1
			}
154 1
			$statement['transactions'] = $transactions;
155 1
			if (count($transactions) > 0) {
156 1
				$result[] = $statement;
157 1
			}
158 1
		}
159
160 1
		return $result;
161
	}
162
163
	/**
164
	 * @param string $descr
165
	 * @return array
166
	 */
167 1
	protected function parseDescription($descr)
168
	{
169 1
		$prepared = array();
170 1
		$result = array();
171
172
		// prefill with empty values
173 1
		for ($i = 0; $i <= 63; $i++) {
174 1
			$prepared[$i] = null;
175 1
		}
176
177 1
		$descr = preg_replace('/' . self::LINE_DIVIDER . '/', '', $descr);
178 1
		$descr = preg_replace('/  +/', ' ', $descr);
179 1
		$descr = str_replace('? ', '?', $descr);
180 1
		preg_match_all('/\?[ \r\n]*(\d{2})([^\?]+)/', $descr, $matches, PREG_SET_ORDER);
181
182 1
		$descriptionLines = array();
183 1
		$description1 = ''; // Legacy, could be removed.
184 1
		$description2 = ''; // Legacy, could be removed.
185 1
		foreach ($matches as $m) {
186 1
			$index = (int) $m[1];
187 1
			if ((20 <= $index && $index <= 29) || (60 <= $index && $index <= 63)) {
188 1
				if (20 <= $index && $index <= 29) {
189 1
					$description1 .= $m[2];
190 1
				} else {
191
					$description2 .= $m[2];
192
				}
193 1
				$m[2] = trim($m[2]);
194 1
				if (!empty($m[2])) {
195 1
					$descriptionLines[] = $m[2];
196 1
				}
197 1
			} else {
198 1
				$prepared[$index] = $m[2];
199
			}
200 1
		}
201
202 1
		$description = array();
203 1
		if (empty($descriptionLines) || strlen($descriptionLines[0]) < 5 || $descriptionLines[0][4] !== '+') {
204
			$description['SVWZ'] = implode('', $descriptionLines);
205
		} else {
206 1
			$lastType = null;
207 1
			foreach ($descriptionLines as $line) {
208 1
				if (strlen($line) > 5 && $line[4] === '+') {
209 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...
210 1
						$description[$lastType] = trim($description[$lastType]);
211 1
					}
212 1
					$lastType = substr($line, 0, 4);
213 1
					$description[$lastType] = substr($line, 5);
214 1
				} else {
215 1
					$description[$lastType] .= $line;
216
				}
217 1
				if (strlen($line) < 27) {
218
					// Usually, lines are 27 characters long. In case characters are missing, then it's either the end
219
					// of the current type or spaces have been trimmed from the end. We want to collapse multiple spaces
220
					// into one and we don't want to leave trailing spaces behind. So add a single space here to make up
221
					// for possibly missing spaces, and if it's the end of the type, it will be trimmed off later.
222 1
					$description[$lastType] .= ' ';
223 1
				}
224 1
			}
225 1
			$description[$lastType] = trim($description[$lastType]);
226
		}
227
228 1
		$result['description']       = $description;
229 1
		$result['booking_text']      = trim($prepared[0]);
230 1
		$result['primanoten_nr']     = trim($prepared[10]);
231 1
		$result['description_1']     = trim($description1);
232 1
		$result['bank_code']         = trim($prepared[30]);
233 1
		$result['account_number']    = trim($prepared[31]);
234 1
		$result['name']              = trim($prepared[32] . $prepared[33]);
235 1
		$result['text_key_addition'] = trim($prepared[34]);
236 1
		$result['description_2']     = trim($description2);
237 1
		return $result;
238
	}
239
240
	/**
241
	 * @param string $val
242
	 * @return string
243
	 */
244 1
	protected function getDate($val)
245
	{
246 1
		$val = '20' . $val;
247 1
		preg_match('/(\d{4})(\d{2})(\d{2})/', $val, $m);
248 1
		return $m[1] . '-' . $m[2] . '-' . $m[3];
249
	}
250
}
251