Total Complexity | 56 |
Total Lines | 572 |
Duplicated Lines | 0 % |
Changes | 1 | ||
Bugs | 0 | Features | 0 |
Complex classes like ImportArrayStorage 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.
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 ImportArrayStorage, and based on these observations, apply Extract Interface, too.
1 | <?php |
||
56 | class ImportArrayStorage |
||
57 | { |
||
58 | /** @var int Number of hits required for a transfer to match. */ |
||
59 | private const REQUIRED_HITS = 4; |
||
60 | /** @var bool Check for transfers during import. */ |
||
61 | private $checkForTransfers = false; |
||
62 | /** @var TransactionGroupRepositoryInterface */ |
||
63 | private $groupRepos; |
||
64 | /** @var ImportJob The import job */ |
||
65 | private $importJob; |
||
66 | /** @var JournalRepositoryInterface Journal repository for storage. */ |
||
67 | private $journalRepos; |
||
68 | /** @var string */ |
||
69 | private $language = 'en_US'; |
||
70 | /** @var ImportJobRepositoryInterface Import job repository */ |
||
71 | private $repository; |
||
72 | /** @var array The transfers the user already has. */ |
||
73 | private $transfers; |
||
74 | |||
75 | /** |
||
76 | * Set job, count transfers in the array and create the repository. |
||
77 | * |
||
78 | * @param ImportJob $importJob |
||
79 | */ |
||
80 | public function setImportJob(ImportJob $importJob): void |
||
100 | } |
||
101 | |||
102 | /** |
||
103 | * Actually does the storing. Does three things. |
||
104 | * - Store journals |
||
105 | * - Link to tag |
||
106 | * - Run rules (if set to) |
||
107 | * |
||
108 | * @throws FireflyException |
||
109 | * @return Collection |
||
110 | */ |
||
111 | public function store(): Collection |
||
112 | { |
||
113 | // store transactions |
||
114 | $this->setStatus('storing_data'); |
||
115 | $collection = $this->storeGroupArray(); |
||
116 | $this->setStatus('stored_data'); |
||
117 | |||
118 | // link tag: |
||
119 | $this->setStatus('linking_to_tag'); |
||
120 | $this->linkToTag($collection); |
||
121 | $this->setStatus('linked_to_tag'); |
||
122 | |||
123 | // run rules, if configured to. |
||
124 | $config = $this->importJob->configuration; |
||
125 | if (isset($config['apply-rules']) && true === $config['apply-rules']) { |
||
126 | $this->setStatus('applying_rules'); |
||
127 | $this->applyRules($collection); |
||
128 | $this->setStatus('rules_applied'); |
||
129 | } |
||
130 | |||
131 | app('preferences')->mark(); |
||
132 | |||
133 | // email about this: |
||
134 | event(new RequestedReportOnJournals((int) $this->importJob->user_id, $collection)); |
||
135 | |||
136 | return $collection; |
||
137 | } |
||
138 | |||
139 | /** |
||
140 | * Applies the users rules to the created journals. |
||
141 | * |
||
142 | * @param Collection $collection |
||
143 | * |
||
144 | */ |
||
145 | private function applyRules(Collection $collection): void |
||
146 | { |
||
147 | Log::debug('Now in applyRules()'); |
||
148 | |||
149 | /** @var RuleEngine $ruleEngine */ |
||
150 | $ruleEngine = app(RuleEngine::class); |
||
151 | $ruleEngine->setUser($this->importJob->user); |
||
152 | $ruleEngine->setAllRules(true); |
||
153 | |||
154 | // for this call, the rule engine only includes "store" rules: |
||
155 | $ruleEngine->setTriggerMode(RuleEngine::TRIGGER_STORE); |
||
156 | Log::debug('Start of engine loop'); |
||
157 | foreach ($collection as $group) { |
||
158 | $this->applyRulesGroup($ruleEngine, $group); |
||
159 | } |
||
160 | Log::debug('End of engine loop.'); |
||
161 | } |
||
162 | |||
163 | /** |
||
164 | * @param RuleEngine $ruleEngine |
||
165 | * @param TransactionGroup $group |
||
166 | */ |
||
167 | private function applyRulesGroup(RuleEngine $ruleEngine, TransactionGroup $group): void |
||
168 | { |
||
169 | Log::debug(sprintf('Processing group #%d', $group->id)); |
||
170 | foreach ($group->transactionJournals as $journal) { |
||
171 | Log::debug(sprintf('Processing journal #%d from group #%d', $journal->id, $group->id)); |
||
172 | $ruleEngine->processTransactionJournal($journal); |
||
173 | } |
||
174 | } |
||
175 | |||
176 | /** |
||
177 | * Count the number of transfers in the array. If this is zero, don't bother checking for double transfers. |
||
178 | */ |
||
179 | private function countTransfers(): void |
||
180 | { |
||
181 | Log::debug('Now in countTransfers()'); |
||
182 | /** @var array $array */ |
||
183 | $array = $this->repository->getTransactions($this->importJob); |
||
184 | |||
185 | |||
186 | $count = 0; |
||
187 | foreach ($array as $index => $group) { |
||
188 | |||
189 | foreach ($group['transactions'] as $transaction) { |
||
190 | if (strtolower(TransactionType::TRANSFER) === strtolower($transaction['type'])) { |
||
191 | $count++; |
||
192 | Log::debug(sprintf('Row #%d is a transfer, increase count to %d', $index + 1, $count)); |
||
193 | } |
||
194 | } |
||
195 | } |
||
196 | Log::debug(sprintf('Count of transfers in import array is %d.', $count)); |
||
197 | if ($count > 0) { |
||
198 | $this->checkForTransfers = true; |
||
199 | Log::debug('Will check for duplicate transfers.'); |
||
200 | // get users transfers. Needed for comparison. |
||
201 | $this->getTransfers(); |
||
202 | } |
||
203 | } |
||
204 | |||
205 | /** |
||
206 | * @param int $index |
||
207 | * @param array $group |
||
208 | * |
||
209 | * @return bool |
||
210 | */ |
||
211 | private function duplicateDetected(int $index, array $group): bool |
||
212 | { |
||
213 | Log::debug(sprintf('Now in duplicateDetected(%d)', $index)); |
||
214 | $transactions = $group['transactions'] ?? []; |
||
215 | foreach ($transactions as $transaction) { |
||
216 | $hash = $this->getHash($transaction); |
||
217 | $existingId = $this->hashExists($hash); |
||
218 | if (null !== $existingId) { |
||
219 | $message = (string) trans('import.duplicate_row', ['row' => $index, 'description' => $transaction['description']]); |
||
220 | $this->logDuplicateObject($transaction, $existingId); |
||
221 | $this->repository->addErrorMessage($this->importJob, $message); |
||
222 | |||
223 | return true; |
||
224 | } |
||
225 | |||
226 | // do transfer detection: |
||
227 | if ($this->checkForTransfers && $this->transferExists($transaction)) { |
||
228 | $message = (string) trans('import.duplicate_row', ['row' => $index, 'description' => $transaction['description']]); |
||
229 | $this->logDuplicateTransfer($transaction); |
||
230 | $this->repository->addErrorMessage($this->importJob, $message); |
||
231 | |||
232 | return true; |
||
233 | } |
||
234 | } |
||
235 | |||
236 | return false; |
||
237 | } |
||
238 | |||
239 | /** |
||
240 | * Get hash of transaction. |
||
241 | * |
||
242 | * @param array $transaction |
||
243 | * |
||
244 | * @return string |
||
245 | */ |
||
246 | private function getHash(array $transaction): string |
||
247 | { |
||
248 | unset($transaction['import_hash_v2'], $transaction['original_source']); |
||
249 | $json = json_encode($transaction, JSON_THROW_ON_ERROR); |
||
250 | if (false === $json) { |
||
251 | // @codeCoverageIgnoreStart |
||
252 | /** @noinspection ForgottenDebugOutputInspection */ |
||
253 | Log::error('Could not encode import array.', $transaction); |
||
254 | try { |
||
255 | $json = random_int(1, 10000); |
||
256 | } catch (Exception $e) { |
||
257 | // seriously? |
||
258 | Log::error(sprintf('random_int() just failed. I want a medal: %s', $e->getMessage())); |
||
259 | } |
||
260 | // @codeCoverageIgnoreEnd |
||
261 | } |
||
262 | |||
263 | $hash = hash('sha256', $json); |
||
264 | Log::debug(sprintf('The hash is: %s', $hash), $transaction); |
||
265 | |||
266 | return $hash; |
||
267 | } |
||
268 | |||
269 | /** |
||
270 | * @param TransactionGroup $transactionGroup |
||
271 | * |
||
272 | * @return array |
||
273 | */ |
||
274 | private function getTransactionFromJournal(TransactionGroup $transactionGroup): array |
||
275 | { |
||
276 | // collect transactions using the journal collector |
||
277 | /** @var GroupCollectorInterface $collector */ |
||
278 | $collector = app(GroupCollectorInterface::class); |
||
279 | |||
280 | $collector->setUser($this->importJob->user); |
||
281 | $collector->setGroup($transactionGroup); |
||
282 | |||
283 | return $collector->getExtractedJournals(); |
||
284 | } |
||
285 | |||
286 | /** |
||
287 | * Get the users transfers, so they can be compared to whatever the user is trying to import. |
||
288 | */ |
||
289 | private function getTransfers(): void |
||
290 | { |
||
291 | Log::debug('Now in getTransfers()'); |
||
292 | app('preferences')->mark(); |
||
293 | |||
294 | /** @var GroupCollectorInterface $collector */ |
||
295 | $collector = app(GroupCollectorInterface::class); |
||
296 | |||
297 | $collector->setUser($this->importJob->user); |
||
298 | $collector |
||
299 | ->setTypes([TransactionType::TRANSFER])->setLimit(10000)->setPage(1) |
||
300 | ->withAccountInformation(); |
||
301 | $this->transfers = $collector->getExtractedJournals(); |
||
302 | Log::debug(sprintf('Count of getTransfers() is %d', count($this->transfers))); |
||
303 | } |
||
304 | |||
305 | /** |
||
306 | * Check if the hash exists for the array the user wants to import. |
||
307 | * |
||
308 | * @param string $hash |
||
309 | * |
||
310 | * @return int|null |
||
311 | */ |
||
312 | private function hashExists(string $hash): ?int |
||
313 | { |
||
314 | $entry = $this->journalRepos->findByHash($hash); |
||
315 | if (null === $entry) { |
||
316 | Log::debug(sprintf('Found no transactions with hash %s.', $hash)); |
||
317 | |||
318 | return null; |
||
319 | } |
||
320 | Log::info(sprintf('Found a transaction journal with an existing hash: %s', $hash)); |
||
321 | |||
322 | return (int) $entry->transaction_journal_id; |
||
323 | } |
||
324 | |||
325 | /** |
||
326 | * Link all imported journals to a tag. |
||
327 | * |
||
328 | * @param Collection $collection |
||
329 | */ |
||
330 | private function linkToTag(Collection $collection): void |
||
373 | |||
374 | } |
||
375 | |||
376 | /** |
||
377 | * Log about a duplicate object (double hash). |
||
378 | * |
||
379 | * @param array $transaction |
||
380 | * @param int $existingId |
||
381 | */ |
||
382 | private function logDuplicateObject(array $transaction, int $existingId): void |
||
383 | { |
||
384 | Log::info( |
||
385 | 'Transaction is a duplicate, and will not be imported (the hash exists).', |
||
386 | [ |
||
387 | 'existing' => $existingId, |
||
388 | 'description' => $transaction['description'] ?? '', |
||
389 | 'amount' => $transaction['transactions'][0]['amount'] ?? 0, |
||
390 | 'date' => $transaction['date'] ?? '', |
||
391 | ] |
||
392 | ); |
||
393 | |||
394 | } |
||
395 | |||
396 | /** |
||
397 | * Log about a duplicate transfer. |
||
398 | * |
||
399 | * @param array $transaction |
||
400 | */ |
||
401 | private function logDuplicateTransfer(array $transaction): void |
||
402 | { |
||
403 | Log::info( |
||
404 | 'Transaction is a duplicate transfer, and will not be imported (such a transfer exists already).', |
||
405 | [ |
||
406 | 'description' => $transaction['description'] ?? '', |
||
407 | 'amount' => $transaction['transactions'][0]['amount'] ?? 0, |
||
408 | 'date' => $transaction['date'] ?? '', |
||
409 | ] |
||
410 | ); |
||
411 | } |
||
412 | |||
413 | /** |
||
414 | * Shorthand method to quickly set job status |
||
415 | * |
||
416 | * @param string $status |
||
417 | */ |
||
418 | private function setStatus(string $status): void |
||
421 | } |
||
422 | |||
423 | /** |
||
424 | * @param int $index |
||
425 | * @param array $group |
||
426 | * |
||
427 | * @return TransactionGroup|null |
||
428 | */ |
||
429 | private function storeGroup(int $index, array $group): ?TransactionGroup |
||
471 | } |
||
472 | |||
473 | /** |
||
474 | * Store array as journals. |
||
475 | * |
||
476 | * @throws FireflyException |
||
477 | * |
||
478 | * @return Collection |
||
479 | */ |
||
480 | private function storeGroupArray(): Collection |
||
500 | } |
||
501 | |||
502 | /** |
||
503 | * Check if a transfer exists. |
||
504 | * |
||
505 | * @param array $transaction |
||
506 | * |
||
507 | * @return bool |
||
508 | * |
||
509 | */ |
||
510 | private function transferExists(array $transaction): bool |
||
628 | } |
||
629 | |||
630 | } |
||
631 |