Various code cleanup.

This commit is contained in:
James Cole
2023-12-22 20:12:38 +01:00
parent 067d160c13
commit 581e5d7330
69 changed files with 361 additions and 317 deletions

View File

@@ -44,8 +44,7 @@ EXIT_CODE=$?
cd $SCRIPT_DIR/.. cd $SCRIPT_DIR/..
echo "Exit code is $EXIT_CODE, but we ignore this for the time being." echo "Exit code is $EXIT_CODE."
# for the time being, exit 0 # for the time being, exit 0
#exit $EXIT_CODE exit $EXIT_CODE
exit 0

View File

@@ -37,14 +37,14 @@
<rule ref="rulesets/design.xml/NumberOfChildren"> <rule ref="rulesets/design.xml/NumberOfChildren">
<properties> <properties>
<!-- TODO we want to be at minimum 15. But we start high, and drop the bar slowly. --> <!-- This is now at 32, which excludes the controllers but should prevent more monoliths. -->
<property name="minimum" value="256"/> <property name="minimum" value="32"/>
</properties> </properties>
</rule> </rule>
<rule ref="rulesets/design.xml/CouplingBetweenObjects"> <rule ref="rulesets/design.xml/CouplingBetweenObjects">
<properties> <properties>
<!-- TODO we want to be at maximum 13. But we start high, and drop the bar slowly. --> <!-- Leaving this at 28 excuses most current code but it can't get worse than that. -->
<property name="maximum" value="256"/> <property name="maximum" value="28"/>
</properties> </properties>
</rule> </rule>
@@ -58,14 +58,15 @@
<!-- code size --> <!-- code size -->
<rule ref="rulesets/codesize.xml/CyclomaticComplexity"> <rule ref="rulesets/codesize.xml/CyclomaticComplexity">
<properties> <properties>
<!-- TODO we want to be at report level 5. But we start high, and drop the bar slowly. --> <!-- Leave at 20. This means methods will be pretty complex before the system starts complaining. -->
<property name="reportLevel" value="500"/> <property name="reportLevel" value="20"/>
</properties> </properties>
</rule> </rule>
<rule ref="rulesets/codesize.xml/NPathComplexity"> <rule ref="rulesets/codesize.xml/NPathComplexity">
<properties> <properties>
<!-- TODO we want to be at a value of 128. But we start high, and drop the bar slowly. --> <!-- 2000 results in some pretty complex methods, but it's OK. -->
<property name="minimum" value="24062500"/> <!-- They should not be much more complex than that though -->
<property name="minimum" value="2000"/>
</properties> </properties>
</rule> </rule>
<rule ref="rulesets/codesize.xml/ExcessiveMethodLength"> <rule ref="rulesets/codesize.xml/ExcessiveMethodLength">

View File

