Total Complexity | 54 |
Total Lines | 570 |
Duplicated Lines | 0 % |
Changes | 1 | ||
Bugs | 0 | Features | 0 |
Complex classes like TransactionJournalFactory 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 TransactionJournalFactory, and based on these observations, apply Extract Interface, too.
1 | <?php |
||
55 | class TransactionJournalFactory |
||
56 | { |
||
57 | use JournalServiceTrait; |
||
|
|||
58 | |||
59 | /** @var AccountRepositoryInterface */ |
||
60 | private $accountRepository; |
||
61 | /** @var AccountValidator */ |
||
62 | private $accountValidator; |
||
63 | /** @var BillRepositoryInterface */ |
||
64 | private $billRepository; |
||
65 | /** @var CurrencyRepositoryInterface */ |
||
66 | private $currencyRepository; |
||
67 | /** @var bool */ |
||
68 | private $errorOnHash; |
||
69 | /** @var array */ |
||
70 | private $fields; |
||
71 | /** @var PiggyBankEventFactory */ |
||
72 | private $piggyEventFactory; |
||
73 | /** @var PiggyBankRepositoryInterface */ |
||
74 | private $piggyRepository; |
||
75 | /** @var TransactionFactory */ |
||
76 | private $transactionFactory; |
||
77 | /** @var TransactionTypeRepositoryInterface */ |
||
78 | private $typeRepository; |
||
79 | /** @var User The user */ |
||
80 | private $user; |
||
81 | |||
82 | /** |
||
83 | * Constructor. |
||
84 | * |
||
85 | * @throws Exception |
||
86 | * @codeCoverageIgnore |
||
87 | */ |
||
88 | public function __construct() |
||
89 | { |
||
90 | $this->errorOnHash = false; |
||
91 | $this->fields = [ |
||
92 | // sepa |
||
93 | 'sepa_cc', 'sepa_ct_op', 'sepa_ct_id', |
||
94 | 'sepa_db', 'sepa_country', 'sepa_ep', |
||
95 | 'sepa_ci', 'sepa_batch_id', |
||
96 | |||
97 | // dates |
||
98 | 'interest_date', 'book_date', 'process_date', |
||
99 | 'due_date', 'payment_date', 'invoice_date', |
||
100 | |||
101 | // others |
||
102 | 'recurrence_id', 'internal_reference', 'bunq_payment_id', |
||
103 | 'import_hash', 'import_hash_v2', 'external_id', 'original_source']; |
||
104 | |||
105 | |||
106 | if ('testing' === config('app.env')) { |
||
107 | Log::warning(sprintf('%s should not be instantiated in the TEST environment!', get_class($this))); |
||
108 | } |
||
109 | |||
110 | $this->currencyRepository = app(CurrencyRepositoryInterface::class); |
||
111 | $this->typeRepository = app(TransactionTypeRepositoryInterface::class); |
||
112 | $this->transactionFactory = app(TransactionFactory::class); |
||
113 | $this->billRepository = app(BillRepositoryInterface::class); |
||
114 | $this->budgetRepository = app(BudgetRepositoryInterface::class); |
||
115 | $this->categoryRepository = app(CategoryRepositoryInterface::class); |
||
116 | $this->piggyRepository = app(PiggyBankRepositoryInterface::class); |
||
117 | $this->piggyEventFactory = app(PiggyBankEventFactory::class); |
||
118 | $this->tagFactory = app(TagFactory::class); |
||
119 | $this->accountValidator = app(AccountValidator::class); |
||
120 | $this->accountRepository = app(AccountRepositoryInterface::class); |
||
121 | } |
||
122 | |||
123 | /** |
||
124 | * Store a new (set of) transaction journals. |
||
125 | * |
||
126 | * @param array $data |
||
127 | * |
||
128 | * @throws DuplicateTransactionException |
||
129 | * @throws FireflyException |
||
130 | * @return Collection |
||
131 | */ |
||
132 | public function create(array $data): Collection |
||
172 | } |
||
173 | |||
174 | /** |
||
175 | * @param bool $errorOnHash |
||
176 | */ |
||
177 | public function setErrorOnHash(bool $errorOnHash): void |
||
178 | { |
||
179 | $this->errorOnHash = $errorOnHash; |
||
180 | if (true === $errorOnHash) { |
||
181 | Log::info('Will trigger duplication alert for this journal.'); |
||
182 | } |
||
183 | } |
||
184 | |||
185 | /** |
||
186 | * Set the user. |
||
187 | * |
||
188 | * @param User $user |
||
189 | */ |
||
190 | public function setUser(User $user): void |
||
201 | } |
||
202 | |||
203 | /** |
||
204 | * @param TransactionJournal $journal |
||
205 | * @param NullArrayObject $data |
||
206 | * @param string $field |
||
207 | */ |
||
208 | protected function storeMeta(TransactionJournal $journal, NullArrayObject $data, string $field): void |
||
209 | { |
||
210 | $set = [ |
||
211 | 'journal' => $journal, |
||
212 | 'name' => $field, |
||
213 | 'data' => (string) ($data[$field] ?? ''), |
||
214 | ]; |
||
215 | |||
216 | Log::debug(sprintf('Going to store meta-field "%s", with value "%s".', $set['name'], $set['data'])); |
||
217 | |||
218 | /** @var TransactionJournalMetaFactory $factory */ |
||
219 | $factory = app(TransactionJournalMetaFactory::class); |
||
220 | $factory->updateOrCreate($set); |
||
221 | } |
||
222 | |||
223 | /** |
||
224 | * Set foreign currency to NULL if it's the same as the normal currency: |
||
225 | * |
||
226 | * @param TransactionCurrency $currency |
||
227 | * @param TransactionCurrency|null $foreignCurrency |
||
228 | * |
||
229 | * @return TransactionCurrency|null |
||
230 | */ |
||
231 | private function compareCurrencies(?TransactionCurrency $currency, ?TransactionCurrency $foreignCurrency): ?TransactionCurrency |
||
241 | } |
||
242 | |||
243 | /** |
||
244 | * @param NullArrayObject $row |
||
245 | * |
||
246 | * @throws FireflyException |
||
247 | * @throws DuplicateTransactionException |
||
248 | * @return TransactionJournal|null |
||
249 | */ |
||
250 | private function createJournal(NullArrayObject $row): ?TransactionJournal |
||
251 | { |
||
252 | $row['import_hash_v2'] = $this->hashArray($row); |
||
253 | |||
254 | $this->errorIfDuplicate($row['import_hash_v2']); |
||
255 | |||
256 | /** Some basic fields */ |
||
257 | $type = $this->typeRepository->findTransactionType(null, $row['type']); |
||
258 | $carbon = $row['date'] ?? new Carbon; |
||
259 | $order = $row['order'] ?? 0; |
||
260 | $currency = $this->currencyRepository->findCurrency((int) $row['currency_id'], $row['currency_code']); |
||
261 | $foreignCurrency = $this->currencyRepository->findCurrencyNull($row['foreign_currency_id'], $row['foreign_currency_code']); |
||
262 | $bill = $this->billRepository->findBill((int) $row['bill_id'], $row['bill_name']); |
||
263 | $billId = TransactionType::WITHDRAWAL === $type->type && null !== $bill ? $bill->id : null; |
||
264 | $description = app('steam')->cleanString((string) $row['description']); |
||
265 | |||
266 | /** Manipulate basic fields */ |
||
267 | $carbon->setTimezone(config('app.timezone')); |
||
268 | |||
269 | try { |
||
270 | // validate source and destination using a new Validator. |
||
271 | $this->validateAccounts($row); |
||
272 | } catch (FireflyException $e) { |
||
273 | Log::error('Could not validate source or destination.'); |
||
274 | Log::error($e->getMessage()); |
||
275 | |||
276 | return null; |
||
277 | } |
||
278 | |||
279 | // TODO typeOverrule: the account validator may have another opinion on the transaction type. |
||
280 | |||
281 | /** create or get source and destination accounts */ |
||
282 | $sourceInfo = [ |
||
283 | 'id' => (int) $row['source_id'], |
||
284 | 'name' => $row['source_name'], |
||
285 | 'iban' => $row['source_iban'], |
||
286 | 'number' => $row['source_number'], |
||
287 | 'bic' => $row['source_bic'], |
||
288 | 'currency_id' => $currency->id, |
||
289 | ]; |
||
290 | |||
291 | $destInfo = [ |
||
292 | 'id' => (int) $row['destination_id'], |
||
293 | 'name' => $row['destination_name'], |
||
294 | 'iban' => $row['destination_iban'], |
||
295 | 'number' => $row['destination_number'], |
||
296 | 'bic' => $row['destination_bic'], |
||
297 | 'currency_id' => $currency->id, |
||
298 | ]; |
||
299 | Log::debug('Source info:', $sourceInfo); |
||
300 | Log::debug('Destination info:', $destInfo); |
||
301 | Log::debug('Now calling getAccount for the source.'); |
||
302 | $sourceAccount = $this->getAccount($type->type, 'source', $sourceInfo); |
||
303 | Log::debug('Now calling getAccount for the destination.'); |
||
304 | $destinationAccount = $this->getAccount($type->type, 'destination', $destInfo); |
||
305 | Log::debug('Done with getAccount(2x)'); |
||
306 | $currency = $this->getCurrencyByAccount($type->type, $currency, $sourceAccount, $destinationAccount); |
||
307 | $foreignCurrency = $this->compareCurrencies($currency, $foreignCurrency); |
||
308 | $foreignCurrency = $this->getForeignByAccount($type->type, $foreignCurrency, $destinationAccount); |
||
309 | $description = $this->getDescription($description); |
||
310 | |||
311 | /** Create a basic journal. */ |
||
312 | $journal = TransactionJournal::create( |
||
313 | [ |
||
314 | 'user_id' => $this->user->id, |
||
315 | 'transaction_type_id' => $type->id, |
||
316 | 'bill_id' => $billId, |
||
317 | 'transaction_currency_id' => $currency->id, |
||
318 | 'description' => substr($description, 0, 1000), |
||
319 | 'date' => $carbon->format('Y-m-d H:i:s'), |
||
320 | 'order' => $order, |
||
321 | 'tag_count' => 0, |
||
322 | 'completed' => 0, |
||
323 | ] |
||
324 | ); |
||
325 | Log::debug(sprintf('Created new journal #%d: "%s"', $journal->id, $journal->description)); |
||
326 | |||
327 | /** Create two transactions. */ |
||
328 | /** @var TransactionFactory $transactionFactory */ |
||
329 | $transactionFactory = app(TransactionFactory::class); |
||
330 | $transactionFactory->setUser($this->user); |
||
331 | $transactionFactory->setJournal($journal); |
||
332 | $transactionFactory->setAccount($sourceAccount); |
||
333 | $transactionFactory->setCurrency($currency); |
||
334 | $transactionFactory->setForeignCurrency($foreignCurrency); |
||
335 | $transactionFactory->setReconciled($row['reconciled'] ?? false); |
||
336 | try { |
||
337 | $negative = $transactionFactory->createNegative((string) $row['amount'], (string) $row['foreign_amount']); |
||
338 | } catch (FireflyException $e) { |
||
339 | Log::error('Exception creating negative transaction.'); |
||
340 | Log::error($e->getMessage()); |
||
341 | Log::error($e->getTraceAsString()); |
||
342 | $this->forceDeleteOnError(new Collection([$journal])); |
||
343 | throw new FireflyException($e->getMessage()); |
||
344 | } |
||
345 | |||
346 | // and the destination one: |
||
347 | /** @var TransactionFactory $transactionFactory */ |
||
348 | $transactionFactory = app(TransactionFactory::class); |
||
349 | $transactionFactory->setUser($this->user); |
||
350 | $transactionFactory->setJournal($journal); |
||
351 | $transactionFactory->setAccount($destinationAccount); |
||
352 | $transactionFactory->setCurrency($currency); |
||
353 | $transactionFactory->setForeignCurrency($foreignCurrency); |
||
354 | $transactionFactory->setReconciled($row['reconciled'] ?? false); |
||
355 | try { |
||
356 | $transactionFactory->createPositive((string) $row['amount'], (string) $row['foreign_amount']); |
||
357 | } catch (FireflyException $e) { |
||
358 | Log::error('Exception creating positive transaction.'); |
||
359 | Log::error($e->getMessage()); |
||
360 | Log::error($e->getTraceAsString()); |
||
361 | Log::warning('Delete negative transaction.'); |
||
362 | $this->forceTrDelete($negative); |
||
363 | $this->forceDeleteOnError(new Collection([$journal])); |
||
364 | throw new FireflyException($e->getMessage()); |
||
365 | } |
||
366 | |||
367 | |||
368 | // verify that journal has two transactions. Otherwise, delete and cancel. |
||
369 | // TODO this can't be faked so it can't be tested. |
||
370 | // $count = $journal->transactions()->count(); |
||
371 | // if (2 !== $count) { |
||
372 | // // @codeCoverageIgnoreStart |
||
373 | // Log::error(sprintf('The journal unexpectedly has %d transaction(s). This is not OK. Cancel operation.', $count)); |
||
374 | // try { |
||
375 | // $journal->delete(); |
||
376 | // } catch (Exception $e) { |
||
377 | // Log::debug(sprintf('Dont care: %s.', $e->getMessage())); |
||
378 | // } |
||
379 | // |
||
380 | // return null; |
||
381 | // // @codeCoverageIgnoreEnd |
||
382 | // } |
||
383 | $journal->completed = true; |
||
384 | $journal->save(); |
||
385 | |||
386 | /** Link all other data to the journal. */ |
||
387 | |||
388 | /** Link budget */ |
||
389 | $this->storeBudget($journal, $row); |
||
390 | |||
391 | /** Link category */ |
||
392 | $this->storeCategory($journal, $row); |
||
393 | |||
394 | /** Set notes */ |
||
395 | $this->storeNotes($journal, $row['notes']); |
||
396 | |||
397 | /** Set piggy bank */ |
||
398 | $this->storePiggyEvent($journal, $row); |
||
399 | |||
400 | /** Set tags */ |
||
401 | $this->storeTags($journal, $row['tags']); |
||
402 | |||
403 | /** set all meta fields */ |
||
404 | $this->storeMetaFields($journal, $row); |
||
405 | |||
406 | return $journal; |
||
407 | } |
||
408 | |||
409 | /** |
||
410 | * If this transaction already exists, throw an error. |
||
411 | * |
||
412 | * @param string $hash |
||
413 | * |
||
414 | * @throws DuplicateTransactionException |
||
415 | */ |
||
416 | private function errorIfDuplicate(string $hash): void |
||
433 | } |
||
434 | } |
||
435 | |||
436 | /** |
||
437 | * Force the deletion of an entire set of transaction journals and their meta object in case of |
||
438 | * an error creating a group. |
||
439 | * |
||
440 | * @param Collection $collection |
||
441 | */ |
||
442 | private function forceDeleteOnError(Collection $collection): void |
||
443 | { |
||
444 | Log::debug(sprintf('forceDeleteOnError on collection size %d item(s)', $collection->count())); |
||
445 | $service = app(JournalDestroyService::class); |
||
446 | /** @var TransactionJournal $journal */ |
||
447 | foreach ($collection as $journal) { |
||
448 | Log::debug(sprintf('forceDeleteOnError on journal #%d', $journal->id)); |
||
449 | $service->destroy($journal); |
||
450 | } |
||
451 | } |
||
452 | |||
453 | /** |
||
454 | * @param Transaction $transaction |
||
455 | */ |
||
456 | private function forceTrDelete(Transaction $transaction): void |
||
457 | { |
||
458 | try { |
||
459 | $transaction->delete(); |
||
460 | } catch (Exception $e) { |
||
461 | Log::error($e->getMessage()); |
||
462 | Log::error($e->getTraceAsString()); |
||
463 | Log::error('Could not delete negative transaction.'); |
||
464 | } |
||
465 | } |
||
466 | |||
467 | /** |
||
468 | * @param TransactionCurrency|null $currency |
||
469 | * @param Account $account |
||
470 | * |
||
471 | * @return TransactionCurrency |
||
472 | */ |
||
473 | private function getCurrency(?TransactionCurrency $currency, Account $account): TransactionCurrency |
||
474 | { |
||
475 | Log::debug('Now in getCurrency()'); |
||
476 | $preference = $this->accountRepository->getAccountCurrency($account); |
||
477 | if (null === $preference && null === $currency) { |
||
478 | // return user's default: |
||
479 | return app('amount')->getDefaultCurrencyByUser($this->user); |
||
480 | } |
||
481 | $result = ($preference ?? $currency) ?? app('amount')->getSystemCurrency(); |
||
482 | Log::debug(sprintf('Currency is now #%d (%s) because of account #%d (%s)', $result->id, $result->code, $account->id, $account->name)); |
||
483 | |||
484 | return $result; |
||
485 | } |
||
486 | |||
487 | /** |
||
488 | * @param string $type |
||
489 | * @param TransactionCurrency|null $currency |
||
490 | * @param Account $source |
||
491 | * @param Account $destination |
||
492 | * |
||
493 | * @return TransactionCurrency |
||
494 | */ |
||
495 | private function getCurrencyByAccount(string $type, ?TransactionCurrency $currency, Account $source, Account $destination): TransactionCurrency |
||
496 | { |
||
497 | Log::debug('Now ingetCurrencyByAccount()'); |
||
498 | switch ($type) { |
||
499 | default: |
||
500 | case TransactionType::WITHDRAWAL: |
||
501 | case TransactionType::TRANSFER: |
||
502 | return $this->getCurrency($currency, $source); |
||
503 | case TransactionType::DEPOSIT: |
||
504 | return $this->getCurrency($currency, $destination); |
||
505 | |||
506 | } |
||
507 | } |
||
508 | |||
509 | /** |
||
510 | * @param string $description |
||
511 | * |
||
512 | * @return string |
||
513 | */ |
||
514 | private function getDescription(string $description): string |
||
515 | { |
||
516 | $description = '' === $description ? '(empty description)' : $description; |
||
517 | |||
518 | return substr($description, 0, 255); |
||
519 | } |
||
520 | |||
521 | /** |
||
522 | * @param string $type |
||
523 | * @param TransactionCurrency|null $foreignCurrency |
||
524 | * @param Account $destination |
||
525 | * |
||
526 | * @return TransactionCurrency|null |
||
527 | */ |
||
528 | private function getForeignByAccount(string $type, ?TransactionCurrency $foreignCurrency, Account $destination): ?TransactionCurrency |
||
529 | { |
||
530 | if (TransactionType::TRANSFER === $type) { |
||
531 | return $this->getCurrency($foreignCurrency, $destination); |
||
532 | } |
||
533 | |||
534 | return $foreignCurrency; |
||
535 | } |
||
536 | |||
537 | /** |
||
538 | * @param NullArrayObject $row |
||
539 | * |
||
540 | * @return string |
||
541 | */ |
||
542 | private function hashArray(NullArrayObject $row): string |
||
558 | } |
||
559 | |||
560 | /** |
||
561 | * @param TransactionJournal $journal |
||
562 | * @param NullArrayObject $transaction |
||
563 | */ |
||
564 | private function storeMetaFields(TransactionJournal $journal, NullArrayObject $transaction): void |
||
568 | } |
||
569 | } |
||
570 | |||
571 | /** |
||
572 | * Link a piggy bank to this journal. |
||
573 | * |
||
574 | * @param TransactionJournal $journal |
||
575 | * @param NullArrayObject $data |
||
576 | */ |
||
577 | private function storePiggyEvent(TransactionJournal $journal, NullArrayObject $data): void |
||
578 | { |
||
579 | Log::debug('Will now store piggy event.'); |
||
580 | if (!$journal->isTransfer()) { |
||
581 | Log::debug('Journal is not a transfer, do nothing.'); |
||
582 | |||
583 | return; |
||
584 | } |
||
585 | |||
586 | $piggyBank = $this->piggyRepository->findPiggyBank((int) $data['piggy_bank_id'], $data['piggy_bank_name']); |
||
587 | |||
588 | if (null !== $piggyBank) { |
||
589 | $this->piggyEventFactory->create($journal, $piggyBank); |
||
590 | Log::debug('Create piggy event.'); |
||
591 | |||
592 | return; |
||
593 | } |
||
594 | Log::debug('Create no piggy event'); |
||
595 | } |
||
596 | |||
597 | /** |
||
598 | * @param NullArrayObject $data |
||
599 | * |
||
600 | * @throws FireflyException |
||
601 | */ |
||
602 | private function validateAccounts(NullArrayObject $data): void |
||
625 | } |
||
626 | } |
||
627 | |||
628 | |||
629 | } |
||
630 |