@@ -40,6 +40,9 @@ use Symfony\Component\HttpFoundation\ParameterBag;
/** /**
* Class Controller. * Class Controller.
*
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
* @SuppressWarnings(PHPMD.NumberOfChildren)
*/ */
abstract class Controller extends BaseController abstract class Controller extends BaseController
{ {

View File

@@ -71,7 +71,7 @@ class ShowController extends Controller
* Display a listing of the resource. * Display a listing of the resource.
* *
* @throws FireflyException * @throws FireflyException
* */ */
public function index(): JsonResponse public function index(): JsonResponse
{ {
$pageSize = $this->parameters->get('limit'); $pageSize = $this->parameters->get('limit');
@@ -101,7 +101,7 @@ class ShowController extends Controller
* Show a currency. * Show a currency.
* *
* @throws FireflyException * @throws FireflyException
* */ */
public function show(TransactionCurrency $currency): JsonResponse public function show(TransactionCurrency $currency): JsonResponse
{ {
/** @var User $user */ /** @var User $user */
@@ -129,7 +129,7 @@ class ShowController extends Controller
* Show a currency. * Show a currency.
* *
* @throws FireflyException * @throws FireflyException
* */ */
public function showDefault(): JsonResponse public function showDefault(): JsonResponse
{ {
/** @var User $user */ /** @var User $user */

View File

@@ -68,7 +68,7 @@ class StoreController extends Controller
* Store new currency. * Store new currency.
* *
* @throws FireflyException * @throws FireflyException
* */ */
public function store(StoreRequest $request): JsonResponse public function store(StoreRequest $request): JsonResponse
{ {
$currency = $this->repository->store($request->getAll()); $currency = $this->repository->store($request->getAll());

View File

@@ -69,7 +69,7 @@ class UpdateController extends Controller
* Disable a currency. * Disable a currency.
* *
* @throws FireflyException * @throws FireflyException
* */ */
public function disable(TransactionCurrency $currency): JsonResponse public function disable(TransactionCurrency $currency): JsonResponse
{ {
// must be unused. // must be unused.
@@ -133,7 +133,7 @@ class UpdateController extends Controller
* Enable a currency. * Enable a currency.
* *
* @throws FireflyException * @throws FireflyException
* */ */
public function enable(TransactionCurrency $currency): JsonResponse public function enable(TransactionCurrency $currency): JsonResponse
{ {
$this->repository->enable($currency); $this->repository->enable($currency);
@@ -160,7 +160,7 @@ class UpdateController extends Controller
* Update a currency. * Update a currency.
* *
* @throws FireflyException * @throws FireflyException
* */ */
public function update(UpdateRequest $request, TransactionCurrency $currency): JsonResponse public function update(UpdateRequest $request, TransactionCurrency $currency): JsonResponse
{ {
$data = $request->getAll(); $data = $request->getAll();

View File

@@ -45,6 +45,9 @@ use Symfony\Component\HttpFoundation\ParameterBag;
/** /**
* Class Controller * Class Controller
*
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
* @SuppressWarnings(PHPMD.NumberOfChildren)
*/ */
class Controller extends BaseController class Controller extends BaseController
{ {
@@ -104,6 +107,8 @@ class Controller extends BaseController
/** /**
* TODO duplicate from V1 controller * TODO duplicate from V1 controller
* Method to grab all parameters from the URL. * Method to grab all parameters from the URL.
*
* @SuppressWarnings(PHPMD.NPathComplexity)
*/ */
private function getParameters(): ParameterBag private function getParameters(): ParameterBag
{ {

View File

@@ -45,6 +45,8 @@ class GracefulNotFoundHandler extends ExceptionHandler
* @param Request $request * @param Request $request
* *
* @throws \Throwable * @throws \Throwable
*
* @SuppressWarnings(PHPMD.CyclomaticComplexity)
*/ */
public function render($request, \Throwable $e): Response public function render($request, \Throwable $e): Response
{ {

View File

@@ -65,11 +65,15 @@ class Handler extends ExceptionHandler
]; ];
/** /**
* Render an exception into an HTTP response. * Render an exception into an HTTP response. It's complex but lucky for us, we never use it because
* Firefly III never crashes.
* *
* @param Request $request * @param Request $request
* *
* @throws \Throwable * @throws \Throwable
*
* @SuppressWarnings(PHPMD.NPathComplexity)
* @SuppressWarnings(PHPMD.CyclomaticComplexity)
*/ */
public function render($request, \Throwable $e): Response public function render($request, \Throwable $e): Response
{ {
@@ -124,7 +128,7 @@ class Handler extends ExceptionHandler
$errorCode = 500; $errorCode = 500;
$errorCode = $e instanceof MethodNotAllowedHttpException ? 405 : $errorCode; $errorCode = $e instanceof MethodNotAllowedHttpException ? 405 : $errorCode;
$isDebug = (bool)config('app.debug', false); $isDebug = (bool) config('app.debug', false);
if ($isDebug) { if ($isDebug) {
app('log')->debug(sprintf('Return JSON %s with debug.', get_class($e))); app('log')->debug(sprintf('Return JSON %s with debug.', get_class($e)));
@@ -181,7 +185,7 @@ class Handler extends ExceptionHandler
*/ */
public function report(\Throwable $e): void public function report(\Throwable $e): void
{ {
$doMailError = (bool)config('firefly.send_error_message'); $doMailError = (bool) config('firefly.send_error_message');
if ($this->shouldntReportLocal($e) || !$doMailError) { if ($this->shouldntReportLocal($e) || !$doMailError) {
parent::report($e); parent::report($e);
@@ -216,7 +220,7 @@ class Handler extends ExceptionHandler
// create job that will mail. // create job that will mail.
$ipAddress = request()->ip() ?? '0.0.0.0'; $ipAddress = request()->ip() ?? '0.0.0.0';
$job = new MailError($userData, (string)config('firefly.site_owner'), $ipAddress, $data); $job = new MailError($userData, (string) config('firefly.site_owner'), $ipAddress, $data);
dispatch($job); dispatch($job);
parent::report($e); parent::report($e);

View File

@@ -68,7 +68,7 @@ class AccountFactory
/** /**
* @throws FireflyException * @throws FireflyException
* */ */
public function findOrCreate(string $accountName, string $accountType): Account public function findOrCreate(string $accountName, string $accountType): Account
{ {
app('log')->debug(sprintf('findOrCreate("%s", "%s")', $accountName, $accountType)); app('log')->debug(sprintf('findOrCreate("%s", "%s")', $accountName, $accountType));
@@ -100,7 +100,7 @@ class AccountFactory
/** /**
* @throws FireflyException * @throws FireflyException
* */ */
public function create(array $data): Account public function create(array $data): Account
{ {
app('log')->debug('Now in AccountFactory::create()'); app('log')->debug('Now in AccountFactory::create()');
@@ -171,7 +171,7 @@ class AccountFactory
/** /**
* @throws FireflyException * @throws FireflyException
* */ */
private function createAccount(AccountType $type, array $data): Account private function createAccount(AccountType $type, array $data): Account
{ {
$this->accountRepository->resetAccountOrder(); $this->accountRepository->resetAccountOrder();
@@ -239,7 +239,7 @@ class AccountFactory
/** /**
* @throws FireflyException * @throws FireflyException
* */ */
private function cleanMetaDataArray(Account $account, array $data): array private function cleanMetaDataArray(Account $account, array $data): array
{ {
$currencyId = array_key_exists('currency_id', $data) ? (int)$data['currency_id'] : 0; $currencyId = array_key_exists('currency_id', $data) ? (int)$data['currency_id'] : 0;

View File

@@ -43,7 +43,7 @@ class BillFactory
/** /**
* @throws FireflyException * @throws FireflyException
* */ */
public function create(array $data): ?Bill public function create(array $data): ?Bill
{ {
app('log')->debug(sprintf('Now in %s', __METHOD__), $data); app('log')->debug(sprintf('Now in %s', __METHOD__), $data);

View File

@@ -52,7 +52,9 @@ class RecurrenceFactory
/** /**
* @throws FireflyException * @throws FireflyException
* */ *
* @SuppressWarnings(PHPMD.NPathComplexity)
*/
public function create(array $data): Recurrence public function create(array $data): Recurrence
{ {
try { try {
@@ -77,7 +79,7 @@ class RecurrenceFactory
$firstDate = $data['recurrence']['first_date']; $firstDate = $data['recurrence']['first_date'];
} }
if (array_key_exists('nr_of_repetitions', $data['recurrence'])) { if (array_key_exists('nr_of_repetitions', $data['recurrence'])) {
$repetitions = (int)$data['recurrence']['nr_of_repetitions']; $repetitions = (int) $data['recurrence']['nr_of_repetitions'];
} }
if (array_key_exists('repeat_until', $data['recurrence'])) { if (array_key_exists('repeat_until', $data['recurrence'])) {
$repeatUntil = $data['recurrence']['repeat_until']; $repeatUntil = $data['recurrence']['repeat_until'];
@@ -114,7 +116,7 @@ class RecurrenceFactory
$recurrence->save(); $recurrence->save();
if (array_key_exists('notes', $data['recurrence'])) { if (array_key_exists('notes', $data['recurrence'])) {
$this->updateNote($recurrence, (string)$data['recurrence']['notes']); $this->updateNote($recurrence, (string) $data['recurrence']['notes']);
} }
$this->createRepetitions($recurrence, $data['repetitions'] ?? []); $this->createRepetitions($recurrence, $data['repetitions'] ?? []);

View File

@@ -49,7 +49,7 @@ class TransactionGroupFactory
* *
* @throws DuplicateTransactionException * @throws DuplicateTransactionException
* @throws FireflyException * @throws FireflyException
* */ */
public function create(array $data): TransactionGroup public function create(array $data): TransactionGroup
{ {
app('log')->debug('Now in TransactionGroupFactory::create()'); app('log')->debug('Now in TransactionGroupFactory::create()');

View File

@@ -91,7 +91,7 @@ class TransactionJournalFactory
* *
* @throws DuplicateTransactionException * @throws DuplicateTransactionException
* @throws FireflyException * @throws FireflyException
* */ */
public function create(array $data): Collection public function create(array $data): Collection
{ {
app('log')->debug('Now in TransactionJournalFactory::create()'); app('log')->debug('Now in TransactionJournalFactory::create()');
@@ -344,7 +344,7 @@ class TransactionJournalFactory
* If this transaction already exists, throw an error. * If this transaction already exists, throw an error.
* *
* @throws DuplicateTransactionException * @throws DuplicateTransactionException
* */ */
private function errorIfDuplicate(string $hash): void private function errorIfDuplicate(string $hash): void
{ {
app('log')->debug(sprintf('In errorIfDuplicate(%s)', $hash)); app('log')->debug(sprintf('In errorIfDuplicate(%s)', $hash));
@@ -442,7 +442,7 @@ class TransactionJournalFactory
/** /**
* @throws FireflyException * @throws FireflyException
* */ */
private function getCurrencyByAccount(string $type, ?TransactionCurrency $currency, Account $source, Account $destination): TransactionCurrency private function getCurrencyByAccount(string $type, ?TransactionCurrency $currency, Account $source, Account $destination): TransactionCurrency
{ {
app('log')->debug('Now in getCurrencyByAccount()'); app('log')->debug('Now in getCurrencyByAccount()');
@@ -455,7 +455,7 @@ class TransactionJournalFactory
/** /**
* @throws FireflyException * @throws FireflyException
* */ */
private function getCurrency(?TransactionCurrency $currency, Account $account): TransactionCurrency private function getCurrency(?TransactionCurrency $currency, Account $account): TransactionCurrency
{ {
app('log')->debug('Now in getCurrency()'); app('log')->debug('Now in getCurrency()');
@@ -489,7 +489,7 @@ class TransactionJournalFactory
/** /**
* @throws FireflyException * @throws FireflyException
* */ */
private function getForeignByAccount(string $type, ?TransactionCurrency $foreignCurrency, Account $destination): ?TransactionCurrency private function getForeignByAccount(string $type, ?TransactionCurrency $foreignCurrency, Account $destination): ?TransactionCurrency
{ {
if (TransactionType::TRANSFER === $type) { if (TransactionType::TRANSFER === $type) {

View File

@@ -45,7 +45,7 @@ class MonthReportGenerator implements ReportGeneratorInterface
* Generates the report. * Generates the report.
* *
* @throws FireflyException * @throws FireflyException
* */ */
public function generate(): string public function generate(): string
{ {
$auditData = []; $auditData = [];
@@ -110,7 +110,7 @@ class MonthReportGenerator implements ReportGeneratorInterface
* Get the audit report. * Get the audit report.
* *
* @throws FireflyException * @throws FireflyException
* */ */
public function getAuditReport(Account $account, Carbon $date): array public function getAuditReport(Account $account, Carbon $date): array
{ {
/** @var AccountRepositoryInterface $accountRepository */ /** @var AccountRepositoryInterface $accountRepository */

View File

@@ -115,7 +115,7 @@ class StandardMessageGenerator implements MessageGeneratorInterface
/** /**
* @throws FireflyException * @throws FireflyException
* */ */
private function runWebhook(Webhook $webhook): void private function runWebhook(Webhook $webhook): void
{ {
app('log')->debug(sprintf('Now in runWebhook(#%d)', $webhook->id)); app('log')->debug(sprintf('Now in runWebhook(#%d)', $webhook->id));
@@ -128,7 +128,7 @@ class StandardMessageGenerator implements MessageGeneratorInterface
/** /**
* @throws FireflyException * @throws FireflyException
* */ */
private function generateMessage(Webhook $webhook, Model $model): void private function generateMessage(Webhook $webhook, Model $model): void
{ {
$class = get_class($model); $class = get_class($model);

View File

@@ -67,7 +67,9 @@ class EditController extends Controller
} }
/** /**
* Edit account overview. * Edit account overview. It's complex, but it just has a lot of if/then/else.
*
* @SuppressWarnings(PHPMD.NPathComplexity)
* *
* @return Factory|Redirector|RedirectResponse|View * @return Factory|Redirector|RedirectResponse|View
*/ */

View File

@@ -146,7 +146,7 @@ class ReconcileController extends Controller
* @return Redirector|RedirectResponse * @return Redirector|RedirectResponse
* *
* @throws DuplicateTransactionException * @throws DuplicateTransactionException
* */ */
public function submit(ReconciliationStoreRequest $request, Account $account, Carbon $start, Carbon $end) public function submit(ReconciliationStoreRequest $request, Account $account, Carbon $start, Carbon $end)
{ {
if (!$this->isEditableAccount($account)) { if (!$this->isEditableAccount($account)) {
@@ -188,7 +188,7 @@ class ReconcileController extends Controller
* Creates a reconciliation group. * Creates a reconciliation group.
* *
* @throws DuplicateTransactionException * @throws DuplicateTransactionException
* */ */
private function createReconciliation(Account $account, Carbon $start, Carbon $end, string $difference): string private function createReconciliation(Account $account, Carbon $start, Carbon $end, string $difference): string
{ {
if (!$this->isEditableAccount($account)) { if (!$this->isEditableAccount($account)) {

View File

@@ -76,8 +76,7 @@ class AccountController extends Controller
* Shows the balances for all the user's expense accounts (on the front page). * Shows the balances for all the user's expense accounts (on the front page).
* *
* This chart is (multi) currency aware. * This chart is (multi) currency aware.
* */
* */
public function expenseAccounts(): JsonResponse public function expenseAccounts(): JsonResponse
{ {
/** @var Carbon $start */ /** @var Carbon $start */
@@ -380,7 +379,7 @@ class AccountController extends Controller
* Shows overview of account during a single period. * Shows overview of account during a single period.
* *
* @throws FireflyException * @throws FireflyException
* */ */
public function period(Account $account, Carbon $start, Carbon $end): JsonResponse public function period(Account $account, Carbon $start, Carbon $end): JsonResponse
{ {
$chartData = []; $chartData = [];
@@ -416,7 +415,7 @@ class AccountController extends Controller
* TODO this chart is not multi currency aware. * TODO this chart is not multi currency aware.
* *
* @throws FireflyException * @throws FireflyException
* */ */
public function report(Collection $accounts, Carbon $start, Carbon $end): JsonResponse public function report(Collection $accounts, Carbon $start, Carbon $end): JsonResponse
{ {
return response()->json($this->accountBalanceChart($accounts, $start, $end)); return response()->json($this->accountBalanceChart($accounts, $start, $end));
@@ -426,8 +425,7 @@ class AccountController extends Controller
* Shows the balances for all the user's revenue accounts. * Shows the balances for all the user's revenue accounts.
* *
* This chart is multi-currency aware. * This chart is multi-currency aware.
* */
* */
public function revenueAccounts(): JsonResponse public function revenueAccounts(): JsonResponse
{ {
/** @var Carbon $start */ /** @var Carbon $start */
@@ -517,7 +515,7 @@ class AccountController extends Controller
/** /**
* @throws FireflyException * @throws FireflyException
* */ */
private function periodByCurrency(Carbon $start, Carbon $end, Account $account, TransactionCurrency $currency): array private function periodByCurrency(Carbon $start, Carbon $end, Account $account, TransactionCurrency $currency): array
{ {
app('log')->debug(sprintf('Now in periodByCurrency("%s", "%s", %s, "%s")', $start->format('Y-m-d'), $end->format('Y-m-d'), $account->id, $currency->code)); app('log')->debug(sprintf('Now in periodByCurrency("%s", "%s", %s, "%s")', $start->format('Y-m-d'), $end->format('Y-m-d'), $account->id, $currency->code));

View File

@@ -32,6 +32,9 @@ use Illuminate\Routing\Controller as BaseController;
/** /**
* Class Controller. * Class Controller.
*
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
* @SuppressWarnings(PHPMD.NumberOfChildren)
*/ */
abstract class Controller extends BaseController abstract class Controller extends BaseController
{ {

View File

@@ -65,7 +65,7 @@ class ReconcileController extends Controller
* Overview of reconciliation. * Overview of reconciliation.
* *
* @throws FireflyException * @throws FireflyException
* */ */
public function overview(Request $request, Account $account = null, Carbon $start = null, Carbon $end = null): JsonResponse public function overview(Request $request, Account $account = null, Carbon $start = null, Carbon $end = null): JsonResponse
{ {
$startBalance = $request->get('startBalance'); $startBalance = $request->get('startBalance');
@@ -165,7 +165,7 @@ class ReconcileController extends Controller
* @return JsonResponse * @return JsonResponse
* *
* @throws FireflyException * @throws FireflyException
* */ */
public function transactions(Account $account, Carbon $start = null, Carbon $end = null) public function transactions(Account $account, Carbon $start = null, Carbon $end = null)
{ {
if (null === $start || null === $end) { if (null === $start || null === $end) {

View File

@@ -59,6 +59,8 @@ class RecurrenceController extends Controller
/** /**
* Shows all events for a repetition. Used in calendar. * Shows all events for a repetition. Used in calendar.
* *
* @SuppressWarnings(PHPMD.NPathComplexity)
*
* @throws FireflyException * @throws FireflyException
*/ */
public function events(Request $request): JsonResponse public function events(Request $request): JsonResponse

View File

@@ -74,7 +74,7 @@ class IndexController extends Controller
* @return Factory|View * @return Factory|View
* *
* @throws FireflyException * @throws FireflyException
* */ */
public function index() public function index()
{ {
$this->cleanupObjectGroups(); $this->cleanupObjectGroups();

View File

@@ -66,7 +66,7 @@ class ShowController extends Controller
* @return Factory|View * @return Factory|View
* *
* @throws FireflyException * @throws FireflyException
* */ */
public function show(PiggyBank $piggyBank) public function show(PiggyBank $piggyBank)
{ {
/** @var Carbon $end */ /** @var Carbon $end */

View File

@@ -150,6 +150,7 @@ class PreferencesController extends Controller
* @throws FireflyException * @throws FireflyException
* *
* @SuppressWarnings(PHPMD.ExcessiveMethodLength) * @SuppressWarnings(PHPMD.ExcessiveMethodLength)
* @SuppressWarnings(PHPMD.NPathComplexity)
*/ */
public function postIndex(Request $request) public function postIndex(Request $request)
{ {

View File

@@ -66,7 +66,7 @@ class BudgetController extends Controller
* @return Factory|View * @return Factory|View
* *
* @throws FireflyException * @throws FireflyException
* */ */
public function accountPerBudget(Collection $accounts, Collection $budgets, Carbon $start, Carbon $end) public function accountPerBudget(Collection $accounts, Collection $budgets, Carbon $start, Carbon $end)
{ {
/** @var BudgetReportGenerator $generator */ /** @var BudgetReportGenerator $generator */
@@ -257,7 +257,7 @@ class BudgetController extends Controller
* @return string * @return string
* *
* @throws FireflyException * @throws FireflyException
* */ */
public function general(Collection $accounts, Carbon $start, Carbon $end) public function general(Collection $accounts, Carbon $start, Carbon $end)
{ {
/** @var BudgetReportGenerator $generator */ /** @var BudgetReportGenerator $generator */

View File

@@ -85,6 +85,8 @@ use Laravel\Passport\Events\AccessTokenCreated;
/** /**
* Class EventServiceProvider. * Class EventServiceProvider.
*
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
*/ */
class EventServiceProvider extends ServiceProvider class EventServiceProvider extends ServiceProvider
{ {

View File

@@ -75,6 +75,8 @@ use Illuminate\Support\ServiceProvider;
/** /**
* Class FireflyServiceProvider. * Class FireflyServiceProvider.
*
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
*/ */
class FireflyServiceProvider extends ServiceProvider class FireflyServiceProvider extends ServiceProvider
{ {

View File

@@ -221,7 +221,7 @@ class AccountRepository implements AccountRepositoryInterface
/** /**
* @throws FireflyException * @throws FireflyException
* */ */
public function getCashAccount(): Account public function getCashAccount(): Account
{ {
/** @var AccountType $type */ /** @var AccountType $type */
@@ -342,7 +342,7 @@ class AccountRepository implements AccountRepositoryInterface
/** /**
* @throws FireflyException * @throws FireflyException
* */ */
public function getReconciliation(Account $account): ?Account public function getReconciliation(Account $account): ?Account
{ {
if (AccountType::ASSET !== $account->accountType->type) { if (AccountType::ASSET !== $account->accountType->type) {
@@ -617,7 +617,7 @@ class AccountRepository implements AccountRepositoryInterface
/** /**
* @throws FireflyException * @throws FireflyException
* */ */
public function store(array $data): Account public function store(array $data): Account
{ {
/** @var AccountFactory $factory */ /** @var AccountFactory $factory */
@@ -629,7 +629,7 @@ class AccountRepository implements AccountRepositoryInterface
/** /**
* @throws FireflyException * @throws FireflyException
* */ */
public function update(Account $account, array $data): Account public function update(Account $account, array $data): Account
{ {
/** @var AccountUpdateService $service */ /** @var AccountUpdateService $service */

View File

@@ -42,7 +42,7 @@ class AccountTasker implements AccountTaskerInterface
/** /**
* @throws FireflyException * @throws FireflyException
* */ */
public function getAccountReport(Collection $accounts, Carbon $start, Carbon $end): array public function getAccountReport(Collection $accounts, Carbon $start, Carbon $end): array
{ {
$yesterday = clone $start; $yesterday = clone $start;
@@ -109,7 +109,7 @@ class AccountTasker implements AccountTaskerInterface
/** /**
* @throws FireflyException * @throws FireflyException
* */ */
public function getExpenseReport(Carbon $start, Carbon $end, Collection $accounts): array public function getExpenseReport(Carbon $start, Carbon $end, Collection $accounts): array
{ {
// get all expenses for the given accounts in the given period! // get all expenses for the given accounts in the given period!
@@ -140,7 +140,7 @@ class AccountTasker implements AccountTaskerInterface
/** /**
* @throws FireflyException * @throws FireflyException
* */ */
public function getIncomeReport(Carbon $start, Carbon $end, Collection $accounts): array public function getIncomeReport(Carbon $start, Carbon $end, Collection $accounts): array
{ {
// get all incomes for the given accounts in the given period! // get all incomes for the given accounts in the given period!
@@ -175,7 +175,7 @@ class AccountTasker implements AccountTaskerInterface
/** /**
* @throws FireflyException * @throws FireflyException
* */ */
private function groupExpenseByDestination(array $array): array private function groupExpenseByDestination(array $array): array
{ {
$defaultCurrency = app('amount')->getDefaultCurrencyByUserGroup($this->user->userGroup); $defaultCurrency = app('amount')->getDefaultCurrencyByUserGroup($this->user->userGroup);
@@ -235,7 +235,7 @@ class AccountTasker implements AccountTaskerInterface
/** /**
* @throws FireflyException * @throws FireflyException
* */ */
private function groupIncomeBySource(array $array): array private function groupIncomeBySource(array $array): array
{ {
$defaultCurrency = app('amount')->getDefaultCurrencyByUserGroup($this->user->userGroup); $defaultCurrency = app('amount')->getDefaultCurrencyByUserGroup($this->user->userGroup);

View File

@@ -218,6 +218,7 @@ class OperationsRepository implements OperationsRepositoryInterface
/** /**
* @SuppressWarnings(PHPMD.ExcessiveParameterList) * @SuppressWarnings(PHPMD.ExcessiveParameterList)
* @SuppressWarnings(PHPMD.NPathComplexity)
*/ */
private function getTransactionsForSum( private function getTransactionsForSum(
string $type, string $type,

View File

@@ -421,8 +421,7 @@ class BillRepository implements BillRepositoryInterface
/** /**
* Given the date in $date, this method will return a moment in the future where the bill is expected to be paid. * Given the date in $date, this method will return a moment in the future where the bill is expected to be paid.
* */
* */
public function nextExpectedMatch(Bill $bill, Carbon $date): Carbon public function nextExpectedMatch(Bill $bill, Carbon $date): Carbon
{ {
$cache = new CacheProperties(); $cache = new CacheProperties();
@@ -463,7 +462,7 @@ class BillRepository implements BillRepositoryInterface
/** /**
* @throws FireflyException * @throws FireflyException
* */ */
public function store(array $data): Bill public function store(array $data): Bill
{ {
/** @var BillFactory $factory */ /** @var BillFactory $factory */
@@ -643,7 +642,7 @@ class BillRepository implements BillRepositoryInterface
/** /**
* @throws FireflyException * @throws FireflyException
* */ */
public function update(Bill $bill, array $data): Bill public function update(Bill $bill, array $data): Bill
{ {
/** @var BillUpdateService $service */ /** @var BillUpdateService $service */

View File

@@ -261,7 +261,7 @@ class BudgetLimitRepository implements BudgetLimitRepositoryInterface
/** /**
* @throws FireflyException * @throws FireflyException
* */ */
public function store(array $data): BudgetLimit public function store(array $data): BudgetLimit
{ {
// if no currency has been provided, use the user's default currency: // if no currency has been provided, use the user's default currency:
@@ -316,7 +316,7 @@ class BudgetLimitRepository implements BudgetLimitRepositoryInterface
/** /**
* @throws FireflyException * @throws FireflyException
* */ */
public function update(BudgetLimit $budgetLimit, array $data): BudgetLimit public function update(BudgetLimit $budgetLimit, array $data): BudgetLimit
{ {
$budgetLimit->amount = array_key_exists('amount', $data) ? $data['amount'] : $budgetLimit->amount; $budgetLimit->amount = array_key_exists('amount', $data) ? $data['amount'] : $budgetLimit->amount;

View File

@@ -97,7 +97,7 @@ class BudgetRepository implements BudgetRepositoryInterface
app('log')->debug(sprintf('Budget limit #%d', $limit->id)); app('log')->debug(sprintf('Budget limit #%d', $limit->id));
$currency = $limit->transactionCurrency; $currency = $limit->transactionCurrency;
$return[$currency->id] ??= [ $return[$currency->id] ??= [
'id' => (string)$currency->id, 'id' => (string) $currency->id,
'name' => $currency->name, 'name' => $currency->name,
'symbol' => $currency->symbol, 'symbol' => $currency->symbol,
'code' => $currency->code, 'code' => $currency->code,
@@ -120,12 +120,12 @@ class BudgetRepository implements BudgetRepositoryInterface
} }
$total = $limit->start_date->diffInDays($limit->end_date) + 1; // include the day itself. $total = $limit->start_date->diffInDays($limit->end_date) + 1; // include the day itself.
$days = $this->daysInOverlap($limit, $start, $end); $days = $this->daysInOverlap($limit, $start, $end);
$amount = bcmul(bcdiv($limit->amount, (string)$total), (string)$days); $amount = bcmul(bcdiv($limit->amount, (string) $total), (string) $days);
$return[$currency->id]['sum'] = bcadd($return[$currency->id]['sum'], $amount); $return[$currency->id]['sum'] = bcadd($return[$currency->id]['sum'], $amount);
app('log')->debug( app('log')->debug(
sprintf( sprintf(
'Amount per day: %s (%s over %d days). Total amount for %d days: %s', 'Amount per day: %s (%s over %d days). Total amount for %d days: %s',
bcdiv($limit->amount, (string)$total), bcdiv($limit->amount, (string) $total),
$limit->amount, $limit->amount,
$total, $total,
$days, $days,
@@ -171,7 +171,7 @@ class BudgetRepository implements BudgetRepositoryInterface
app('log')->debug(sprintf('Budget limit #%d', $limit->id)); app('log')->debug(sprintf('Budget limit #%d', $limit->id));
$currency = $limit->transactionCurrency; $currency = $limit->transactionCurrency;
$return[$currency->id] ??= [ $return[$currency->id] ??= [
'id' => (string)$currency->id, 'id' => (string) $currency->id,
'name' => $currency->name, 'name' => $currency->name,
'symbol' => $currency->symbol, 'symbol' => $currency->symbol,
'code' => $currency->code, 'code' => $currency->code,
@@ -194,12 +194,12 @@ class BudgetRepository implements BudgetRepositoryInterface
} }
$total = $limit->start_date->diffInDays($limit->end_date) + 1; // include the day itself. $total = $limit->start_date->diffInDays($limit->end_date) + 1; // include the day itself.
$days = $this->daysInOverlap($limit, $start, $end); $days = $this->daysInOverlap($limit, $start, $end);
$amount = bcmul(bcdiv($limit->amount, (string)$total), (string)$days); $amount = bcmul(bcdiv($limit->amount, (string) $total), (string) $days);
$return[$currency->id]['sum'] = bcadd($return[$currency->id]['sum'], $amount); $return[$currency->id]['sum'] = bcadd($return[$currency->id]['sum'], $amount);
app('log')->debug( app('log')->debug(
sprintf( sprintf(
'Amount per day: %s (%s over %d days). Total amount for %d days: %s', 'Amount per day: %s (%s over %d days). Total amount for %d days: %s',
bcdiv($limit->amount, (string)$total), bcdiv($limit->amount, (string) $total),
$limit->amount, $limit->amount,
$total, $total,
$days, $days,
@@ -233,7 +233,7 @@ class BudgetRepository implements BudgetRepositoryInterface
/** /**
* @throws FireflyException * @throws FireflyException
* */ */
public function update(Budget $budget, array $data): Budget public function update(Budget $budget, array $data): Budget
{ {
app('log')->debug('Now in update()'); app('log')->debug('Now in update()');
@@ -248,7 +248,7 @@ class BudgetRepository implements BudgetRepositoryInterface
$budget->active = $data['active']; $budget->active = $data['active'];
} }
if (array_key_exists('notes', $data)) { if (array_key_exists('notes', $data)) {
$this->setNoteText($budget, (string)$data['notes']); $this->setNoteText($budget, (string) $data['notes']);
} }
$budget->save(); $budget->save();
@@ -310,8 +310,8 @@ class BudgetRepository implements BudgetRepositoryInterface
foreach ($budgets as $budget) { foreach ($budgets as $budget) {
\DB::table('budget_transaction')->where('budget_id', $budget->id)->delete(); \DB::table('budget_transaction')->where('budget_id', $budget->id)->delete();
\DB::table('budget_transaction_journal')->where('budget_id', $budget->id)->delete(); \DB::table('budget_transaction_journal')->where('budget_id', $budget->id)->delete();
RecurrenceTransactionMeta::where('name', 'budget_id')->where('value', (string)$budget->id)->delete(); RecurrenceTransactionMeta::where('name', 'budget_id')->where('value', (string) $budget->id)->delete();
RuleAction::where('action_type', 'set_budget')->where('action_value', (string)$budget->id)->delete(); RuleAction::where('action_type', 'set_budget')->where('action_value', (string) $budget->id)->delete();
$budget->delete(); $budget->delete();
} }
} }
@@ -335,7 +335,7 @@ class BudgetRepository implements BudgetRepositoryInterface
{ {
app('log')->debug('Now in findBudget()'); app('log')->debug('Now in findBudget()');
app('log')->debug(sprintf('Searching for budget with ID #%d...', $budgetId)); app('log')->debug(sprintf('Searching for budget with ID #%d...', $budgetId));
$result = $this->find((int)$budgetId); $result = $this->find((int) $budgetId);
if (null === $result && null !== $budgetName && '' !== $budgetName) { if (null === $result && null !== $budgetName && '' !== $budgetName) {
app('log')->debug(sprintf('Searching for budget with name %s...', $budgetName)); app('log')->debug(sprintf('Searching for budget with name %s...', $budgetName));
$result = $this->findByName($budgetName); $result = $this->findByName($budgetName);
@@ -471,9 +471,9 @@ class BudgetRepository implements BudgetRepositoryInterface
$array = []; $array = [];
foreach ($journals as $journal) { foreach ($journals as $journal) {
$currencyId = (int)$journal['currency_id']; $currencyId = (int) $journal['currency_id'];
$array[$currencyId] ??= [ $array[$currencyId] ??= [
'id' => (string)$currencyId, 'id' => (string) $currencyId,
'name' => $journal['currency_name'], 'name' => $journal['currency_name'],
'symbol' => $journal['currency_symbol'], 'symbol' => $journal['currency_symbol'],
'code' => $journal['currency_code'], 'code' => $journal['currency_code'],
@@ -483,10 +483,10 @@ class BudgetRepository implements BudgetRepositoryInterface
$array[$currencyId]['sum'] = bcadd($array[$currencyId]['sum'], app('steam')->negative($journal['amount'])); $array[$currencyId]['sum'] = bcadd($array[$currencyId]['sum'], app('steam')->negative($journal['amount']));
// also do foreign amount: // also do foreign amount:
$foreignId = (int)$journal['foreign_currency_id']; $foreignId = (int) $journal['foreign_currency_id'];
if (0 !== $foreignId) { if (0 !== $foreignId) {
$array[$foreignId] ??= [ $array[$foreignId] ??= [
'id' => (string)$foreignId, 'id' => (string) $foreignId,
'name' => $journal['foreign_currency_name'], 'name' => $journal['foreign_currency_name'],
'symbol' => $journal['foreign_currency_symbol'], 'symbol' => $journal['foreign_currency_symbol'],
'code' => $journal['foreign_currency_code'], 'code' => $journal['foreign_currency_code'],
@@ -533,9 +533,9 @@ class BudgetRepository implements BudgetRepositoryInterface
$array = []; $array = [];
foreach ($journals as $journal) { foreach ($journals as $journal) {
$currencyId = (int)$journal['currency_id']; $currencyId = (int) $journal['currency_id'];
$array[$currencyId] ??= [ $array[$currencyId] ??= [
'id' => (string)$currencyId, 'id' => (string) $currencyId,
'name' => $journal['currency_name'], 'name' => $journal['currency_name'],
'symbol' => $journal['currency_symbol'], 'symbol' => $journal['currency_symbol'],
'code' => $journal['currency_code'], 'code' => $journal['currency_code'],
@@ -545,10 +545,10 @@ class BudgetRepository implements BudgetRepositoryInterface
$array[$currencyId]['sum'] = bcadd($array[$currencyId]['sum'], app('steam')->negative($journal['amount'])); $array[$currencyId]['sum'] = bcadd($array[$currencyId]['sum'], app('steam')->negative($journal['amount']));
// also do foreign amount: // also do foreign amount:
$foreignId = (int)$journal['foreign_currency_id']; $foreignId = (int) $journal['foreign_currency_id'];
if (0 !== $foreignId) { if (0 !== $foreignId) {
$array[$foreignId] ??= [ $array[$foreignId] ??= [
'id' => (string)$foreignId, 'id' => (string) $foreignId,
'name' => $journal['foreign_currency_name'], 'name' => $journal['foreign_currency_name'],
'symbol' => $journal['foreign_currency_symbol'], 'symbol' => $journal['foreign_currency_symbol'],
'code' => $journal['foreign_currency_code'], 'code' => $journal['foreign_currency_code'],
@@ -564,7 +564,9 @@ class BudgetRepository implements BudgetRepositoryInterface
/** /**
* @throws FireflyException * @throws FireflyException
* */ *
* @SuppressWarnings(PHPMD.NPathComplexity)
*/
public function store(array $data): Budget public function store(array $data): Budget
{ {
$order = $this->getMaxOrder(); $order = $this->getMaxOrder();
@@ -588,7 +590,7 @@ class BudgetRepository implements BudgetRepositoryInterface
// set notes // set notes
if (array_key_exists('notes', $data)) { if (array_key_exists('notes', $data)) {
$this->setNoteText($newBudget, (string)$data['notes']); $this->setNoteText($newBudget, (string) $data['notes']);
} }
if (!array_key_exists('auto_budget_type', $data) || !array_key_exists('auto_budget_amount', $data) || !array_key_exists('auto_budget_period', $data)) { if (!array_key_exists('auto_budget_type', $data) || !array_key_exists('auto_budget_amount', $data) || !array_key_exists('auto_budget_period', $data)) {
@@ -616,10 +618,10 @@ class BudgetRepository implements BudgetRepositoryInterface
$repos = app(CurrencyRepositoryInterface::class); $repos = app(CurrencyRepositoryInterface::class);
$currency = null; $currency = null;
if (array_key_exists('currency_id', $data)) { if (array_key_exists('currency_id', $data)) {
$currency = $repos->find((int)$data['currency_id']); $currency = $repos->find((int) $data['currency_id']);
} }
if (array_key_exists('currency_code', $data)) { if (array_key_exists('currency_code', $data)) {
$currency = $repos->findByCode((string)$data['currency_code']); $currency = $repos->findByCode((string) $data['currency_code']);
} }
if (null === $currency) { if (null === $currency) {
$currency = app('amount')->getDefaultCurrencyByUserGroup($this->user->userGroup); $currency = app('amount')->getDefaultCurrencyByUserGroup($this->user->userGroup);
@@ -655,7 +657,7 @@ class BudgetRepository implements BudgetRepositoryInterface
public function getMaxOrder(): int public function getMaxOrder(): int
{ {
return (int)$this->user->budgets()->max('order'); return (int) $this->user->budgets()->max('order');
} }
/** /**
@@ -750,7 +752,7 @@ class BudgetRepository implements BudgetRepositoryInterface
/** /**
* @throws FireflyException * @throws FireflyException
* */ */
private function updateAutoBudget(Budget $budget, array $data): void private function updateAutoBudget(Budget $budget, array $data): void
{ {
// update or create auto-budget: // update or create auto-budget:
@@ -771,8 +773,8 @@ class BudgetRepository implements BudgetRepositoryInterface
if (array_key_exists('currency_id', $data) || array_key_exists('currency_code', $data)) { if (array_key_exists('currency_id', $data) || array_key_exists('currency_code', $data)) {
/** @var CurrencyRepositoryInterface $repos */ /** @var CurrencyRepositoryInterface $repos */
$repos = app(CurrencyRepositoryInterface::class); $repos = app(CurrencyRepositoryInterface::class);
$currencyId = (int)($data['currency_id'] ?? 0); $currencyId = (int) ($data['currency_id'] ?? 0);
$currencyCode = (string)($data['currency_code'] ?? ''); $currencyCode = (string) ($data['currency_code'] ?? '');
$currency = $repos->find($currencyId); $currency = $repos->find($currencyId);
if (null === $currency) { if (null === $currency) {
$currency = $repos->findByCode($currencyCode); $currency = $repos->findByCode($currencyCode);

View File

@@ -135,7 +135,7 @@ class PiggyBankRepository implements PiggyBankRepositoryInterface
* Used for connecting to a piggy bank. * Used for connecting to a piggy bank.
* *
* @throws FireflyException * @throws FireflyException
* */ */
public function getExactAmount(PiggyBank $piggyBank, PiggyBankRepetition $repetition, TransactionJournal $journal): string public function getExactAmount(PiggyBank $piggyBank, PiggyBankRepetition $repetition, TransactionJournal $journal): string
{ {
app('log')->debug(sprintf('Now in getExactAmount(%d, %d, %d)', $piggyBank->id, $repetition->id, $journal->id)); app('log')->debug(sprintf('Now in getExactAmount(%d, %d, %d)', $piggyBank->id, $repetition->id, $journal->id));
@@ -318,8 +318,7 @@ class PiggyBankRepository implements PiggyBankRepositoryInterface
/** /**
* Get for piggy account what is left to put in piggies. * Get for piggy account what is left to put in piggies.
* */
* */
public function leftOnAccount(PiggyBank $piggyBank, Carbon $date): string public function leftOnAccount(PiggyBank $piggyBank, Carbon $date): string
{ {
$balance = app('steam')->balanceIgnoreVirtual($piggyBank->account, $date); $balance = app('steam')->balanceIgnoreVirtual($piggyBank->account, $date);

View File

@@ -258,8 +258,7 @@ class RecurringRepository implements RecurringRepositoryInterface
/** /**
* Get the tags from the recurring transaction. * Get the tags from the recurring transaction.
* */
* */
public function getTags(RecurrenceTransaction $transaction): array public function getTags(RecurrenceTransaction $transaction): array
{ {
$tags = []; $tags = [];
@@ -479,7 +478,7 @@ class RecurringRepository implements RecurringRepositoryInterface
/** /**
* @throws FireflyException * @throws FireflyException
* */ */
public function store(array $data): Recurrence public function store(array $data): Recurrence
{ {
/** @var RecurrenceFactory $factory */ /** @var RecurrenceFactory $factory */

View File

@@ -255,7 +255,7 @@ class TransactionGroupRepository implements TransactionGroupRepositoryInterface
* Return all piggy bank events for all journals in the group. * Return all piggy bank events for all journals in the group.
* *
* @throws FireflyException * @throws FireflyException
* */ */
public function getPiggyEvents(TransactionGroup $group): array public function getPiggyEvents(TransactionGroup $group): array
{ {
$return = []; $return = [];
@@ -318,7 +318,7 @@ class TransactionGroupRepository implements TransactionGroupRepositoryInterface
/** /**
* @throws DuplicateTransactionException * @throws DuplicateTransactionException
* @throws FireflyException * @throws FireflyException
* */ */
public function store(array $data): TransactionGroup public function store(array $data): TransactionGroup
{ {
/** @var TransactionGroupFactory $factory */ /** @var TransactionGroupFactory $factory */

View File

@@ -157,6 +157,8 @@ class UserGroupRepository implements UserGroupRepositoryInterface
} }
/** /**
* @SuppressWarnings(PHPMD.NPathComplexity)
*
* @throws FireflyException * @throws FireflyException
*/ */
public function updateMembership(UserGroup $userGroup, array $data): UserGroup public function updateMembership(UserGroup $userGroup, array $data): UserGroup

View File

@@ -217,7 +217,7 @@ class CurrencyRepository implements CurrencyRepositoryInterface
* Find by object, ID or code. Returns user default or system default. * Find by object, ID or code. Returns user default or system default.
* *
* @throws FireflyException * @throws FireflyException
* */ */
public function findCurrency(?int $currencyId, ?string $currencyCode): TransactionCurrency public function findCurrency(?int $currencyId, ?string $currencyCode): TransactionCurrency
{ {
$result = $this->findCurrencyNull($currencyId, $currencyCode); $result = $this->findCurrencyNull($currencyId, $currencyCode);

View File

@@ -88,6 +88,8 @@ trait AccountServiceTrait
/** /**
* Update metadata for account. Depends on type which fields are valid. * Update metadata for account. Depends on type which fields are valid.
* *
* @SuppressWarnings(PHPMD.NPathComplexity)
*
* TODO this method treats expense accounts and liabilities the same way (tries to save interest) * TODO this method treats expense accounts and liabilities the same way (tries to save interest)
*/ */
public function updateMetaData(Account $account, array $data): void public function updateMetaData(Account $account, array $data): void
@@ -336,7 +338,7 @@ trait AccountServiceTrait
/** /**
* @throws FireflyException * @throws FireflyException
* */ */
protected function getCurrency(int $currencyId, string $currencyCode): TransactionCurrency protected function getCurrency(int $currencyId, string $currencyCode): TransactionCurrency
{ {
// find currency, or use default currency instead. // find currency, or use default currency instead.
@@ -360,7 +362,7 @@ trait AccountServiceTrait
* Create the opposing "credit liability" transaction for credit liabilities. * Create the opposing "credit liability" transaction for credit liabilities.
* *
* @throws FireflyException * @throws FireflyException
* */ */
protected function updateCreditTransaction(Account $account, string $direction, string $openingBalance, Carbon $openingBalanceDate): TransactionGroup protected function updateCreditTransaction(Account $account, string $direction, string $openingBalance, Carbon $openingBalanceDate): TransactionGroup
{ {
app('log')->debug(sprintf('Now in %s', __METHOD__)); app('log')->debug(sprintf('Now in %s', __METHOD__));
@@ -416,7 +418,7 @@ trait AccountServiceTrait
/** /**
* @throws FireflyException * @throws FireflyException
* */ */
protected function createCreditTransaction(Account $account, string $openingBalance, Carbon $openingBalanceDate): TransactionGroup protected function createCreditTransaction(Account $account, string $openingBalance, Carbon $openingBalanceDate): TransactionGroup
{ {
app('log')->debug('Now going to create an createCreditTransaction.'); app('log')->debug('Now going to create an createCreditTransaction.');
@@ -510,7 +512,7 @@ trait AccountServiceTrait
* Since opening balance and date can still be empty strings, it may fail. * Since opening balance and date can still be empty strings, it may fail.
* *
* @throws FireflyException * @throws FireflyException
* */ */
protected function updateOBGroupV2(Account $account, string $openingBalance, Carbon $openingBalanceDate): TransactionGroup protected function updateOBGroupV2(Account $account, string $openingBalance, Carbon $openingBalanceDate): TransactionGroup
{ {
app('log')->debug(sprintf('Now in %s', __METHOD__)); app('log')->debug(sprintf('Now in %s', __METHOD__));
@@ -566,7 +568,7 @@ trait AccountServiceTrait
/** /**
* @throws FireflyException * @throws FireflyException
* */ */
protected function createOBGroupV2(Account $account, string $openingBalance, Carbon $openingBalanceDate): TransactionGroup protected function createOBGroupV2(Account $account, string $openingBalance, Carbon $openingBalanceDate): TransactionGroup
{ {
app('log')->debug('Now going to create an OB group.'); app('log')->debug('Now going to create an OB group.');

View File

@@ -243,7 +243,11 @@ class CreditRecalculateService
} }
/** /**
* A complex and long method, but rarely used luckily.
*
* @SuppressWarnings(PHPMD.ExcessiveMethodLength) * @SuppressWarnings(PHPMD.ExcessiveMethodLength)
* @SuppressWarnings(PHPMD.NPathComplexity)
* @SuppressWarnings(PHPMD.CyclomaticComplexity)
*/ */
private function processTransaction(Account $account, string $direction, Transaction $transaction, string $leftOfDebt): string private function processTransaction(Account $account, string $direction, Transaction $transaction, string $leftOfDebt): string
{ {

View File

@@ -87,7 +87,9 @@ trait RecurringTransactionTrait
* Store transactions of a recurring transactions. It's complex but readable. * Store transactions of a recurring transactions. It's complex but readable.
* *
* @throws FireflyException * @throws FireflyException
* */ *
* @SuppressWarnings(PHPMD.NPathComplexity)
*/
protected function createTransactions(Recurrence $recurrence, array $transactions): void protected function createTransactions(Recurrence $recurrence, array $transactions): void
{ {
app('log')->debug('Now in createTransactions()'); app('log')->debug('Now in createTransactions()');
@@ -123,7 +125,7 @@ trait RecurringTransactionTrait
if (!$validator->validateDestination(['id' => $destination->id])) { if (!$validator->validateDestination(['id' => $destination->id])) {
throw new FireflyException(sprintf('Destination invalid: %s', $validator->destError)); throw new FireflyException(sprintf('Destination invalid: %s', $validator->destError));
} }
if (array_key_exists('foreign_amount', $array) && '' === (string)$array['foreign_amount']) { if (array_key_exists('foreign_amount', $array) && '' === (string) $array['foreign_amount']) {
unset($array['foreign_amount']); unset($array['foreign_amount']);
} }
// TODO typeOverrule. The account validator may have a different opinion on the type of the transaction. // TODO typeOverrule. The account validator may have a different opinion on the type of the transaction.
@@ -135,25 +137,25 @@ trait RecurringTransactionTrait
'source_id' => $source->id, 'source_id' => $source->id,
'destination_id' => $destination->id, 'destination_id' => $destination->id,
'amount' => $array['amount'], 'amount' => $array['amount'],
'foreign_amount' => array_key_exists('foreign_amount', $array) ? (string)$array['foreign_amount'] : null, 'foreign_amount' => array_key_exists('foreign_amount', $array) ? (string) $array['foreign_amount'] : null,
'description' => $array['description'], 'description' => $array['description'],
] ]
); );
$transaction->save(); $transaction->save();
if (array_key_exists('budget_id', $array)) { if (array_key_exists('budget_id', $array)) {
$this->setBudget($transaction, (int)$array['budget_id']); $this->setBudget($transaction, (int) $array['budget_id']);
} }
if (array_key_exists('bill_id', $array)) { if (array_key_exists('bill_id', $array)) {
$this->setBill($transaction, (int)$array['bill_id']); $this->setBill($transaction, (int) $array['bill_id']);
} }
if (array_key_exists('category_id', $array)) { if (array_key_exists('category_id', $array)) {
$this->setCategory($transaction, (int)$array['category_id']); $this->setCategory($transaction, (int) $array['category_id']);
} }
// same for piggy bank // same for piggy bank
if (array_key_exists('piggy_bank_id', $array)) { if (array_key_exists('piggy_bank_id', $array)) {
$this->updatePiggyBank($transaction, (int)$array['piggy_bank_id']); $this->updatePiggyBank($transaction, (int) $array['piggy_bank_id']);
} }
if (array_key_exists('tags', $array) && is_array($array['tags'])) { if (array_key_exists('tags', $array) && is_array($array['tags'])) {
@@ -165,8 +167,8 @@ trait RecurringTransactionTrait
protected function findAccount(array $expectedTypes, ?int $accountId, ?string $accountName): Account protected function findAccount(array $expectedTypes, ?int $accountId, ?string $accountName): Account
{ {
$result = null; $result = null;
$accountId = (int)$accountId; $accountId = (int) $accountId;
$accountName = (string)$accountName; $accountName = (string) $accountName;
/** @var AccountRepositoryInterface $repository */ /** @var AccountRepositoryInterface $repository */
$repository = app(AccountRepositoryInterface::class); $repository = app(AccountRepositoryInterface::class);

View File

@@ -63,7 +63,7 @@ class AccountUpdateService
* Update account data. * Update account data.
* *
* @throws FireflyException * @throws FireflyException
* */ */
public function update(Account $account, array $data): Account public function update(Account $account, array $data): Account
{ {
app('log')->debug(sprintf('Now in %s', __METHOD__)); app('log')->debug(sprintf('Now in %s', __METHOD__));

View File

@@ -46,14 +46,14 @@ class BillUpdateService
/** /**
* @throws FireflyException * @throws FireflyException
* */ */
public function update(Bill $bill, array $data): Bill public function update(Bill $bill, array $data): Bill
{ {
$this->user = $bill->user; $this->user = $bill->user;
if (array_key_exists('currency_id', $data) || array_key_exists('currency_code', $data)) { if (array_key_exists('currency_id', $data) || array_key_exists('currency_code', $data)) {
$factory = app(TransactionCurrencyFactory::class); $factory = app(TransactionCurrencyFactory::class);
$currency = $factory->find((int)($data['currency_id'] ?? null), $data['currency_code'] ?? null) ?? $currency = $factory->find((int) ($data['currency_id'] ?? null), $data['currency_code'] ?? null) ??
app('amount')->getDefaultCurrencyByUserGroup($bill->user->userGroup); app('amount')->getDefaultCurrencyByUserGroup($bill->user->userGroup);
// enable the currency if it isn't. // enable the currency if it isn't.
@@ -75,14 +75,14 @@ class BillUpdateService
]; ];
// update note: // update note:
if (array_key_exists('notes', $data)) { if (array_key_exists('notes', $data)) {
$this->updateNote($bill, (string)$data['notes']); $this->updateNote($bill, (string) $data['notes']);
} }
// update order. // update order.
if (array_key_exists('order', $data)) { if (array_key_exists('order', $data)) {
// update the order of the piggy bank: // update the order of the piggy bank:
$oldOrder = $bill->order; $oldOrder = $bill->order;
$newOrder = (int)($data['order'] ?? $oldOrder); $newOrder = (int) ($data['order'] ?? $oldOrder);
if ($oldOrder !== $newOrder) { if ($oldOrder !== $newOrder) {
$this->updateOrder($bill, $oldOrder, $newOrder); $this->updateOrder($bill, $oldOrder, $newOrder);
} }
@@ -112,7 +112,7 @@ class BillUpdateService
} }
if (array_key_exists('object_group_id', $data)) { if (array_key_exists('object_group_id', $data)) {
// try also with ID: // try also with ID:
$objectGroupId = (int)($data['object_group_id'] ?? 0); $objectGroupId = (int) ($data['object_group_id'] ?? 0);
if (0 !== $objectGroupId) { if (0 !== $objectGroupId) {
$objectGroup = $this->findObjectGroupById($objectGroupId); $objectGroup = $this->findObjectGroupById($objectGroupId);
if (null !== $objectGroup) { if (null !== $objectGroup) {
@@ -129,22 +129,25 @@ class BillUpdateService
return $bill; return $bill;
} }
/**
* @SuppressWarnings(PHPMD.NPathComplexity)
*/
private function updateBillProperties(Bill $bill, array $data): Bill private function updateBillProperties(Bill $bill, array $data): Bill
{ {
if (array_key_exists('name', $data) && '' !== (string)$data['name']) { if (array_key_exists('name', $data) && '' !== (string) $data['name']) {
$bill->name = $data['name']; $bill->name = $data['name'];
} }
if (array_key_exists('amount_min', $data) && '' !== (string)$data['amount_min']) { if (array_key_exists('amount_min', $data) && '' !== (string) $data['amount_min']) {
$bill->amount_min = $data['amount_min']; $bill->amount_min = $data['amount_min'];
} }
if (array_key_exists('amount_max', $data) && '' !== (string)$data['amount_max']) { if (array_key_exists('amount_max', $data) && '' !== (string) $data['amount_max']) {
$bill->amount_max = $data['amount_max']; $bill->amount_max = $data['amount_max'];
} }
if (array_key_exists('date', $data) && '' !== (string)$data['date']) { if (array_key_exists('date', $data) && '' !== (string) $data['date']) {
$bill->date = $data['date']; $bill->date = $data['date'];
} }
if (array_key_exists('repeat_freq', $data) && '' !== (string)$data['repeat_freq']) { if (array_key_exists('repeat_freq', $data) && '' !== (string) $data['repeat_freq']) {
$bill->repeat_freq = $data['repeat_freq']; $bill->repeat_freq = $data['repeat_freq'];
} }
if (array_key_exists('skip', $data)) { if (array_key_exists('skip', $data)) {

View File

@@ -41,7 +41,7 @@ class GroupUpdateService
* *
* @throws DuplicateTransactionException * @throws DuplicateTransactionException
* @throws FireflyException * @throws FireflyException
* */ */
public function update(TransactionGroup $transactionGroup, array $data): TransactionGroup public function update(TransactionGroup $transactionGroup, array $data): TransactionGroup
{ {
app('log')->debug(sprintf('Now in %s', __METHOD__)); app('log')->debug(sprintf('Now in %s', __METHOD__));
@@ -149,7 +149,7 @@ class GroupUpdateService
/** /**
* @throws DuplicateTransactionException * @throws DuplicateTransactionException
* @throws FireflyException * @throws FireflyException
* */ */
private function updateTransactions(TransactionGroup $transactionGroup, array $transactions): array private function updateTransactions(TransactionGroup $transactionGroup, array $transactions): array
{ {
app('log')->debug(sprintf('Now in %s', __METHOD__)); app('log')->debug(sprintf('Now in %s', __METHOD__));
@@ -206,7 +206,7 @@ class GroupUpdateService
/** /**
* @throws DuplicateTransactionException * @throws DuplicateTransactionException
* @throws FireflyException * @throws FireflyException
* */ */
private function createTransactionJournal(TransactionGroup $transactionGroup, array $data): ?TransactionJournal private function createTransactionJournal(TransactionGroup $transactionGroup, array $data): ?TransactionJournal
{ {
$submission = [ $submission = [

View File

@@ -71,7 +71,7 @@ class RecurrenceUpdateService
$recurrence->repetitions = 0; $recurrence->repetitions = 0;
} }
if (array_key_exists('nr_of_repetitions', $info)) { if (array_key_exists('nr_of_repetitions', $info)) {
if (0 !== (int)$info['nr_of_repetitions']) { if (0 !== (int) $info['nr_of_repetitions']) {
$recurrence->repeat_until = null; $recurrence->repeat_until = null;
} }
$recurrence->repetitions = $info['nr_of_repetitions']; $recurrence->repetitions = $info['nr_of_repetitions'];
@@ -192,7 +192,7 @@ class RecurrenceUpdateService
* TODO this method is very complex. * TODO this method is very complex.
* *
* @throws FireflyException * @throws FireflyException
* */ */
private function updateTransactions(Recurrence $recurrence, array $transactions): void private function updateTransactions(Recurrence $recurrence, array $transactions): void
{ {
app('log')->debug('Now in updateTransactions()'); app('log')->debug('Now in updateTransactions()');
@@ -209,7 +209,7 @@ class RecurrenceUpdateService
// First, make sure to loop all existing transactions and match them to a counterpart in the submitted transactions array. // First, make sure to loop all existing transactions and match them to a counterpart in the submitted transactions array.
foreach ($originalTransactions as $i => $originalTransaction) { foreach ($originalTransactions as $i => $originalTransaction) {
foreach ($transactions as $ii => $submittedTransaction) { foreach ($transactions as $ii => $submittedTransaction) {
if (array_key_exists('id', $submittedTransaction) && (int)$originalTransaction['id'] === (int)$submittedTransaction['id']) { if (array_key_exists('id', $submittedTransaction) && (int) $originalTransaction['id'] === (int) $submittedTransaction['id']) {
app('log')->debug(sprintf('Match original transaction #%d with an entry in the submitted array.', $originalTransaction['id'])); app('log')->debug(sprintf('Match original transaction #%d with an entry in the submitted array.', $originalTransaction['id']));
$combinations[] = [ $combinations[] = [
'original' => $originalTransaction, 'original' => $originalTransaction,
@@ -238,29 +238,34 @@ class RecurrenceUpdateService
// anything left in the original transactions array can be deleted. // anything left in the original transactions array can be deleted.
foreach ($originalTransactions as $original) { foreach ($originalTransactions as $original) {
app('log')->debug(sprintf('Original transaction #%d is unmatched, delete it!', $original['id'])); app('log')->debug(sprintf('Original transaction #%d is unmatched, delete it!', $original['id']));
$this->deleteTransaction($recurrence, (int)$original['id']); $this->deleteTransaction($recurrence, (int) $original['id']);
} }
// anything left is new. // anything left is new.
$this->createTransactions($recurrence, $transactions); $this->createTransactions($recurrence, $transactions);
} }
/**
* It's a complex method but nothing surprising.
*
* @SuppressWarnings(PHPMD.NPathComplexity)
* @SuppressWarnings(PHPMD.CyclomaticComplexity)
*/
private function updateCombination(Recurrence $recurrence, array $combination): void private function updateCombination(Recurrence $recurrence, array $combination): void
{ {
$original = $combination['original']; $original = $combination['original'];
$submitted = $combination['submitted']; $submitted = $combination['submitted'];
$currencyFactory = app(TransactionCurrencyFactory::class);
/** @var RecurrenceTransaction $transaction */ /** @var RecurrenceTransaction $transaction */
$transaction = $recurrence->recurrenceTransactions()->find($original['id']); $transaction = $recurrence->recurrenceTransactions()->find($original['id']);
app('log')->debug(sprintf('Now in updateCombination(#%d)', $original['id'])); app('log')->debug(sprintf('Now in updateCombination(#%d)', $original['id']));
$currencyFactory = app(TransactionCurrencyFactory::class);
// loop all and try to match them: // loop all and try to match them:
$currency = null; $currency = null;
$foreignCurrency = null; $foreignCurrency = null;
if (array_key_exists('currency_id', $submitted) || array_key_exists('currency_code', $submitted)) { if (array_key_exists('currency_id', $submitted) || array_key_exists('currency_code', $submitted)) {
$currency = $currencyFactory->find( $currency = $currencyFactory->find(
array_key_exists('currency_id', $submitted) ? (int)$submitted['currency_id'] : null, array_key_exists('currency_id', $submitted) ? (int) $submitted['currency_id'] : null,
array_key_exists('currency_code', $submitted) ? $submitted['currency_code'] : null array_key_exists('currency_code', $submitted) ? $submitted['currency_code'] : null
); );
} }
@@ -272,7 +277,7 @@ class RecurrenceUpdateService
} }
if (array_key_exists('foreign_currency_id', $submitted) || array_key_exists('foreign_currency_code', $submitted)) { if (array_key_exists('foreign_currency_id', $submitted) || array_key_exists('foreign_currency_code', $submitted)) {
$foreignCurrency = $currencyFactory->find( $foreignCurrency = $currencyFactory->find(
array_key_exists('foreign_currency_id', $submitted) ? (int)$submitted['foreign_currency_id'] : null, array_key_exists('foreign_currency_id', $submitted) ? (int) $submitted['foreign_currency_id'] : null,
array_key_exists('foreign_currency_code', $submitted) ? $submitted['foreign_currency_code'] : null array_key_exists('foreign_currency_code', $submitted) ? $submitted['foreign_currency_code'] : null
); );
} }
@@ -301,29 +306,29 @@ class RecurrenceUpdateService
} }
// update meta data // update meta data
if (array_key_exists('budget_id', $submitted)) { if (array_key_exists('budget_id', $submitted)) {
$this->setBudget($transaction, (int)$submitted['budget_id']); $this->setBudget($transaction, (int) $submitted['budget_id']);
} }
if (array_key_exists('bill_id', $submitted)) { if (array_key_exists('bill_id', $submitted)) {
$this->setBill($transaction, (int)$submitted['bill_id']); $this->setBill($transaction, (int) $submitted['bill_id']);
} }
// reset category if name is set but empty: // reset category if name is set but empty:
// can be removed when v1 is retired. // can be removed when v1 is retired.
if (array_key_exists('category_name', $submitted) && '' === (string)$submitted['category_name']) { if (array_key_exists('category_name', $submitted) && '' === (string) $submitted['category_name']) {
app('log')->debug('Category name is submitted but is empty. Set category to be empty.'); app('log')->debug('Category name is submitted but is empty. Set category to be empty.');
$submitted['category_name'] = null; $submitted['category_name'] = null;
$submitted['category_id'] = 0; $submitted['category_id'] = 0;
} }
if (array_key_exists('category_id', $submitted)) { if (array_key_exists('category_id', $submitted)) {
app('log')->debug(sprintf('Category ID is submitted, set category to be %d.', (int)$submitted['category_id'])); app('log')->debug(sprintf('Category ID is submitted, set category to be %d.', (int) $submitted['category_id']));
$this->setCategory($transaction, (int)$submitted['category_id']); $this->setCategory($transaction, (int) $submitted['category_id']);
} }
if (array_key_exists('tags', $submitted) && is_array($submitted['tags'])) { if (array_key_exists('tags', $submitted) && is_array($submitted['tags'])) {
$this->updateTags($transaction, $submitted['tags']); $this->updateTags($transaction, $submitted['tags']);
} }
if (array_key_exists('piggy_bank_id', $submitted)) { if (array_key_exists('piggy_bank_id', $submitted)) {
$this->updatePiggyBank($transaction, (int)$submitted['piggy_bank_id']); $this->updatePiggyBank($transaction, (int) $submitted['piggy_bank_id']);
} }
} }

View File

@@ -40,7 +40,7 @@ trait ChartGeneration
* Shows an overview of the account balances for a set of accounts. * Shows an overview of the account balances for a set of accounts.
* *
* @throws FireflyException * @throws FireflyException
* */ */
protected function accountBalanceChart(Collection $accounts, Carbon $start, Carbon $end): array // chart helper method. protected function accountBalanceChart(Collection $accounts, Carbon $start, Carbon $end): array // chart helper method.
{ {
// chart properties for cache: // chart properties for cache:

View File

@@ -70,6 +70,8 @@ class ParseDateString
/** /**
* @throws FireflyException * @throws FireflyException
*
* @SuppressWarnings(PHPMD.NPathComplexity)
*/ */
public function parseDate(string $date): Carbon public function parseDate(string $date): Carbon
{ {
@@ -82,7 +84,7 @@ class ParseDateString
// if regex for YYYY-MM-DD: // if regex for YYYY-MM-DD:
$pattern = '/^(19|20)\d\d-(0[1-9]|1[012])-(0[1-9]|[12]\d|3[01])$/'; $pattern = '/^(19|20)\d\d-(0[1-9]|1[012])-(0[1-9]|[12]\d|3[01])$/';
$result = preg_match($pattern, $date); $result = preg_match($pattern, $date);
if (false !== $result && 0 !== $result) { if (false !== $result && 0 !== $result) {
return $this->parseDefaultDate($date); return $this->parseDefaultDate($date);
} }
@@ -224,7 +226,7 @@ class ParseDateString
// verify if correct // verify if correct
$pattern = '/[+-]\d+[wqmdy]/'; $pattern = '/[+-]\d+[wqmdy]/';
$result = preg_match($pattern, $part); $result = preg_match($pattern, $part);
if (0 === $result || false === $result) { if (0 === $result || false === $result) {
app('log')->error(sprintf('Part "%s" does not match regular expression. Will be skipped.', $part)); app('log')->error(sprintf('Part "%s" does not match regular expression. Will be skipped.', $part));
@@ -280,7 +282,7 @@ class ParseDateString
{ {
// if regex for xxxx-MM-xx: // if regex for xxxx-MM-xx:
$pattern = '/^xxxx-(0[1-9]|1[012])-xx$/'; $pattern = '/^xxxx-(0[1-9]|1[012])-xx$/';
$result = preg_match($pattern, $date); $result = preg_match($pattern, $date);
if (false !== $result && 0 !== $result) { if (false !== $result && 0 !== $result) {
app('log')->debug(sprintf('"%s" is a month range.', $date)); app('log')->debug(sprintf('"%s" is a month range.', $date));
@@ -308,7 +310,7 @@ class ParseDateString
{ {
// if regex for YYYY-xx-xx: // if regex for YYYY-xx-xx:
$pattern = '/^(19|20)\d\d-xx-xx$/'; $pattern = '/^(19|20)\d\d-xx-xx$/';
$result = preg_match($pattern, $date); $result = preg_match($pattern, $date);
if (false !== $result && 0 !== $result) { if (false !== $result && 0 !== $result) {
app('log')->debug(sprintf('"%s" is a year range.', $date)); app('log')->debug(sprintf('"%s" is a year range.', $date));
@@ -336,7 +338,7 @@ class ParseDateString
{ {
// if regex for xxxx-MM-DD: // if regex for xxxx-MM-DD:
$pattern = '/^xxxx-(0[1-9]|1[012])-(0[1-9]|[12]\d|3[01])$/'; $pattern = '/^xxxx-(0[1-9]|1[012])-(0[1-9]|[12]\d|3[01])$/';
$result = preg_match($pattern, $date); $result = preg_match($pattern, $date);
if (false !== $result && 0 !== $result) { if (false !== $result && 0 !== $result) {
app('log')->debug(sprintf('"%s" is a month/day range.', $date)); app('log')->debug(sprintf('"%s" is a month/day range.', $date));
@@ -351,7 +353,7 @@ class ParseDateString
{ {
// if regex for YYYY-xx-DD: // if regex for YYYY-xx-DD:
$pattern = '/^(19|20)\d\d-xx-(0[1-9]|[12]\d|3[01])$/'; $pattern = '/^(19|20)\d\d-xx-(0[1-9]|[12]\d|3[01])$/';
$result = preg_match($pattern, $date); $result = preg_match($pattern, $date);
if (false !== $result && 0 !== $result) { if (false !== $result && 0 !== $result) {
app('log')->debug(sprintf('"%s" is a day/year range.', $date)); app('log')->debug(sprintf('"%s" is a day/year range.', $date));
@@ -366,7 +368,7 @@ class ParseDateString
{ {
// if regex for YYYY-MM-xx: // if regex for YYYY-MM-xx:
$pattern = '/^(19|20)\d\d-(0[1-9]|1[012])-xx$/'; $pattern = '/^(19|20)\d\d-(0[1-9]|1[012])-xx$/';
$result = preg_match($pattern, $date); $result = preg_match($pattern, $date);
if (false !== $result && 0 !== $result) { if (false !== $result && 0 !== $result) {
app('log')->debug(sprintf('"%s" is a month/year range.', $date)); app('log')->debug(sprintf('"%s" is a month/year range.', $date));

View File

@@ -134,7 +134,7 @@ class BudgetReportGenerator
/** /**
* @throws FireflyException * @throws FireflyException
* */ */
public function setUser(User $user): void public function setUser(User $user): void
{ {
$this->repository->setUser($user); $this->repository->setUser($user);

View File

@@ -30,60 +30,25 @@ trait GetRecurrenceData
{ {
protected function getSingleTransactionData(array $transaction): array protected function getSingleTransactionData(array $transaction): array
{ {
$return = []; $return = [];
$stringKeys = ['id'];
$intKeys = ['currency_id', 'foreign_currency_id', 'source_id', 'destination_id', 'bill_id', 'piggy_bank_id', 'bill_id', 'budget_id', 'category_id'];
$keys = ['amount', 'currency_code', 'foreign_amount', 'foreign_currency_code', 'description', 'tags'];
if (array_key_exists('id', $transaction)) { foreach ($stringKeys as $key) {
$return['id'] = (string)$transaction['id']; if (array_key_exists($key, $transaction)) {
$return[$key] = (string) $transaction[$key];
}
} }
foreach ($intKeys as $key) {
// amount + currency if (array_key_exists($key, $transaction)) {
if (array_key_exists('amount', $transaction)) { $return[$key] = (int) $transaction[$key];
$return['amount'] = $transaction['amount']; }
} }
if (array_key_exists('currency_id', $transaction)) { foreach ($keys as $key) {
$return['currency_id'] = (int)$transaction['currency_id']; if (array_key_exists($key, $transaction)) {
} $return[$key] = $transaction[$key];
if (array_key_exists('currency_code', $transaction)) { }
$return['currency_code'] = $transaction['currency_code'];
}
// foreign amount + currency
if (array_key_exists('foreign_amount', $transaction)) {
$return['foreign_amount'] = $transaction['foreign_amount'];
}
if (array_key_exists('foreign_currency_id', $transaction)) {
$return['foreign_currency_id'] = (int)$transaction['foreign_currency_id'];
}
if (array_key_exists('foreign_currency_code', $transaction)) {
$return['foreign_currency_code'] = $transaction['foreign_currency_code'];
}
// source + dest
if (array_key_exists('source_id', $transaction)) {
$return['source_id'] = (int)$transaction['source_id'];
}
if (array_key_exists('destination_id', $transaction)) {
$return['destination_id'] = (int)$transaction['destination_id'];
}
// description
if (array_key_exists('description', $transaction)) {
$return['description'] = $transaction['description'];
}
if (array_key_exists('piggy_bank_id', $transaction)) {
$return['piggy_bank_id'] = (int)$transaction['piggy_bank_id'];
}
if (array_key_exists('bill_id', $transaction)) {
$return['bill_id'] = (int)$transaction['bill_id'];
}
if (array_key_exists('tags', $transaction)) {
$return['tags'] = $transaction['tags'];
}
if (array_key_exists('budget_id', $transaction)) {
$return['budget_id'] = (int)$transaction['budget_id'];
}
if (array_key_exists('category_id', $transaction)) {
$return['category_id'] = (int)$transaction['category_id'];
} }
return $return; return $return;

View File

@@ -59,6 +59,8 @@ use Illuminate\Support\Collection;
/** /**
* Class OperatorQuerySearch * Class OperatorQuerySearch
*
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
*/ */
class OperatorQuerySearch implements SearchInterface class OperatorQuerySearch implements SearchInterface
{ {
@@ -69,8 +71,8 @@ class OperatorQuerySearch implements SearchInterface
private CategoryRepositoryInterface $categoryRepository; private CategoryRepositoryInterface $categoryRepository;
private GroupCollectorInterface $collector; private GroupCollectorInterface $collector;
private CurrencyRepositoryInterface $currencyRepository; private CurrencyRepositoryInterface $currencyRepository;
private array $excludeTags; private array $excludeTags;
private array $includeTags; private array $includeTags;
private array $invalidOperators; private array $invalidOperators;
private int $limit; private int $limit;
private Collection $operators; private Collection $operators;
@@ -231,7 +233,7 @@ class OperatorQuerySearch implements SearchInterface
$this->collector->setUser($user); $this->collector->setUser($user);
$this->collector->withAccountInformation()->withCategoryInformation()->withBudgetInformation(); $this->collector->withAccountInformation()->withCategoryInformation()->withBudgetInformation();
$this->setLimit((int)app('preferences')->getForUser($user, 'listPageSize', 50)->data); $this->setLimit((int) app('preferences')->getForUser($user, 'listPageSize', 50)->data);
} }
public function setLimit(int $limit): void public function setLimit(int $limit): void
@@ -242,6 +244,8 @@ class OperatorQuerySearch implements SearchInterface
/** /**
* @throws FireflyException * @throws FireflyException
*
* @SuppressWarnings(PHPMD.CyclomaticComplexity)
*/ */
private function handleSearchNode(Node $searchNode): void private function handleSearchNode(Node $searchNode): void
{ {
@@ -271,7 +275,7 @@ class OperatorQuerySearch implements SearchInterface
case Emoticon::class: case Emoticon::class:
case Emoji::class: case Emoji::class:
case Mention::class: case Mention::class:
$allWords = (string)$searchNode->getValue(); $allWords = (string) $searchNode->getValue();
app('log')->debug(sprintf('Add words "%s" to search string, because Node class is "%s"', $allWords, $class)); app('log')->debug(sprintf('Add words "%s" to search string, because Node class is "%s"', $allWords, $class));
$this->words[] = $allWords; $this->words[] = $allWords;
@@ -301,11 +305,11 @@ class OperatorQuerySearch implements SearchInterface
// must be valid operator: // must be valid operator:
if ( if (
in_array($operator, $this->validOperators, true) in_array($operator, $this->validOperators, true)
&& $this->updateCollector($operator, (string)$value, $prohibited)) { && $this->updateCollector($operator, (string) $value, $prohibited)) {
$this->operators->push( $this->operators->push(
[ [
'type' => self::getRootOperator($operator), 'type' => self::getRootOperator($operator),
'value' => (string)$value, 'value' => (string) $value,
'prohibited' => $prohibited, 'prohibited' => $prohibited,
] ]
); );
@@ -315,7 +319,7 @@ class OperatorQuerySearch implements SearchInterface
app('log')->debug(sprintf('Added INVALID operator type "%s"', $operator)); app('log')->debug(sprintf('Added INVALID operator type "%s"', $operator));
$this->invalidOperators[] = [ $this->invalidOperators[] = [
'type' => $operator, 'type' => $operator,
'value' => (string)$value, 'value' => (string) $value,
]; ];
} }
} }
@@ -325,6 +329,7 @@ class OperatorQuerySearch implements SearchInterface
* @throws FireflyException * @throws FireflyException
* *
* @SuppressWarnings(PHPMD.ExcessiveMethodLength) * @SuppressWarnings(PHPMD.ExcessiveMethodLength)
* @SuppressWarnings(PHPMD.CyclomaticComplexity)
*/ */
private function updateCollector(string $operator, string $value, bool $prohibited): bool private function updateCollector(string $operator, string $value, bool $prohibited): bool
{ {
@@ -514,7 +519,7 @@ class OperatorQuerySearch implements SearchInterface
break; break;
case 'source_account_id': case 'source_account_id':
$account = $this->accountRepository->find((int)$value); $account = $this->accountRepository->find((int) $value);
if (null !== $account) { if (null !== $account) {
$this->collector->setSourceAccounts(new Collection([$account])); $this->collector->setSourceAccounts(new Collection([$account]));
} }
@@ -526,7 +531,7 @@ class OperatorQuerySearch implements SearchInterface
break; break;
case '-source_account_id': case '-source_account_id':
$account = $this->accountRepository->find((int)$value); $account = $this->accountRepository->find((int) $value);
if (null !== $account) { if (null !== $account) {
$this->collector->excludeSourceAccounts(new Collection([$account])); $this->collector->excludeSourceAccounts(new Collection([$account]));
} }
@@ -642,7 +647,7 @@ class OperatorQuerySearch implements SearchInterface
break; break;
case 'destination_account_id': case 'destination_account_id':
$account = $this->accountRepository->find((int)$value); $account = $this->accountRepository->find((int) $value);
if (null !== $account) { if (null !== $account) {
$this->collector->setDestinationAccounts(new Collection([$account])); $this->collector->setDestinationAccounts(new Collection([$account]));
} }
@@ -653,7 +658,7 @@ class OperatorQuerySearch implements SearchInterface
break; break;
case '-destination_account_id': case '-destination_account_id':
$account = $this->accountRepository->find((int)$value); $account = $this->accountRepository->find((int) $value);
if (null !== $account) { if (null !== $account) {
$this->collector->excludeDestinationAccounts(new Collection([$account])); $this->collector->excludeDestinationAccounts(new Collection([$account]));
} }
@@ -667,7 +672,7 @@ class OperatorQuerySearch implements SearchInterface
$parts = explode(',', $value); $parts = explode(',', $value);
$collection = new Collection(); $collection = new Collection();
foreach ($parts as $accountId) { foreach ($parts as $accountId) {
$account = $this->accountRepository->find((int)$accountId); $account = $this->accountRepository->find((int) $accountId);
if (null !== $account) { if (null !== $account) {
$collection->push($account); $collection->push($account);
} }
@@ -685,7 +690,7 @@ class OperatorQuerySearch implements SearchInterface
$parts = explode(',', $value); $parts = explode(',', $value);
$collection = new Collection(); $collection = new Collection();
foreach ($parts as $accountId) { foreach ($parts as $accountId) {
$account = $this->accountRepository->find((int)$accountId); $account = $this->accountRepository->find((int) $accountId);
if (null !== $account) { if (null !== $account) {
$collection->push($account); $collection->push($account);
} }
@@ -1974,6 +1979,7 @@ class OperatorQuerySearch implements SearchInterface
* stringPosition: 1 = start (default), 2 = end, 3 = contains, 4 = is * stringPosition: 1 = start (default), 2 = end, 3 = contains, 4 = is
* *
* @SuppressWarnings(PHPMD.BooleanArgumentFlag) * @SuppressWarnings(PHPMD.BooleanArgumentFlag)
* @SuppressWarnings(PHPMD.NPathComplexity)
*/ */
private function searchAccountNr(string $value, SearchDirection $searchDirection, StringPosition $stringPosition, bool $prohibited = false): void private function searchAccountNr(string $value, SearchDirection $searchDirection, StringPosition $stringPosition, bool $prohibited = false): void
{ {
@@ -2033,7 +2039,7 @@ class OperatorQuerySearch implements SearchInterface
$filtered = $accounts->filter( $filtered = $accounts->filter(
static function (Account $account) use ($value, $stringMethod) { static function (Account $account) use ($value, $stringMethod) {
// either IBAN or account number // either IBAN or account number
$ibanMatch = $stringMethod(strtolower((string)$account->iban), strtolower($value)); $ibanMatch = $stringMethod(strtolower((string) $account->iban), strtolower($value));
$accountNrMatch = false; $accountNrMatch = false;
/** @var AccountMeta $meta */ /** @var AccountMeta $meta */

View File

@@ -87,7 +87,7 @@ class Steam
* [yyyy-mm-dd] => 123,2 * [yyyy-mm-dd] => 123,2
* *
* @throws FireflyException * @throws FireflyException
* */ */
public function balanceInRange(Account $account, Carbon $start, Carbon $end, ?TransactionCurrency $currency = null): array public function balanceInRange(Account $account, Carbon $start, Carbon $end, ?TransactionCurrency $currency = null): array
{ {
$cache = new CacheProperties(); $cache = new CacheProperties();

View File

@@ -29,7 +29,6 @@ use FireflyIII\Repositories\Account\AccountRepositoryInterface;
use FireflyIII\Repositories\User\UserRepositoryInterface; use FireflyIII\Repositories\User\UserRepositoryInterface;
use FireflyIII\Support\Search\OperatorQuerySearch; use FireflyIII\Support\Search\OperatorQuerySearch;
use League\CommonMark\GithubFlavoredMarkdownConverter; use League\CommonMark\GithubFlavoredMarkdownConverter;
use Route;
use Twig\Extension\AbstractExtension; use Twig\Extension\AbstractExtension;
use Twig\TwigFilter; use Twig\TwigFilter;
use Twig\TwigFunction; use Twig\TwigFunction;
@@ -111,6 +110,8 @@ class General extends AbstractExtension
/** /**
* Show icon with attachment. * Show icon with attachment.
*
* @SuppressWarnings(PHPMD.CyclomaticComplexity)
*/ */
protected function mimeIcon(): TwigFilter protected function mimeIcon(): TwigFilter
{ {
@@ -205,7 +206,7 @@ class General extends AbstractExtension
] ]
); );
return (string)$converter->convert($text); return (string) $converter->convert($text);
}, },
['is_safe' => ['html']] ['is_safe' => ['html']]
); );
@@ -219,8 +220,8 @@ class General extends AbstractExtension
return new TwigFilter( return new TwigFilter(
'phphost', 'phphost',
static function (string $string): string { static function (string $string): string {
$proto = (string)parse_url($string, PHP_URL_SCHEME); $proto = (string) parse_url($string, PHP_URL_SCHEME);
$host = (string)parse_url($string, PHP_URL_HOST); $host = (string) parse_url($string, PHP_URL_HOST);
return e(sprintf('%s://%s', $proto, $host)); return e(sprintf('%s://%s', $proto, $host));
} }

View File

@@ -121,7 +121,7 @@ class ConvertToDeposit implements ActionInterface
* Is converted to a deposit from C to A. * Is converted to a deposit from C to A.
* *
* @throws FireflyException * @throws FireflyException
* */ */
private function convertWithdrawalArray(TransactionJournal $journal): bool private function convertWithdrawalArray(TransactionJournal $journal): bool
{ {
$user = $journal->user; $user = $journal->user;
@@ -210,7 +210,7 @@ class ConvertToDeposit implements ActionInterface
* The source account is replaced. * The source account is replaced.
* *
* @throws FireflyException * @throws FireflyException
* */ */
private function convertTransferArray(TransactionJournal $journal): bool private function convertTransferArray(TransactionJournal $journal): bool
{ {
$user = $journal->user; $user = $journal->user;

View File

@@ -51,6 +51,7 @@ class ConvertToTransfer implements ActionInterface
/** /**
* @SuppressWarnings(PHPMD.ExcessiveMethodLength) * @SuppressWarnings(PHPMD.ExcessiveMethodLength)
* @SuppressWarnings(PHPMD.NPathComplexity)
*/ */
public function actOnArray(array $journal): bool public function actOnArray(array $journal): bool
{ {

View File

@@ -116,7 +116,7 @@ class ConvertToWithdrawal implements ActionInterface
/** /**
* @throws FireflyException * @throws FireflyException
* */ */
private function convertDepositArray(TransactionJournal $journal): bool private function convertDepositArray(TransactionJournal $journal): bool
{ {
$user = $journal->user; $user = $journal->user;
@@ -202,7 +202,7 @@ class ConvertToWithdrawal implements ActionInterface
* Output is a withdrawal from A to C. * Output is a withdrawal from A to C.
* *
* @throws FireflyException * @throws FireflyException
* */ */
private function convertTransferArray(TransactionJournal $journal): bool private function convertTransferArray(TransactionJournal $journal): bool
{ {
// find or create expense account. // find or create expense account.

View File

@@ -49,7 +49,7 @@ class AccountTransformer extends AbstractTransformer
* Transform the account. * Transform the account.
* *
* @throws FireflyException * @throws FireflyException
* */ */
public function transform(Account $account): array public function transform(Account $account): array
{ {
$this->repository->setUser($account->user); $this->repository->setUser($account->user);
@@ -156,7 +156,7 @@ class AccountTransformer extends AbstractTransformer
/** /**
* @throws FireflyException * @throws FireflyException
* */ */
private function getCurrency(Account $account): array private function getCurrency(Account $account): array
{ {
$currency = $this->repository->getAccountCurrency($account); $currency = $this->repository->getAccountCurrency($account);

View File

@@ -53,6 +53,7 @@ class BillTransformer extends AbstractTransformer
* Transform the bill. * Transform the bill.
* *
* @SuppressWarnings(PHPMD.ExcessiveMethodLength) * @SuppressWarnings(PHPMD.ExcessiveMethodLength)
* @SuppressWarnings(PHPMD.NPathComplexity)
*/ */
public function transform(Bill $bill): array public function transform(Bill $bill): array
{ {

View File

@@ -49,7 +49,7 @@ class PiggyBankEventTransformer extends AbstractTransformer
* Convert piggy bank event. * Convert piggy bank event.
* *
* @throws FireflyException * @throws FireflyException
* */ */
public function transform(PiggyBankEvent $event): array public function transform(PiggyBankEvent $event): array
{ {
// get account linked to piggy bank // get account linked to piggy bank

View File

@@ -50,7 +50,7 @@ class PiggyBankTransformer extends AbstractTransformer
* Transform the piggy bank. * Transform the piggy bank.
* *
* @throws FireflyException * @throws FireflyException
* */ */
public function transform(PiggyBank $piggyBank): array public function transform(PiggyBank $piggyBank): array
{ {
$account = $piggyBank->account; $account = $piggyBank->account;

View File

@@ -139,7 +139,7 @@ class PiggyBankTransformer extends AbstractTransformer
* Transform the piggy bank. * Transform the piggy bank.
* *
* @throws FireflyException * @throws FireflyException
* */ */
public function transform(PiggyBank $piggyBank): array public function transform(PiggyBank $piggyBank): array
{ {
// $account = $piggyBank->account; // $account = $piggyBank->account;

View File

@@ -76,6 +76,8 @@ use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
/** /**
* Class User. * Class User.
* *
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
*
* @property int|string $id * @property int|string $id
* @property string $email * @property string $email
* @property bool $isAdmin * @property bool $isAdmin

View File

@@ -45,7 +45,7 @@ trait DepositValidation
if (null === $accountId && null === $accountName && null === $accountIban && false === $this->canCreateTypes($validTypes)) { if (null === $accountId && null === $accountName && null === $accountIban && false === $this->canCreateTypes($validTypes)) {
// if both values are NULL we return false, // if both values are NULL we return false,
// because the destination of a deposit can't be created. // because the destination of a deposit can't be created.
$this->destError = (string)trans('validation.deposit_dest_need_data'); $this->destError = (string) trans('validation.deposit_dest_need_data');
app('log')->error('Both values are NULL, cant create deposit destination.'); app('log')->error('Both values are NULL, cant create deposit destination.');
$result = false; $result = false;
} }
@@ -60,7 +60,7 @@ trait DepositValidation
$search = $this->findExistingAccount($validTypes, $array); $search = $this->findExistingAccount($validTypes, $array);
if (null === $search) { if (null === $search) {
app('log')->debug('findExistingAccount() returned NULL, so the result is false.'); app('log')->debug('findExistingAccount() returned NULL, so the result is false.');
$this->destError = (string)trans('validation.deposit_dest_bad_data', ['id' => $accountId, 'name' => $accountName]); $this->destError = (string) trans('validation.deposit_dest_bad_data', ['id' => $accountId, 'name' => $accountName]);
$result = false; $result = false;
} }
if (null !== $search) { if (null !== $search) {
@@ -78,6 +78,12 @@ trait DepositValidation
abstract protected function findExistingAccount(array $validTypes, array $data): ?Account; abstract protected function findExistingAccount(array $validTypes, array $data): ?Account;
/**
* Pretty complex unfortunately.
*
* @SuppressWarnings(PHPMD.NPathComplexity)
* @SuppressWarnings(PHPMD.CyclomaticComplexity)
*/
protected function validateDepositSource(array $array): bool protected function validateDepositSource(array $array): bool
{ {
$accountId = array_key_exists('id', $array) ? $array['id'] : null; $accountId = array_key_exists('id', $array) ? $array['id'] : null;
@@ -100,7 +106,7 @@ trait DepositValidation
// if both values are NULL return false, // if both values are NULL return false,
// because the source of a deposit can't be created. // because the source of a deposit can't be created.
// (this never happens). // (this never happens).
$this->sourceError = (string)trans('validation.deposit_source_need_data'); $this->sourceError = (string) trans('validation.deposit_source_need_data');
$result = false; $result = false;
} }
@@ -109,7 +115,7 @@ trait DepositValidation
app('log')->debug('Check if there is not already another account with this IBAN'); app('log')->debug('Check if there is not already another account with this IBAN');
$existing = $this->findExistingAccount($validTypes, ['iban' => $accountIban], true); $existing = $this->findExistingAccount($validTypes, ['iban' => $accountIban], true);
if (null !== $existing) { if (null !== $existing) {
$this->sourceError = (string)trans('validation.deposit_src_iban_exists'); $this->sourceError = (string) trans('validation.deposit_src_iban_exists');
return false; return false;
} }

View File

@@ -247,7 +247,11 @@ class AccountValidator
} }
/** /**
* It's a long and fairly complex method, but I don't mind.
*
* @SuppressWarnings(PHPMD.CyclomaticComplexity)
* @SuppressWarnings(PHPMD.BooleanArgumentFlag) * @SuppressWarnings(PHPMD.BooleanArgumentFlag)
* @SuppressWarnings(PHPMD.NPathComplexity)
*/ */
protected function findExistingAccount(array $validTypes, array $data, bool $inverse = false): ?Account protected function findExistingAccount(array $validTypes, array $data, bool $inverse = false): ?Account
{ {

View File

@@ -30,39 +30,42 @@ use Illuminate\Validation\Validator;
*/ */
trait ValidatesAutoBudgetRequest trait ValidatesAutoBudgetRequest
{ {
/**
* @SuppressWarnings(PHPMD.NPathComplexity)
*/
protected function validateAutoBudgetAmount(Validator $validator): void protected function validateAutoBudgetAmount(Validator $validator): void
{ {
$data = $validator->getData(); $data = $validator->getData();
$type = $data['auto_budget_type'] ?? ''; $type = $data['auto_budget_type'] ?? '';
$amount = array_key_exists('auto_budget_amount', $data) ? $data['auto_budget_amount'] : null; $amount = array_key_exists('auto_budget_amount', $data) ? $data['auto_budget_amount'] : null;
$period = array_key_exists('auto_budget_period', $data) ? $data['auto_budget_period'] : null; $period = array_key_exists('auto_budget_period', $data) ? $data['auto_budget_period'] : null;
$currencyId = array_key_exists('auto_budget_currency_id', $data) ? (int)$data['auto_budget_currency_id'] : null; $currencyId = array_key_exists('auto_budget_currency_id', $data) ? (int) $data['auto_budget_currency_id'] : null;
$currencyCode = array_key_exists('auto_budget_currency_code', $data) ? $data['auto_budget_currency_code'] : null; $currencyCode = array_key_exists('auto_budget_currency_code', $data) ? $data['auto_budget_currency_code'] : null;
if (is_numeric($type)) { if (is_numeric($type)) {
$type = (int)$type; $type = (int) $type;
} }
if ('' === $type || 0 === $type) { if ('' === $type || 0 === $type) {
return; return;
} }
// basic float check: // basic float check:
if (!is_numeric($amount)) { if (!is_numeric($amount)) {
$validator->errors()->add('auto_budget_amount', (string)trans('validation.amount_required_for_auto_budget')); $validator->errors()->add('auto_budget_amount', (string) trans('validation.amount_required_for_auto_budget'));
return; return;
} }
if (1 !== bccomp((string)$amount, '0')) { if (1 !== bccomp((string) $amount, '0')) {
$validator->errors()->add('auto_budget_amount', (string)trans('validation.auto_budget_amount_positive')); $validator->errors()->add('auto_budget_amount', (string) trans('validation.auto_budget_amount_positive'));
} }
if ('' === $period) { if ('' === $period) {
$validator->errors()->add('auto_budget_period', (string)trans('validation.auto_budget_period_mandatory')); $validator->errors()->add('auto_budget_period', (string) trans('validation.auto_budget_period_mandatory'));
} }
if (null !== $currencyId && null !== $currencyCode && '' === $currencyCode && 0 === $currencyId) { if (null !== $currencyId && null !== $currencyCode && '' === $currencyCode && 0 === $currencyId) {
$validator->errors()->add('auto_budget_amount', (string)trans('validation.require_currency_info')); $validator->errors()->add('auto_budget_amount', (string) trans('validation.require_currency_info'));
} }
// too big amount // too big amount
if ((int)$amount > 268435456) { if ((int) $amount > 268435456) {
$validator->errors()->add('auto_budget_amount', (string)trans('validation.amount_required_for_auto_budget')); $validator->errors()->add('auto_budget_amount', (string) trans('validation.amount_required_for_auto_budget'));
return; return;
} }

View File

@@ -88,7 +88,7 @@ trait RecurrenceValidation
continue; continue;
} }
// validate source account. // validate source account.
$sourceId = array_key_exists('source_id', $transaction) ? (int)$transaction['source_id'] : null; $sourceId = array_key_exists('source_id', $transaction) ? (int) $transaction['source_id'] : null;
$sourceName = $transaction['source_name'] ?? null; $sourceName = $transaction['source_name'] ?? null;
$validSource = $accountValidator->validateSource(['id' => $sourceId, 'name' => $sourceName]); $validSource = $accountValidator->validateSource(['id' => $sourceId, 'name' => $sourceName]);
@@ -100,7 +100,7 @@ trait RecurrenceValidation
return; return;
} }
// validate destination account // validate destination account
$destinationId = array_key_exists('destination_id', $transaction) ? (int)$transaction['destination_id'] : null; $destinationId = array_key_exists('destination_id', $transaction) ? (int) $transaction['destination_id'] : null;
$destinationName = $transaction['destination_name'] ?? null; $destinationName = $transaction['destination_name'] ?? null;
$validDestination = $accountValidator->validateDestination(['id' => $destinationId, 'name' => $destinationName]); $validDestination = $accountValidator->validateDestination(['id' => $destinationId, 'name' => $destinationName]);
// do something with result: // do something with result:
@@ -122,7 +122,7 @@ trait RecurrenceValidation
$repetitions = $data['repetitions'] ?? []; $repetitions = $data['repetitions'] ?? [];
// need at least one transaction // need at least one transaction
if (!is_countable($repetitions) || 0 === count($repetitions)) { if (!is_countable($repetitions) || 0 === count($repetitions)) {
$validator->errors()->add('repetitions', (string)trans('validation.at_least_one_repetition')); $validator->errors()->add('repetitions', (string) trans('validation.at_least_one_repetition'));
} }
} }
@@ -138,7 +138,7 @@ trait RecurrenceValidation
} }
// need at least one transaction // need at least one transaction
if (0 === count($repetitions)) { if (0 === count($repetitions)) {
$validator->errors()->add('repetitions', (string)trans('validation.at_least_one_repetition')); $validator->errors()->add('repetitions', (string) trans('validation.at_least_one_repetition'));
} }
} }
@@ -153,15 +153,15 @@ trait RecurrenceValidation
$repeatUntil = $data['repeat_until'] ?? null; $repeatUntil = $data['repeat_until'] ?? null;
if (null !== $repetitions && null !== $repeatUntil) { if (null !== $repetitions && null !== $repeatUntil) {
// expect a date OR count: // expect a date OR count:
$validator->errors()->add('repeat_until', (string)trans('validation.require_repeat_until')); $validator->errors()->add('repeat_until', (string) trans('validation.require_repeat_until'));
$validator->errors()->add('nr_of_repetitions', (string)trans('validation.require_repeat_until')); $validator->errors()->add('nr_of_repetitions', (string) trans('validation.require_repeat_until'));
} }
} }
public function validateRecurringConfig(Validator $validator): void public function validateRecurringConfig(Validator $validator): void
{ {
$data = $validator->getData(); $data = $validator->getData();
$reps = array_key_exists('nr_of_repetitions', $data) ? (int)$data['nr_of_repetitions'] : null; $reps = array_key_exists('nr_of_repetitions', $data) ? (int) $data['nr_of_repetitions'] : null;
$repeatUntil = array_key_exists('repeat_until', $data) ? new Carbon($data['repeat_until']) : null; $repeatUntil = array_key_exists('repeat_until', $data) ? new Carbon($data['repeat_until']) : null;
if (null === $reps && null === $repeatUntil) { if (null === $reps && null === $repeatUntil) {
@@ -181,7 +181,7 @@ trait RecurrenceValidation
$data = $validator->getData(); $data = $validator->getData();
$repetitions = $data['repetitions'] ?? []; $repetitions = $data['repetitions'] ?? [];
if (!is_array($repetitions)) { if (!is_array($repetitions)) {
$validator->errors()->add(sprintf('repetitions.%d.type', 0), (string)trans('validation.valid_recurrence_rep_type')); $validator->errors()->add(sprintf('repetitions.%d.type', 0), (string) trans('validation.valid_recurrence_rep_type'));
return; return;
} }
@@ -200,32 +200,32 @@ trait RecurrenceValidation
switch ($repetition['type'] ?? 'empty') { switch ($repetition['type'] ?? 'empty') {
default: default:
$validator->errors()->add(sprintf('repetitions.%d.type', $index), (string)trans('validation.valid_recurrence_rep_type')); $validator->errors()->add(sprintf('repetitions.%d.type', $index), (string) trans('validation.valid_recurrence_rep_type'));
return; return;
case 'daily': case 'daily':
$this->validateDaily($validator, $index, (string)$repetition['moment']); $this->validateDaily($validator, $index, (string) $repetition['moment']);
break; break;
case 'monthly': case 'monthly':
$this->validateMonthly($validator, $index, (int)$repetition['moment']); $this->validateMonthly($validator, $index, (int) $repetition['moment']);
break; break;
case 'ndom': case 'ndom':
$this->validateNdom($validator, $index, (string)$repetition['moment']); $this->validateNdom($validator, $index, (string) $repetition['moment']);
break; break;
case 'weekly': case 'weekly':
$this->validateWeekly($validator, $index, (int)$repetition['moment']); $this->validateWeekly($validator, $index, (int) $repetition['moment']);
break; break;
case 'yearly': case 'yearly':
$this->validateYearly($validator, $index, (string)$repetition['moment']); $this->validateYearly($validator, $index, (string) $repetition['moment']);
break; break;
} }
@@ -238,7 +238,7 @@ trait RecurrenceValidation
protected function validateDaily(Validator $validator, int $index, string $moment): void protected function validateDaily(Validator $validator, int $index, string $moment): void
{ {
if ('' !== $moment) { if ('' !== $moment) {
$validator->errors()->add(sprintf('repetitions.%d.moment', $index), (string)trans('validation.valid_recurrence_rep_moment')); $validator->errors()->add(sprintf('repetitions.%d.moment', $index), (string) trans('validation.valid_recurrence_rep_moment'));
} }
} }
@@ -248,7 +248,7 @@ trait RecurrenceValidation
protected function validateMonthly(Validator $validator, int $index, int $dayOfMonth): void protected function validateMonthly(Validator $validator, int $index, int $dayOfMonth): void
{ {
if ($dayOfMonth < 1 || $dayOfMonth > 31) { if ($dayOfMonth < 1 || $dayOfMonth > 31) {
$validator->errors()->add(sprintf('repetitions.%d.moment', $index), (string)trans('validation.valid_recurrence_rep_moment')); $validator->errors()->add(sprintf('repetitions.%d.moment', $index), (string) trans('validation.valid_recurrence_rep_moment'));
} }
} }
@@ -260,19 +260,19 @@ trait RecurrenceValidation
{ {
$parameters = explode(',', $moment); $parameters = explode(',', $moment);
if (2 !== count($parameters)) { if (2 !== count($parameters)) {
$validator->errors()->add(sprintf('repetitions.%d.moment', $index), (string)trans('validation.valid_recurrence_rep_moment')); $validator->errors()->add(sprintf('repetitions.%d.moment', $index), (string) trans('validation.valid_recurrence_rep_moment'));
return; return;
} }
$nthDay = (int)($parameters[0] ?? 0.0); $nthDay = (int) ($parameters[0] ?? 0.0);
$dayOfWeek = (int)($parameters[1] ?? 0.0); $dayOfWeek = (int) ($parameters[1] ?? 0.0);
if ($nthDay < 1 || $nthDay > 5) { if ($nthDay < 1 || $nthDay > 5) {
$validator->errors()->add(sprintf('repetitions.%d.moment', $index), (string)trans('validation.valid_recurrence_rep_moment')); $validator->errors()->add(sprintf('repetitions.%d.moment', $index), (string) trans('validation.valid_recurrence_rep_moment'));
return; return;
} }
if ($dayOfWeek < 1 || $dayOfWeek > 7) { if ($dayOfWeek < 1 || $dayOfWeek > 7) {
$validator->errors()->add(sprintf('repetitions.%d.moment', $index), (string)trans('validation.valid_recurrence_rep_moment')); $validator->errors()->add(sprintf('repetitions.%d.moment', $index), (string) trans('validation.valid_recurrence_rep_moment'));
} }
} }
@@ -282,7 +282,7 @@ trait RecurrenceValidation
protected function validateWeekly(Validator $validator, int $index, int $dayOfWeek): void protected function validateWeekly(Validator $validator, int $index, int $dayOfWeek): void
{ {
if ($dayOfWeek < 1 || $dayOfWeek > 7) { if ($dayOfWeek < 1 || $dayOfWeek > 7) {
$validator->errors()->add(sprintf('repetitions.%d.moment', $index), (string)trans('validation.valid_recurrence_rep_moment')); $validator->errors()->add(sprintf('repetitions.%d.moment', $index), (string) trans('validation.valid_recurrence_rep_moment'));
} }
} }
@@ -295,10 +295,13 @@ trait RecurrenceValidation
Carbon::createFromFormat('Y-m-d', $moment); Carbon::createFromFormat('Y-m-d', $moment);
} catch (\InvalidArgumentException $e) { // @phpstan-ignore-line } catch (\InvalidArgumentException $e) { // @phpstan-ignore-line
app('log')->debug(sprintf('Invalid argument for Carbon: %s', $e->getMessage())); app('log')->debug(sprintf('Invalid argument for Carbon: %s', $e->getMessage()));
$validator->errors()->add(sprintf('repetitions.%d.moment', $index), (string)trans('validation.valid_recurrence_rep_moment')); $validator->errors()->add(sprintf('repetitions.%d.moment', $index), (string) trans('validation.valid_recurrence_rep_moment'));
} }
} }
/**
* @SuppressWarnings(PHPMD.NPathComplexity)
*/
protected function validateTransactionId(Recurrence $recurrence, Validator $validator): void protected function validateTransactionId(Recurrence $recurrence, Validator $validator): void
{ {
app('log')->debug('Now in validateTransactionId'); app('log')->debug('Now in validateTransactionId');
@@ -307,7 +310,7 @@ trait RecurrenceValidation
if (0 === $submittedTrCount) { if (0 === $submittedTrCount) {
app('log')->warning('[b] User submitted no transactions.'); app('log')->warning('[b] User submitted no transactions.');
$validator->errors()->add('transactions', (string)trans('validation.at_least_one_transaction')); $validator->errors()->add('transactions', (string) trans('validation.at_least_one_transaction'));
return; return;
} }
@@ -320,16 +323,16 @@ trait RecurrenceValidation
return; // home safe! return; // home safe!
} }
$id = $first['id']; $id = $first['id'];
if ('' === (string)$id) { if ('' === (string) $id) {
app('log')->debug('Single count and empty ID, done.'); app('log')->debug('Single count and empty ID, done.');
return; // home safe! return; // home safe!
} }
$integer = (int)$id; $integer = (int) $id;
$secondCount = $recurrence->recurrenceTransactions()->where('recurrences_transactions.id', $integer)->count(); $secondCount = $recurrence->recurrenceTransactions()->where('recurrences_transactions.id', $integer)->count();
app('log')->debug(sprintf('Result of ID count: %d', $secondCount)); app('log')->debug(sprintf('Result of ID count: %d', $secondCount));
if (0 === $secondCount) { if (0 === $secondCount) {
$validator->errors()->add('transactions.0.id', (string)trans('validation.id_does_not_match', ['id' => $integer])); $validator->errors()->add('transactions.0.id', (string) trans('validation.id_does_not_match', ['id' => $integer]));
} }
app('log')->debug('Single ID validation done.'); app('log')->debug('Single ID validation done.');
@@ -360,19 +363,19 @@ trait RecurrenceValidation
app('log')->debug(sprintf('Now at %d/%d', $index + 1, $submittedTrCount)); app('log')->debug(sprintf('Now at %d/%d', $index + 1, $submittedTrCount));
if (!is_array($transaction)) { if (!is_array($transaction)) {
app('log')->warning('Not an array. Give error.'); app('log')->warning('Not an array. Give error.');
$validator->errors()->add(sprintf('transactions.%d.id', $index), (string)trans('validation.at_least_one_transaction')); $validator->errors()->add(sprintf('transactions.%d.id', $index), (string) trans('validation.at_least_one_transaction'));
return; return;
} }
if (!array_key_exists('id', $transaction) && $idsMandatory) { if (!array_key_exists('id', $transaction) && $idsMandatory) {
app('log')->warning('ID is mandatory but array has no ID.'); app('log')->warning('ID is mandatory but array has no ID.');
$validator->errors()->add(sprintf('transactions.%d.id', $index), (string)trans('validation.need_id_to_match')); $validator->errors()->add(sprintf('transactions.%d.id', $index), (string) trans('validation.need_id_to_match'));
return; return;
} }
if (array_key_exists('id', $transaction)) { // don't matter if $idsMandatory if (array_key_exists('id', $transaction)) { // don't matter if $idsMandatory
app('log')->debug('Array has ID.'); app('log')->debug('Array has ID.');
$idCount = $recurrence->recurrenceTransactions()->where('recurrences_transactions.id', (int)$transaction['id'])->count(); $idCount = $recurrence->recurrenceTransactions()->where('recurrences_transactions.id', (int) $transaction['id'])->count();
if (0 === $idCount) { if (0 === $idCount) {
app('log')->debug('ID does not exist or no match. Count another unmatched ID.'); app('log')->debug('ID does not exist or no match. Count another unmatched ID.');
++$unmatchedIds; ++$unmatchedIds;
@@ -388,7 +391,7 @@ trait RecurrenceValidation
app('log')->debug(sprintf('Submitted: %d. Original: %d. User can submit %d unmatched transactions.', $submittedTrCount, $originalTrCount, $maxUnmatched)); app('log')->debug(sprintf('Submitted: %d. Original: %d. User can submit %d unmatched transactions.', $submittedTrCount, $originalTrCount, $maxUnmatched));
if ($unmatchedIds > $maxUnmatched) { if ($unmatchedIds > $maxUnmatched) {
app('log')->warning(sprintf('Too many unmatched transactions (%d).', $unmatchedIds)); app('log')->warning(sprintf('Too many unmatched transactions (%d).', $unmatchedIds));
$validator->errors()->add('transactions.0.id', (string)trans('validation.too_many_unmatched')); $validator->errors()->add('transactions.0.id', (string) trans('validation.too_many_unmatched'));
return; return;
} }

View File

@@ -109,7 +109,7 @@ trait TransactionValidation
// need at least one transaction // need at least one transaction
if (0 === count($transactions)) { if (0 === count($transactions)) {
$validator->errors()->add('transactions', (string)trans('validation.at_least_one_transaction')); $validator->errors()->add('transactions', (string) trans('validation.at_least_one_transaction'));
} }
} }
@@ -127,7 +127,7 @@ trait TransactionValidation
$transactions = $this->getTransactionsArray($validator); $transactions = $this->getTransactionsArray($validator);
// need at least one transaction // need at least one transaction
if (0 === count($transactions)) { if (0 === count($transactions)) {
$validator->errors()->add('transactions.0.description', (string)trans('validation.at_least_one_transaction')); $validator->errors()->add('transactions.0.description', (string) trans('validation.at_least_one_transaction'));
app('log')->debug('Added error: at_least_one_transaction.'); app('log')->debug('Added error: at_least_one_transaction.');
return; return;
@@ -143,7 +143,7 @@ trait TransactionValidation
$transactions = $this->getTransactionsArray($validator); $transactions = $this->getTransactionsArray($validator);
foreach (array_keys($transactions) as $key) { foreach (array_keys($transactions) as $key) {
if (!is_int($key)) { if (!is_int($key)) {
$validator->errors()->add('transactions.0.description', (string)trans('validation.at_least_one_transaction')); $validator->errors()->add('transactions.0.description', (string) trans('validation.at_least_one_transaction'));
app('log')->debug('Added error: at_least_one_transaction.'); app('log')->debug('Added error: at_least_one_transaction.');
return; return;
@@ -168,13 +168,13 @@ trait TransactionValidation
} }
$unique = array_unique($types); $unique = array_unique($types);
if (count($unique) > 1) { if (count($unique) > 1) {
$validator->errors()->add('transactions.0.type', (string)trans('validation.transaction_types_equal')); $validator->errors()->add('transactions.0.type', (string) trans('validation.transaction_types_equal'));
return; return;
} }
$first = $unique[0] ?? 'invalid'; $first = $unique[0] ?? 'invalid';
if ('invalid' === $first) { if ('invalid' === $first) {
$validator->errors()->add('transactions.0.type', (string)trans('validation.invalid_transaction_type')); $validator->errors()->add('transactions.0.type', (string) trans('validation.invalid_transaction_type'));
} }
} }
@@ -187,14 +187,14 @@ trait TransactionValidation
$transactions = $this->getTransactionsArray($validator); $transactions = $this->getTransactionsArray($validator);
$types = []; $types = [];
foreach ($transactions as $transaction) { foreach ($transactions as $transaction) {
$originalType = $this->getOriginalType((int)($transaction['transaction_journal_id'] ?? 0)); $originalType = $this->getOriginalType((int) ($transaction['transaction_journal_id'] ?? 0));
// if type is not set, fall back to the type of the journal, if one is given. // if type is not set, fall back to the type of the journal, if one is given.
$types[] = $transaction['type'] ?? $originalType; $types[] = $transaction['type'] ?? $originalType;
} }
$unique = array_unique($types); $unique = array_unique($types);
if (count($unique) > 1) { if (count($unique) > 1) {
app('log')->warning('Add error for mismatch transaction types.'); app('log')->warning('Add error for mismatch transaction types.');
$validator->errors()->add('transactions.0.type', (string)trans('validation.transaction_types_equal')); $validator->errors()->add('transactions.0.type', (string) trans('validation.transaction_types_equal'));
return; return;
} }
@@ -217,6 +217,9 @@ trait TransactionValidation
return $transactions; return $transactions;
} }
/**
* @SuppressWarnings(PHPMD.NPathComplexity)
*/
protected function validateSingleAccount(Validator $validator, int $index, string $transactionType, array $transaction): void protected function validateSingleAccount(Validator $validator, int $index, string $transactionType, array $transaction): void
{ {
app('log')->debug(sprintf('Now in validateSingleAccount(%d)', $index)); app('log')->debug(sprintf('Now in validateSingleAccount(%d)', $index));
@@ -235,10 +238,10 @@ trait TransactionValidation
$accountValidator->setTransactionType($transactionType); $accountValidator->setTransactionType($transactionType);
// validate source account. // validate source account.
$sourceId = array_key_exists('source_id', $transaction) ? (int)$transaction['source_id'] : null; $sourceId = array_key_exists('source_id', $transaction) ? (int) $transaction['source_id'] : null;
$sourceName = array_key_exists('source_name', $transaction) ? (string)$transaction['source_name'] : null; $sourceName = array_key_exists('source_name', $transaction) ? (string) $transaction['source_name'] : null;
$sourceIban = array_key_exists('source_iban', $transaction) ? (string)$transaction['source_iban'] : null; $sourceIban = array_key_exists('source_iban', $transaction) ? (string) $transaction['source_iban'] : null;
$sourceNumber = array_key_exists('source_number', $transaction) ? (string)$transaction['source_number'] : null; $sourceNumber = array_key_exists('source_number', $transaction) ? (string) $transaction['source_number'] : null;
$source = [ $source = [
'id' => $sourceId, 'id' => $sourceId,
'name' => $sourceName, 'name' => $sourceName,
@@ -255,10 +258,10 @@ trait TransactionValidation
return; return;
} }
// validate destination account // validate destination account
$destinationId = array_key_exists('destination_id', $transaction) ? (int)$transaction['destination_id'] : null; $destinationId = array_key_exists('destination_id', $transaction) ? (int) $transaction['destination_id'] : null;
$destinationName = array_key_exists('destination_name', $transaction) ? (string)$transaction['destination_name'] : null; $destinationName = array_key_exists('destination_name', $transaction) ? (string) $transaction['destination_name'] : null;
$destinationIban = array_key_exists('destination_iban', $transaction) ? (string)$transaction['destination_iban'] : null; $destinationIban = array_key_exists('destination_iban', $transaction) ? (string) $transaction['destination_iban'] : null;
$destinationNumber = array_key_exists('destination_number', $transaction) ? (string)$transaction['destination_number'] : null; $destinationNumber = array_key_exists('destination_number', $transaction) ? (string) $transaction['destination_number'] : null;
$destination = [ $destination = [
'id' => $destinationId, 'id' => $destinationId,
'name' => $destinationName, 'name' => $destinationName,
@@ -335,7 +338,7 @@ trait TransactionValidation
|| array_key_exists('source_number', $transaction) || array_key_exists('source_number', $transaction)
) { ) {
app('log')->debug('Will try to validate source account information.'); app('log')->debug('Will try to validate source account information.');
$sourceId = (int)($transaction['source_id'] ?? 0); $sourceId = (int) ($transaction['source_id'] ?? 0);
$sourceName = $transaction['source_name'] ?? null; $sourceName = $transaction['source_name'] ?? null;
$sourceIban = $transaction['source_iban'] ?? null; $sourceIban = $transaction['source_iban'] ?? null;
$sourceNumber = $transaction['source_number'] ?? null; $sourceNumber = $transaction['source_number'] ?? null;
@@ -374,7 +377,7 @@ trait TransactionValidation
$accountValidator->source = $source; $accountValidator->source = $source;
} }
} }
$destinationId = (int)($transaction['destination_id'] ?? 0); $destinationId = (int) ($transaction['destination_id'] ?? 0);
$destinationName = $transaction['destination_name'] ?? null; $destinationName = $transaction['destination_name'] ?? null;
$destinationIban = $transaction['destination_iban'] ?? null; $destinationIban = $transaction['destination_iban'] ?? null;
$destinationNumber = $transaction['destination_number'] ?? null; $destinationNumber = $transaction['destination_number'] ?? null;
@@ -395,6 +398,7 @@ trait TransactionValidation
* TODO describe this method. * TODO describe this method.
* *
* @SuppressWarnings(PHPMD.ExcessiveParameterList) * @SuppressWarnings(PHPMD.ExcessiveParameterList)
* @SuppressWarnings(PHPMD.NPathComplexity)
*/ */
private function sanityCheckForeignCurrency( private function sanityCheckForeignCurrency(
Validator $validator, Validator $validator,
@@ -455,17 +459,17 @@ trait TransactionValidation
// no foreign currency information is present: // no foreign currency information is present:
if (!$this->hasForeignCurrencyInfo($transaction)) { if (!$this->hasForeignCurrencyInfo($transaction)) {
$validator->errors()->add(sprintf('transactions.%d.foreign_amount', $index), (string)trans('validation.require_foreign_currency')); $validator->errors()->add(sprintf('transactions.%d.foreign_amount', $index), (string) trans('validation.require_foreign_currency'));
return; return;
} }
// wrong currency information is present // wrong currency information is present
$foreignCurrencyCode = $transaction['foreign_currency_code'] ?? false; $foreignCurrencyCode = $transaction['foreign_currency_code'] ?? false;
$foreignCurrencyId = (int)($transaction['foreign_currency_id'] ?? 0); $foreignCurrencyId = (int) ($transaction['foreign_currency_id'] ?? 0);
app('log')->debug(sprintf('Foreign currency code seems to be #%d "%s"', $foreignCurrencyId, $foreignCurrencyCode), $transaction); app('log')->debug(sprintf('Foreign currency code seems to be #%d "%s"', $foreignCurrencyId, $foreignCurrencyCode), $transaction);
if ($foreignCurrencyCode !== $sourceCurrency->code && $foreignCurrencyId !== $sourceCurrency->id) { if ($foreignCurrencyCode !== $sourceCurrency->code && $foreignCurrencyId !== $sourceCurrency->id) {
$validator->errors()->add(sprintf('transactions.%d.foreign_currency_code', $index), (string)trans('validation.require_foreign_src')); $validator->errors()->add(sprintf('transactions.%d.foreign_currency_code', $index), (string) trans('validation.require_foreign_src'));
return; return;
} }
@@ -482,19 +486,19 @@ trait TransactionValidation
// no foreign currency information is present: // no foreign currency information is present:
if (!$this->hasForeignCurrencyInfo($transaction)) { if (!$this->hasForeignCurrencyInfo($transaction)) {
$validator->errors()->add(sprintf('transactions.%d.foreign_amount', $index), (string)trans('validation.require_foreign_currency')); $validator->errors()->add(sprintf('transactions.%d.foreign_amount', $index), (string) trans('validation.require_foreign_currency'));
return; return;
} }
// wrong currency information is present // wrong currency information is present
$foreignCurrencyCode = $transaction['foreign_currency_code'] ?? false; $foreignCurrencyCode = $transaction['foreign_currency_code'] ?? false;
$foreignCurrencyId = (int)($transaction['foreign_currency_id'] ?? 0); $foreignCurrencyId = (int) ($transaction['foreign_currency_id'] ?? 0);
app('log')->debug(sprintf('Foreign currency code seems to be #%d "%s"', $foreignCurrencyId, $foreignCurrencyCode), $transaction); app('log')->debug(sprintf('Foreign currency code seems to be #%d "%s"', $foreignCurrencyId, $foreignCurrencyCode), $transaction);
if ($foreignCurrencyCode !== $destinationCurrency->code && $foreignCurrencyId !== $destinationCurrency->id) { if ($foreignCurrencyCode !== $destinationCurrency->code && $foreignCurrencyId !== $destinationCurrency->id) {
app('log')->debug(sprintf('No match on code, "%s" vs "%s"', $foreignCurrencyCode, $destinationCurrency->code)); app('log')->debug(sprintf('No match on code, "%s" vs "%s"', $foreignCurrencyCode, $destinationCurrency->code));
app('log')->debug(sprintf('No match on ID, #%d vs #%d', $foreignCurrencyId, $destinationCurrency->id)); app('log')->debug(sprintf('No match on ID, #%d vs #%d', $foreignCurrencyId, $destinationCurrency->id));
$validator->errors()->add(sprintf('transactions.%d.foreign_amount', $index), (string)trans('validation.require_foreign_dest')); $validator->errors()->add(sprintf('transactions.%d.foreign_amount', $index), (string) trans('validation.require_foreign_dest'));
} }
} }
} }
@@ -541,7 +545,7 @@ trait TransactionValidation
private function getTransactionType(TransactionGroup $group, array $transactions): string private function getTransactionType(TransactionGroup $group, array $transactions): string
{ {
return $transactions[0]['type'] ?? strtolower((string)$group->transactionJournals()->first()?->transactionType->type); return $transactions[0]['type'] ?? strtolower((string) $group->transactionJournals()->first()?->transactionType->type);
} }
private function getOriginalSource(array $transaction, TransactionGroup $transactionGroup): ?Account private function getOriginalSource(array $transaction, TransactionGroup $transactionGroup): ?Account
@@ -554,7 +558,7 @@ trait TransactionValidation
/** @var TransactionJournal $journal */ /** @var TransactionJournal $journal */
foreach ($transactionGroup->transactionJournals as $journal) { foreach ($transactionGroup->transactionJournals as $journal) {
$journalId = (int)($transaction['transaction_journal_id'] ?? 0); $journalId = (int) ($transaction['transaction_journal_id'] ?? 0);
if ($journal->id === $journalId) { if ($journal->id === $journalId) {
return $journal->transactions()->where('amount', '<', 0)->first()?->account; return $journal->transactions()->where('amount', '<', 0)->first()?->account;
} }
@@ -604,22 +608,22 @@ trait TransactionValidation
default: default:
case 'withdrawal': case 'withdrawal':
if (count($sources) > 1) { if (count($sources) > 1) {
$validator->errors()->add('transactions.0.source_id', (string)trans('validation.all_accounts_equal')); $validator->errors()->add('transactions.0.source_id', (string) trans('validation.all_accounts_equal'));
} }
break; break;
case 'deposit': case 'deposit':
if (count($dests) > 1) { if (count($dests) > 1) {
$validator->errors()->add('transactions.0.destination_id', (string)trans('validation.all_accounts_equal')); $validator->errors()->add('transactions.0.destination_id', (string) trans('validation.all_accounts_equal'));
} }
break; break;
case'transfer': case'transfer':
if (count($sources) > 1 || count($dests) > 1) { if (count($sources) > 1 || count($dests) > 1) {
$validator->errors()->add('transactions.0.source_id', (string)trans('validation.all_accounts_equal')); $validator->errors()->add('transactions.0.source_id', (string) trans('validation.all_accounts_equal'));
$validator->errors()->add('transactions.0.destination_id', (string)trans('validation.all_accounts_equal')); $validator->errors()->add('transactions.0.destination_id', (string) trans('validation.all_accounts_equal'));
} }
break; break;
@@ -653,14 +657,14 @@ trait TransactionValidation
$result = $this->compareAccountData($type, $comparison); $result = $this->compareAccountData($type, $comparison);
if (false === $result) { if (false === $result) {
if ('withdrawal' === $type) { if ('withdrawal' === $type) {
$validator->errors()->add('transactions.0.source_id', (string)trans('validation.all_accounts_equal')); $validator->errors()->add('transactions.0.source_id', (string) trans('validation.all_accounts_equal'));
} }
if ('deposit' === $type) { if ('deposit' === $type) {
$validator->errors()->add('transactions.0.destination_id', (string)trans('validation.all_accounts_equal')); $validator->errors()->add('transactions.0.destination_id', (string) trans('validation.all_accounts_equal'));
} }
if ('transfer' === $type) { if ('transfer' === $type) {
$validator->errors()->add('transactions.0.source_id', (string)trans('validation.all_accounts_equal')); $validator->errors()->add('transactions.0.source_id', (string) trans('validation.all_accounts_equal'));
$validator->errors()->add('transactions.0.destination_id', (string)trans('validation.all_accounts_equal')); $validator->errors()->add('transactions.0.destination_id', (string) trans('validation.all_accounts_equal'));
} }
app('log')->warning('Add error about equal accounts.'); app('log')->warning('Add error about equal accounts.');
@@ -679,7 +683,7 @@ trait TransactionValidation
/** @var array $transaction */ /** @var array $transaction */
foreach ($transactions as $transaction) { foreach ($transactions as $transaction) {
// source or destination may be omitted. If this is the case, use the original source / destination name + ID. // source or destination may be omitted. If this is the case, use the original source / destination name + ID.
$originalData = $this->getOriginalData((int)($transaction['transaction_journal_id'] ?? 0)); $originalData = $this->getOriginalData((int) ($transaction['transaction_journal_id'] ?? 0));
// get field. // get field.
$comparison[$field][] = $transaction[$field] ?? $originalData[$field]; $comparison[$field][] = $transaction[$field] ?? $originalData[$field];

View File

@@ -527,6 +527,7 @@ class CreateMainTables extends Migration
/** /**
* @SuppressWarnings(PHPMD.ExcessiveMethodLength) * @SuppressWarnings(PHPMD.ExcessiveMethodLength)
* @SuppressWarnings(PHPMD.NPathComplexity)
*/ */
private function createTransactionTables(): void private function createTransactionTables(): void
{ {

View File

@@ -125,6 +125,7 @@ class ChangesForV550 extends Migration
* *
* @SuppressWarnings(PHPMD.ShortMethodName) * @SuppressWarnings(PHPMD.ShortMethodName)
* @SuppressWarnings(PHPMD.ExcessiveMethodLength) * @SuppressWarnings(PHPMD.ExcessiveMethodLength)
* @SuppressWarnings(PHPMD.NPathComplexity)
*/ */
public function up(): void public function up(): void
{ {