Reformat various code.

This commit is contained in:
James Cole
2022-03-29 15:00:29 +02:00
parent d1a09ff33b
commit d04efb8325
81 changed files with 662 additions and 662 deletions

View File

@@ -51,7 +51,7 @@ class Amount
*/ */
public function formatAnything(TransactionCurrency $format, string $amount, bool $coloured = null): string public function formatAnything(TransactionCurrency $format, string $amount, bool $coloured = null): string
{ {
return $this->formatFlat($format->symbol, (int)$format->decimal_places, $amount, $coloured); return $this->formatFlat($format->symbol, (int) $format->decimal_places, $amount, $coloured);
} }
/** /**
@@ -77,7 +77,7 @@ class Amount
$fmt->setSymbol(NumberFormatter::CURRENCY_SYMBOL, $symbol); $fmt->setSymbol(NumberFormatter::CURRENCY_SYMBOL, $symbol);
$fmt->setAttribute(NumberFormatter::MIN_FRACTION_DIGITS, $decimalPlaces); $fmt->setAttribute(NumberFormatter::MIN_FRACTION_DIGITS, $decimalPlaces);
$fmt->setAttribute(NumberFormatter::MAX_FRACTION_DIGITS, $decimalPlaces); $fmt->setAttribute(NumberFormatter::MAX_FRACTION_DIGITS, $decimalPlaces);
$result = $fmt->format((float)$amount); $result = $fmt->format((float) $amount);
if (true === $coloured) { if (true === $coloured) {
if ($amount > 0) { if ($amount > 0) {
@@ -131,7 +131,7 @@ class Amount
} }
$cache->store(config('firefly.default_currency', 'EUR')); $cache->store(config('firefly.default_currency', 'EUR'));
return (string)config('firefly.default_currency', 'EUR'); return (string) config('firefly.default_currency', 'EUR');
} }
/** /**
@@ -164,7 +164,7 @@ class Amount
$currencyPrefStr = $currencyPreference ? $currencyPreference->data : 'EUR'; $currencyPrefStr = $currencyPreference ? $currencyPreference->data : 'EUR';
// at this point the currency preference could be encrypted, if coming from an old version. // at this point the currency preference could be encrypted, if coming from an old version.
$currencyCode = $this->tryDecrypt((string)$currencyPrefStr); $currencyCode = $this->tryDecrypt((string) $currencyPrefStr);
// could still be json encoded: // could still be json encoded:
/** @var TransactionCurrency|null $currency */ /** @var TransactionCurrency|null $currency */

View File

@@ -81,7 +81,7 @@ class RemoteUserGuard implements Guard
$header = config('auth.guard_email'); $header = config('auth.guard_email');
if (null !== $header) { if (null !== $header) {
$emailAddress = (string)(request()->server($header) ?? null); $emailAddress = (string) (request()->server($header) ?? null);
$preference = app('preferences')->getForUser($retrievedUser, 'remote_guard_alt_email'); $preference = app('preferences')->getForUser($retrievedUser, 'remote_guard_alt_email');
if (null !== $emailAddress && null === $preference && $emailAddress !== $userID) { if (null !== $emailAddress && null === $preference && $emailAddress !== $userID) {
@@ -93,6 +93,14 @@ class RemoteUserGuard implements Guard
$this->user = $retrievedUser; $this->user = $retrievedUser;
} }
/**
* @inheritDoc
*/
public function guest(): bool
{
return !$this->check();
}
/** /**
* @inheritDoc * @inheritDoc
*/ */
@@ -104,9 +112,17 @@ class RemoteUserGuard implements Guard
/** /**
* @inheritDoc * @inheritDoc
*/ */
public function guest(): bool public function user(): ?User
{ {
return !$this->check(); return $this->user;
}
/**
* @inheritDoc
*/
public function hasUser()
{
// TODO: Implement hasUser() method.
} }
/** /**
@@ -125,14 +141,6 @@ class RemoteUserGuard implements Guard
$this->user = $user; $this->user = $user;
} }
/**
* @inheritDoc
*/
public function user(): ?User
{
return $this->user;
}
/** /**
* @inheritDoc * @inheritDoc
*/ */
@@ -140,12 +148,4 @@ class RemoteUserGuard implements Guard
{ {
throw new FireflyException('Did not implement RemoteUserGuard::validate()'); throw new FireflyException('Did not implement RemoteUserGuard::validate()');
} }
/**
* @inheritDoc
*/
public function hasUser()
{
// TODO: Implement hasUser() method.
}
} }

View File

@@ -57,10 +57,10 @@ class RemoteUserProvider implements UserProvider
Log::debug(sprintf('User with email "%s" not found. Will be created.', $identifier)); Log::debug(sprintf('User with email "%s" not found. Will be created.', $identifier));
$user = User::create( $user = User::create(
[ [
'blocked' => false, 'blocked' => false,
'blocked_code' => null, 'blocked_code' => null,
'email' => $identifier, 'email' => $identifier,
'password' => bcrypt(Str::random(64)), 'password' => bcrypt(Str::random(64)),
] ]
); );
} }

View File

@@ -49,7 +49,7 @@ class CLIToken implements BinderInterface
$users = $repository->all(); $users = $repository->all();
// check for static token // check for static token
if ($value === config('firefly.static_cron_token') && 32 === strlen((string)config('firefly.static_cron_token'))) { if ($value === config('firefly.static_cron_token') && 32 === strlen((string) config('firefly.static_cron_token'))) {
return $value; return $value;
} }

View File

@@ -69,7 +69,7 @@ class TagList implements BinderInterface
if (in_array(strtolower($tag->tag), $list, true)) { if (in_array(strtolower($tag->tag), $list, true)) {
return true; return true;
} }
if (in_array((string)$tag->id, $list, true)) { if (in_array((string) $tag->id, $list, true)) {
return true; return true;
} }

View File

@@ -48,7 +48,7 @@ class TagOrId implements BinderInterface
$result = $repository->findByTag($value); $result = $repository->findByTag($value);
if (null === $result) { if (null === $result) {
$result = $repository->find((int)$value); $result = $repository->find((int) $value);
} }
if (null !== $result) { if (null !== $result) {
return $result; return $result;

View File

@@ -95,7 +95,7 @@ class CacheProperties
$content .= json_encode($property, JSON_THROW_ON_ERROR); $content .= json_encode($property, JSON_THROW_ON_ERROR);
} catch (JsonException $e) { } catch (JsonException $e) {
// @ignoreException // @ignoreException
$content .= hash('sha256', (string)time()); $content .= hash('sha256', (string) time());
} }
} }
$this->hash = substr(hash('sha256', $content), 0, 16); $this->hash = substr(hash('sha256', $content), 0, 16);

View File

@@ -64,9 +64,9 @@ class FrontpageChartGenerator
{ {
$budgets = $this->budgetRepository->getActiveBudgets(); $budgets = $this->budgetRepository->getActiveBudgets();
$data = [ $data = [
['label' => (string)trans('firefly.spent_in_budget'), 'entries' => [], 'type' => 'bar'], ['label' => (string) trans('firefly.spent_in_budget'), 'entries' => [], 'type' => 'bar'],
['label' => (string)trans('firefly.left_to_spend'), 'entries' => [], 'type' => 'bar'], ['label' => (string) trans('firefly.left_to_spend'), 'entries' => [], 'type' => 'bar'],
['label' => (string)trans('firefly.overspent'), 'entries' => [], 'type' => 'bar'], ['label' => (string) trans('firefly.overspent'), 'entries' => [], 'type' => 'bar'],
]; ];
// loop al budgets: // loop al budgets:
@@ -158,7 +158,7 @@ class FrontpageChartGenerator
/** @var array $entry */ /** @var array $entry */
foreach ($spent as $entry) { foreach ($spent as $entry) {
// only spent the entry where the entry's currency matches the budget limit's currency // only spent the entry where the entry's currency matches the budget limit's currency
if ($entry['currency_id'] === (int)$limit->transaction_currency_id) { if ($entry['currency_id'] === (int) $limit->transaction_currency_id) {
$data = $this->processRow($data, $budget, $limit, $entry); $data = $this->processRow($data, $budget, $limit, $entry);
} }
} }
@@ -229,6 +229,6 @@ class FrontpageChartGenerator
$this->opsRepository->setUser($user); $this->opsRepository->setUser($user);
$locale = app('steam')->getLocale(); $locale = app('steam')->getLocale();
$this->monthAndDayFormat = (string)trans('config.month_and_day_js', [], $locale); $this->monthAndDayFormat = (string) trans('config.month_and_day_js', [], $locale);
} }
} }

View File

@@ -114,8 +114,8 @@ class FrontpageChartGenerator
$tempData[] = [ $tempData[] = [
'name' => $category->name, 'name' => $category->name,
'sum' => $currency['sum'], 'sum' => $currency['sum'],
'sum_float' => round((float)$currency['sum'], $currency['currency_decimal_places']), 'sum_float' => round((float) $currency['sum'], $currency['currency_decimal_places']),
'currency_id' => (int)$currency['currency_id'], 'currency_id' => (int) $currency['currency_id'],
]; ];
} }
@@ -127,7 +127,7 @@ class FrontpageChartGenerator
*/ */
private function addCurrency(array $currency): void private function addCurrency(array $currency): void
{ {
$currencyId = (int)$currency['currency_id']; $currencyId = (int) $currency['currency_id'];
$this->currencies[$currencyId] = $this->currencies[$currencyId] ?? [ $this->currencies[$currencyId] = $this->currencies[$currencyId] ?? [
'currency_id' => $currencyId, 'currency_id' => $currencyId,
@@ -152,8 +152,8 @@ class FrontpageChartGenerator
$tempData[] = [ $tempData[] = [
'name' => trans('firefly.no_category'), 'name' => trans('firefly.no_category'),
'sum' => $currency['sum'], 'sum' => $currency['sum'],
'sum_float' => round((float)$currency['sum'], $currency['currency_decimal_places'] ?? 2), 'sum_float' => round((float) $currency['sum'], $currency['currency_decimal_places'] ?? 2),
'currency_id' => (int)$currency['currency_id'], 'currency_id' => (int) $currency['currency_id'],
]; ];
} }
@@ -175,7 +175,7 @@ class FrontpageChartGenerator
foreach ($this->currencies as $currencyId => $currency) { foreach ($this->currencies as $currencyId => $currency) {
$key = sprintf('spent-%d', $currencyId); $key = sprintf('spent-%d', $currencyId);
$return[$key] = [ $return[$key] = [
'label' => sprintf('%s (%s)', (string)trans('firefly.spent'), $currency['currency_name']), 'label' => sprintf('%s (%s)', (string) trans('firefly.spent'), $currency['currency_name']),
'type' => 'bar', 'type' => 'bar',
'currency_symbol' => $currency['currency_symbol'], 'currency_symbol' => $currency['currency_symbol'],
'entries' => $names, 'entries' => $names,

View File

@@ -77,14 +77,14 @@ class WholePeriodChartGenerator
$code = $currency['currency_code']; $code = $currency['currency_code'];
$name = $currency['currency_name']; $name = $currency['currency_name'];
$chartData[sprintf('spent-in-%s', $code)] = [ $chartData[sprintf('spent-in-%s', $code)] = [
'label' => (string)trans('firefly.box_spent_in_currency', ['currency' => $name]), 'label' => (string) trans('firefly.box_spent_in_currency', ['currency' => $name]),
'entries' => [], 'entries' => [],
'type' => 'bar', 'type' => 'bar',
'backgroundColor' => 'rgba(219, 68, 55, 0.5)', // red 'backgroundColor' => 'rgba(219, 68, 55, 0.5)', // red
]; ];
$chartData[sprintf('earned-in-%s', $code)] = [ $chartData[sprintf('earned-in-%s', $code)] = [
'label' => (string)trans('firefly.box_earned_in_currency', ['currency' => $name]), 'label' => (string) trans('firefly.box_earned_in_currency', ['currency' => $name]),
'entries' => [], 'entries' => [],
'type' => 'bar', 'type' => 'bar',
'backgroundColor' => 'rgba(0, 141, 76, 0.5)', // green 'backgroundColor' => 'rgba(0, 141, 76, 0.5)', // green
@@ -105,8 +105,8 @@ class WholePeriodChartGenerator
$earnedInfoKey = sprintf('earned-in-%s', $code); $earnedInfoKey = sprintf('earned-in-%s', $code);
$spentAmount = $spent[$key][$currencyId]['sum'] ?? '0'; $spentAmount = $spent[$key][$currencyId]['sum'] ?? '0';
$earnedAmount = $earned[$key][$currencyId]['sum'] ?? '0'; $earnedAmount = $earned[$key][$currencyId]['sum'] ?? '0';
$chartData[$spentInfoKey]['entries'][$label] = round((float)$spentAmount, $currency['currency_decimal_places']); $chartData[$spentInfoKey]['entries'][$label] = round((float) $spentAmount, $currency['currency_decimal_places']);
$chartData[$earnedInfoKey]['entries'][$label] = round((float)$earnedAmount, $currency['currency_decimal_places']); $chartData[$earnedInfoKey]['entries'][$label] = round((float) $earnedAmount, $currency['currency_decimal_places']);
} }
$current = app('navigation')->addPeriod($current, $step, 0); $current = app('navigation')->addPeriod($current, $step, 0);
} }

View File

@@ -32,10 +32,10 @@ use Carbon\Carbon;
*/ */
abstract class AbstractCronjob abstract class AbstractCronjob
{ {
public bool $jobErrored; public bool $jobErrored;
public bool $jobFired; public bool $jobFired;
public bool $jobSucceeded; public bool $jobSucceeded;
public ?string $message; public ?string $message;
public int $timeBetweenRuns = 43200; public int $timeBetweenRuns = 43200;
protected Carbon $date; protected Carbon $date;
protected bool $force; protected bool $force;

View File

@@ -42,7 +42,7 @@ class AutoBudgetCronjob extends AbstractCronjob
{ {
/** @var Configuration $config */ /** @var Configuration $config */
$config = app('fireflyconfig')->get('last_ab_job', 0); $config = app('fireflyconfig')->get('last_ab_job', 0);
$lastTime = (int)$config->data; $lastTime = (int) $config->data;
$diff = time() - $lastTime; $diff = time() - $lastTime;
$diffForHumans = Carbon::now()->diffForHumans(Carbon::createFromTimestamp($lastTime), null, true); $diffForHumans = Carbon::now()->diffForHumans(Carbon::createFromTimestamp($lastTime), null, true);
if (0 === $lastTime) { if (0 === $lastTime) {
@@ -89,7 +89,7 @@ class AutoBudgetCronjob extends AbstractCronjob
$this->jobSucceeded = true; $this->jobSucceeded = true;
$this->message = 'Auto-budget cron job fired successfully.'; $this->message = 'Auto-budget cron job fired successfully.';
app('fireflyconfig')->set('last_ab_job', (int)$this->date->format('U')); app('fireflyconfig')->set('last_ab_job', (int) $this->date->format('U'));
Log::info('Done with auto budget cron job task.'); Log::info('Done with auto budget cron job task.');
} }
} }

View File

@@ -42,7 +42,7 @@ class BillWarningCronjob extends AbstractCronjob
Log::debug(sprintf('Now in %s', __METHOD__)); Log::debug(sprintf('Now in %s', __METHOD__));
/** @var Configuration $config */ /** @var Configuration $config */
$config = app('fireflyconfig')->get('last_bw_job', 0); $config = app('fireflyconfig')->get('last_bw_job', 0);
$lastTime = (int)$config->data; $lastTime = (int) $config->data;
$diff = time() - $lastTime; $diff = time() - $lastTime;
$diffForHumans = Carbon::now()->diffForHumans(Carbon::createFromTimestamp($lastTime), null, true); $diffForHumans = Carbon::now()->diffForHumans(Carbon::createFromTimestamp($lastTime), null, true);
@@ -95,8 +95,8 @@ class BillWarningCronjob extends AbstractCronjob
$this->jobSucceeded = true; $this->jobSucceeded = true;
$this->message = 'Bill warning cron job fired successfully.'; $this->message = 'Bill warning cron job fired successfully.';
app('fireflyconfig')->set('last_bw_job', (int)$this->date->format('U')); app('fireflyconfig')->set('last_bw_job', (int) $this->date->format('U'));
Log::info(sprintf('Marked the last time this job has run as "%s" (%d)', $this->date->format('Y-m-d H:i:s'), (int)$this->date->format('U'))); Log::info(sprintf('Marked the last time this job has run as "%s" (%d)', $this->date->format('Y-m-d H:i:s'), (int) $this->date->format('U')));
Log::info('Done with bill warning cron job task.'); Log::info('Done with bill warning cron job task.');
} }
} }

View File

@@ -214,7 +214,7 @@ class ExpandedForm
$fields = ['title', 'name', 'description']; $fields = ['title', 'name', 'description'];
/** @var Eloquent $entry */ /** @var Eloquent $entry */
foreach ($set as $entry) { foreach ($set as $entry) {
$entryId = (int)$entry->id; // @phpstan-ignore-line $entryId = (int) $entry->id; // @phpstan-ignore-line
$current = $entry->toArray(); $current = $entry->toArray();
$title = null; $title = null;
foreach ($fields as $field) { foreach ($fields as $field) {

View File

@@ -69,7 +69,7 @@ class FireflyConfig
try { try {
/** @var Configuration|null $config */ /** @var Configuration|null $config */
$config = Configuration::where('name', $name)->first(['id', 'name', 'data']); $config = Configuration::where('name', $name)->first(['id', 'name', 'data']);
} catch (QueryException | Exception $e) { // @phpstan-ignore-line } catch (QueryException|Exception $e) { // @phpstan-ignore-line
throw new FireflyException(sprintf('Could not poll the database: %s', $e->getMessage())); throw new FireflyException(sprintf('Could not poll the database: %s', $e->getMessage()));
} }
@@ -96,7 +96,7 @@ class FireflyConfig
{ {
try { try {
$config = Configuration::whereName($name)->whereNull('deleted_at')->first(); $config = Configuration::whereName($name)->whereNull('deleted_at')->first();
} catch (QueryException | Exception $e) { // @phpstan-ignore-line } catch (QueryException|Exception $e) { // @phpstan-ignore-line
$item = new Configuration; $item = new Configuration;
$item->name = $name; $item->name = $name;
$item->data = $value; $item->data = $value;

View File

@@ -56,8 +56,8 @@ class AccountForm
$repository = $this->getAccountRepository(); $repository = $this->getAccountRepository();
$grouped = $this->getAccountsGrouped($types, $repository); $grouped = $this->getAccountsGrouped($types, $repository);
$cash = $repository->getCashAccount(); $cash = $repository->getCashAccount();
$key = (string)trans('firefly.cash_account_type'); $key = (string) trans('firefly.cash_account_type');
$grouped[$key][$cash->id] = sprintf('(%s)', (string)trans('firefly.cash')); $grouped[$key][$cash->id] = sprintf('(%s)', (string) trans('firefly.cash'));
return $this->select($name, $grouped, $value, $options); return $this->select($name, $grouped, $value, $options);
} }
@@ -73,7 +73,7 @@ class AccountForm
/** @var Account $account */ /** @var Account $account */
foreach ($accountList as $account) { foreach ($accountList as $account) {
$role = (string)$repository->getMetaValue($account, 'account_role'); $role = (string) $repository->getMetaValue($account, 'account_role');
if (in_array($account->accountType->type, $liabilityTypes, true)) { if (in_array($account->accountType->type, $liabilityTypes, true)) {
$role = sprintf('l_%s', $account->accountType->type); $role = sprintf('l_%s', $account->accountType->type);
} elseif ('' === $role) { } elseif ('' === $role) {
@@ -85,7 +85,7 @@ class AccountForm
$role = 'no_account_type'; $role = 'no_account_type';
} }
} }
$key = (string)trans(sprintf('firefly.opt_group_%s', $role)); $key = (string) trans(sprintf('firefly.opt_group_%s', $role));
$grouped[$key][$account->id] = $account->name; $grouped[$key][$account->id] = $account->name;
} }
@@ -108,8 +108,8 @@ class AccountForm
$grouped = $this->getAccountsGrouped($types, $repository); $grouped = $this->getAccountsGrouped($types, $repository);
$cash = $repository->getCashAccount(); $cash = $repository->getCashAccount();
$key = (string)trans('firefly.cash_account_type'); $key = (string) trans('firefly.cash_account_type');
$grouped[$key][$cash->id] = sprintf('(%s)', (string)trans('firefly.cash')); $grouped[$key][$cash->id] = sprintf('(%s)', (string) trans('firefly.cash'));
return $this->select($name, $grouped, $value, $options); return $this->select($name, $grouped, $value, $options);
} }

View File

@@ -77,7 +77,7 @@ class CurrencyForm
$preFilled = []; $preFilled = [];
} }
$key = 'amount_currency_id_' . $name; $key = 'amount_currency_id_' . $name;
$sentCurrencyId = array_key_exists($key, $preFilled) ? (int)$preFilled[$key] : $defaultCurrency->id; $sentCurrencyId = array_key_exists($key, $preFilled) ? (int) $preFilled[$key] : $defaultCurrency->id;
Log::debug(sprintf('Sent currency ID is %d', $sentCurrencyId)); Log::debug(sprintf('Sent currency ID is %d', $sentCurrencyId));
@@ -92,7 +92,7 @@ class CurrencyForm
// make sure value is formatted nicely: // make sure value is formatted nicely:
if (null !== $value && '' !== $value) { if (null !== $value && '' !== $value) {
$value = round((float)$value, $defaultCurrency->decimal_places); $value = round((float) $value, $defaultCurrency->decimal_places);
} }
try { try {
$html = view('form.' . $view, compact('defaultCurrency', 'currencies', 'classes', 'name', 'label', 'value', 'options'))->render(); $html = view('form.' . $view, compact('defaultCurrency', 'currencies', 'classes', 'name', 'label', 'value', 'options'))->render();
@@ -146,7 +146,7 @@ class CurrencyForm
$preFilled = []; $preFilled = [];
} }
$key = 'amount_currency_id_' . $name; $key = 'amount_currency_id_' . $name;
$sentCurrencyId = array_key_exists($key, $preFilled) ? (int)$preFilled[$key] : $defaultCurrency->id; $sentCurrencyId = array_key_exists($key, $preFilled) ? (int) $preFilled[$key] : $defaultCurrency->id;
Log::debug(sprintf('Sent currency ID is %d', $sentCurrencyId)); Log::debug(sprintf('Sent currency ID is %d', $sentCurrencyId));
@@ -161,7 +161,7 @@ class CurrencyForm
// make sure value is formatted nicely: // make sure value is formatted nicely:
if (null !== $value && '' !== $value) { if (null !== $value && '' !== $value) {
$value = round((float)$value, $defaultCurrency->decimal_places); $value = round((float) $value, $defaultCurrency->decimal_places);
} }
try { try {
$html = view('form.' . $view, compact('defaultCurrency', 'currencies', 'classes', 'name', 'label', 'value', 'options'))->render(); $html = view('form.' . $view, compact('defaultCurrency', 'currencies', 'classes', 'name', 'label', 'value', 'options'))->render();
@@ -215,7 +215,7 @@ class CurrencyForm
// get all currencies: // get all currencies:
$list = $currencyRepos->get(); $list = $currencyRepos->get();
$array = [ $array = [
0 => (string)trans('firefly.no_currency'), 0 => (string) trans('firefly.no_currency'),
]; ];
/** @var TransactionCurrency $currency */ /** @var TransactionCurrency $currency */
foreach ($list as $currency) { foreach ($list as $currency) {

View File

@@ -76,7 +76,7 @@ trait FormSupport
} }
$name = str_replace('[]', '', $name); $name = str_replace('[]', '', $name);
return (string)trans('form.' . $name); return (string) trans('form.' . $name);
} }
/** /**

View File

@@ -50,7 +50,7 @@ class PiggyBankForm
/** @var PiggyBankRepositoryInterface $repository */ /** @var PiggyBankRepositoryInterface $repository */
$repository = app(PiggyBankRepositoryInterface::class); $repository = app(PiggyBankRepositoryInterface::class);
$piggyBanks = $repository->getPiggyBanksWithAmount(); $piggyBanks = $repository->getPiggyBanksWithAmount();
$title = (string)trans('firefly.default_group_title_name'); $title = (string) trans('firefly.default_group_title_name');
$array = []; $array = [];
$subList = [ $subList = [
0 => [ 0 => [
@@ -58,7 +58,7 @@ class PiggyBankForm
'title' => $title, 'title' => $title,
], ],
'piggies' => [ 'piggies' => [
(string)trans('firefly.none_in_select_list'), (string) trans('firefly.none_in_select_list'),
], ],
], ],
]; ];

View File

@@ -76,11 +76,11 @@ class RuleForm
// get all currencies: // get all currencies:
$list = $groupRepos->get(); $list = $groupRepos->get();
$array = [ $array = [
0 => (string)trans('firefly.none_in_select_list'), 0 => (string) trans('firefly.none_in_select_list'),
]; ];
/** @var RuleGroup $group */ /** @var RuleGroup $group */
foreach ($list as $group) { foreach ($list as $group) {
if (array_key_exists('hidden', $options) && (int)$options['hidden'] !== $group->id) { if (array_key_exists('hidden', $options) && (int) $options['hidden'] !== $group->id) {
$array[$group->id] = $group->title; $array[$group->id] = $group->title;
} }
} }

View File

@@ -123,7 +123,7 @@ trait AugumentData
$return = []; $return = [];
foreach ($accountIds as $combinedId) { foreach ($accountIds as $combinedId) {
$parts = explode('-', $combinedId); $parts = explode('-', $combinedId);
$accountId = (int)$parts[0]; $accountId = (int) $parts[0];
if (array_key_exists($accountId, $grouped)) { if (array_key_exists($accountId, $grouped)) {
$return[$accountId] = $grouped[$accountId][0]['name']; $return[$accountId] = $grouped[$accountId][0]['name'];
} }
@@ -152,7 +152,7 @@ trait AugumentData
$return[$budgetId] = $grouped[$budgetId][0]['name']; $return[$budgetId] = $grouped[$budgetId][0]['name'];
} }
} }
$return[0] = (string)trans('firefly.no_budget'); $return[0] = (string) trans('firefly.no_budget');
return $return; return $return;
} }
@@ -173,12 +173,12 @@ trait AugumentData
$return = []; $return = [];
foreach ($categoryIds as $combinedId) { foreach ($categoryIds as $combinedId) {
$parts = explode('-', $combinedId); $parts = explode('-', $combinedId);
$categoryId = (int)$parts[0]; $categoryId = (int) $parts[0];
if (array_key_exists($categoryId, $grouped)) { if (array_key_exists($categoryId, $grouped)) {
$return[$categoryId] = $grouped[$categoryId][0]['name']; $return[$categoryId] = $grouped[$categoryId][0]['name'];
} }
} }
$return[0] = (string)trans('firefly.no_category'); $return[0] = (string) trans('firefly.no_category');
return $return; return $return;
} }
@@ -222,7 +222,7 @@ trait AugumentData
$currentStart = clone $entry->start_date; $currentStart = clone $entry->start_date;
$currentEnd = clone $entry->end_date; $currentEnd = clone $entry->end_date;
$expenses = $opsRepository->sumExpenses($currentStart, $currentEnd, null, $budgetCollection, $currency); $expenses = $opsRepository->sumExpenses($currentStart, $currentEnd, null, $budgetCollection, $currency);
$spent = $expenses[(int)$currency->id]['sum'] ?? '0'; $spent = $expenses[(int) $currency->id]['sum'] ?? '0';
$entry->spent = $spent; $entry->spent = $spent;
$limits->push($entry); $limits->push($entry);
@@ -285,7 +285,7 @@ trait AugumentData
]; ];
// loop to support multi currency // loop to support multi currency
foreach ($journals as $journal) { foreach ($journals as $journal) {
$currencyId = (int)$journal['currency_id']; $currencyId = (int) $journal['currency_id'];
// if not set, set to zero: // if not set, set to zero:
if (!array_key_exists($currencyId, $sum['per_currency'])) { if (!array_key_exists($currencyId, $sum['per_currency'])) {

View File

@@ -77,7 +77,7 @@ trait ChartGeneration
/** @var Account $account */ /** @var Account $account */
foreach ($accounts as $account) { foreach ($accounts as $account) {
// See reference nr. 33 // See reference nr. 33
$currency = $repository->find((int)$accountRepos->getMetaValue($account, 'currency_id')); $currency = $repository->find((int) $accountRepos->getMetaValue($account, 'currency_id'));
if (null === $currency) { if (null === $currency) {
$currency = $default; $currency = $default;
} }
@@ -92,7 +92,7 @@ trait ChartGeneration
$previous = array_values($range)[0]; $previous = array_values($range)[0];
while ($currentStart <= $end) { while ($currentStart <= $end) {
$format = $currentStart->format('Y-m-d'); $format = $currentStart->format('Y-m-d');
$label = trim($currentStart->isoFormat((string)trans('config.month_and_day_js', [], $locale))); $label = trim($currentStart->isoFormat((string) trans('config.month_and_day_js', [], $locale)));
$balance = $range[$format] ?? $previous; $balance = $range[$format] ?? $previous;
$previous = $balance; $previous = $balance;
$currentStart->addDay(); $currentStart->addDay();

View File

@@ -83,7 +83,7 @@ trait CreateStuff
/** @var AccountRepositoryInterface $repository */ /** @var AccountRepositoryInterface $repository */
$repository = app(AccountRepositoryInterface::class); $repository = app(AccountRepositoryInterface::class);
$assetAccount = [ $assetAccount = [
'name' => (string)trans('firefly.cash_wallet', [], $language), 'name' => (string) trans('firefly.cash_wallet', [], $language),
'iban' => null, 'iban' => null,
'account_type_name' => 'asset', 'account_type_name' => 'asset',
'virtual_balance' => 0, 'virtual_balance' => 0,
@@ -150,7 +150,7 @@ trait CreateStuff
/** @var AccountRepositoryInterface $repository */ /** @var AccountRepositoryInterface $repository */
$repository = app(AccountRepositoryInterface::class); $repository = app(AccountRepositoryInterface::class);
$savingsAccount = [ $savingsAccount = [
'name' => (string)trans('firefly.new_savings_account', ['bank_name' => $request->get('bank_name')], $language), 'name' => (string) trans('firefly.new_savings_account', ['bank_name' => $request->get('bank_name')], $language),
'iban' => null, 'iban' => null,
'account_type_name' => 'asset', 'account_type_name' => 'asset',
'account_type_id' => null, 'account_type_id' => null,

View File

@@ -52,7 +52,7 @@ trait GetConfigurationData
E_COMPILE_ERROR | E_RECOVERABLE_ERROR | E_ERROR | E_CORE_ERROR => 'E_COMPILE_ERROR|E_RECOVERABLE_ERROR|E_ERROR|E_CORE_ERROR', E_COMPILE_ERROR | E_RECOVERABLE_ERROR | E_ERROR | E_CORE_ERROR => 'E_COMPILE_ERROR|E_RECOVERABLE_ERROR|E_ERROR|E_CORE_ERROR',
]; ];
return $array[$value] ?? (string)$value; return $array[$value] ?? (string) $value;
} }
/** /**
@@ -72,7 +72,7 @@ trait GetConfigurationData
$currentStep = $options; $currentStep = $options;
// get the text: // get the text:
$currentStep['intro'] = (string)trans('intro.' . $route . '_' . $key); $currentStep['intro'] = (string) trans('intro.' . $route . '_' . $key);
// save in array: // save in array:
$steps[] = $currentStep; $steps[] = $currentStep;
@@ -91,7 +91,7 @@ trait GetConfigurationData
*/ */
protected function getDateRangeConfig(): array // get configuration + get preferences. protected function getDateRangeConfig(): array // get configuration + get preferences.
{ {
$viewRange = (string)app('preferences')->get('viewRange', '1M')->data; $viewRange = (string) app('preferences')->get('viewRange', '1M')->data;
/** @var Carbon $start */ /** @var Carbon $start */
$start = session('start'); $start = session('start');
/** @var Carbon $end */ /** @var Carbon $end */
@@ -132,31 +132,31 @@ trait GetConfigurationData
/** @var Carbon $todayEnd */ /** @var Carbon $todayEnd */
$todayEnd = app('navigation')->endOfPeriod($todayStart, $viewRange); $todayEnd = app('navigation')->endOfPeriod($todayStart, $viewRange);
if ($todayStart->ne($start) || $todayEnd->ne($end)) { if ($todayStart->ne($start) || $todayEnd->ne($end)) {
$ranges[ucfirst((string)trans('firefly.today'))] = [$todayStart, $todayEnd]; $ranges[ucfirst((string) trans('firefly.today'))] = [$todayStart, $todayEnd];
} }
// last seven days: // last seven days:
$seven = Carbon::now()->subDays(7); $seven = Carbon::now()->subDays(7);
$index = (string)trans('firefly.last_seven_days'); $index = (string) trans('firefly.last_seven_days');
$ranges[$index] = [$seven, new Carbon]; $ranges[$index] = [$seven, new Carbon];
// last 30 days: // last 30 days:
$thirty = Carbon::now()->subDays(30); $thirty = Carbon::now()->subDays(30);
$index = (string)trans('firefly.last_thirty_days'); $index = (string) trans('firefly.last_thirty_days');
$ranges[$index] = [$thirty, new Carbon]; $ranges[$index] = [$thirty, new Carbon];
// everything // everything
$index = (string)trans('firefly.everything'); $index = (string) trans('firefly.everything');
$ranges[$index] = [$first, new Carbon]; $ranges[$index] = [$first, new Carbon];
return [ return [
'title' => $title, 'title' => $title,
'configuration' => [ 'configuration' => [
'apply' => (string)trans('firefly.apply'), 'apply' => (string) trans('firefly.apply'),
'cancel' => (string)trans('firefly.cancel'), 'cancel' => (string) trans('firefly.cancel'),
'from' => (string)trans('firefly.from'), 'from' => (string) trans('firefly.from'),
'to' => (string)trans('firefly.to'), 'to' => (string) trans('firefly.to'),
'customRange' => (string)trans('firefly.customRange'), 'customRange' => (string) trans('firefly.customRange'),
'start' => $start->format('Y-m-d'), 'start' => $start->format('Y-m-d'),
'end' => $end->format('Y-m-d'), 'end' => $end->format('Y-m-d'),
'ranges' => $ranges, 'ranges' => $ranges,
@@ -187,7 +187,7 @@ trait GetConfigurationData
$currentStep = $options; $currentStep = $options;
// get the text: // get the text:
$currentStep['intro'] = (string)trans('intro.' . $route . '_' . $specificPage . '_' . $key); $currentStep['intro'] = (string) trans('intro.' . $route . '_' . $specificPage . '_' . $key);
// save in array: // save in array:
$steps[] = $currentStep; $steps[] = $currentStep;
@@ -205,7 +205,7 @@ trait GetConfigurationData
protected function verifyRecurringCronJob(): void protected function verifyRecurringCronJob(): void
{ {
$config = app('fireflyconfig')->get('last_rt_job', 0); $config = app('fireflyconfig')->get('last_rt_job', 0);
$lastTime = (int)$config->data; $lastTime = (int) $config->data;
$now = time(); $now = time();
Log::debug(sprintf('verifyRecurringCronJob: last time is %d ("%s"), now is %d', $lastTime, $config->data, $now)); Log::debug(sprintf('verifyRecurringCronJob: last time is %d ("%s"), now is %d', $lastTime, $config->data, $now));
if (0 === $lastTime) { if (0 === $lastTime) {

View File

@@ -83,9 +83,9 @@ trait ModelInformation
$mortgage = $repository->getAccountTypeByType(AccountType::MORTGAGE); $mortgage = $repository->getAccountTypeByType(AccountType::MORTGAGE);
/** @noinspection NullPointerExceptionInspection */ /** @noinspection NullPointerExceptionInspection */
$liabilityTypes = [ $liabilityTypes = [
$debt->id => (string)trans(sprintf('firefly.account_type_%s', AccountType::DEBT)), $debt->id => (string) trans(sprintf('firefly.account_type_%s', AccountType::DEBT)),
$loan->id => (string)trans(sprintf('firefly.account_type_%s', AccountType::LOAN)), $loan->id => (string) trans(sprintf('firefly.account_type_%s', AccountType::LOAN)),
$mortgage->id => (string)trans(sprintf('firefly.account_type_%s', AccountType::MORTGAGE)), $mortgage->id => (string) trans(sprintf('firefly.account_type_%s', AccountType::MORTGAGE)),
]; ];
asort($liabilityTypes); asort($liabilityTypes);
@@ -100,7 +100,7 @@ trait ModelInformation
{ {
$roles = []; $roles = [];
foreach (config('firefly.accountRoles') as $role) { foreach (config('firefly.accountRoles') as $role) {
$roles[$role] = (string)trans(sprintf('firefly.account_role_%s', $role)); $roles[$role] = (string) trans(sprintf('firefly.account_role_%s', $role));
} }
return $roles; return $roles;
@@ -121,7 +121,7 @@ trait ModelInformation
foreach ($operators as $key => $operator) { foreach ($operators as $key => $operator) {
if ('user_action' !== $key && false === $operator['alias']) { if ('user_action' !== $key && false === $operator['alias']) {
$triggers[$key] = (string)trans(sprintf('firefly.rule_trigger_%s_choice', $key)); $triggers[$key] = (string) trans(sprintf('firefly.rule_trigger_%s_choice', $key));
} }
} }
asort($triggers); asort($triggers);
@@ -130,8 +130,8 @@ trait ModelInformation
$billTriggers = ['currency_is', 'amount_more', 'amount_less', 'description_contains']; $billTriggers = ['currency_is', 'amount_more', 'amount_less', 'description_contains'];
$values = [ $values = [
$bill->transactionCurrency()->first()->name, $bill->transactionCurrency()->first()->name,
round((float)$bill->amount_min, 24), round((float) $bill->amount_min, 24),
round((float)$bill->amount_max, 24), round((float) $bill->amount_max, 24),
$bill->name, $bill->name,
]; ];
foreach ($billTriggers as $index => $trigger) { foreach ($billTriggers as $index => $trigger) {
@@ -173,7 +173,7 @@ trait ModelInformation
foreach ($operators as $key => $operator) { foreach ($operators as $key => $operator) {
if ('user_action' !== $key && false === $operator['alias']) { if ('user_action' !== $key && false === $operator['alias']) {
$triggers[$key] = (string)trans(sprintf('firefly.rule_trigger_%s_choice', $key)); $triggers[$key] = (string) trans(sprintf('firefly.rule_trigger_%s_choice', $key));
} }
} }
asort($triggers); asort($triggers);

View File

@@ -183,7 +183,7 @@ trait PeriodOverview
$return = []; $return = [];
/** @var array $journal */ /** @var array $journal */
foreach ($journals as $journal) { foreach ($journals as $journal) {
if ($account->id === (int)$journal['source_account_id']) { if ($account->id === (int) $journal['source_account_id']) {
$return[] = $journal; $return[] = $journal;
} }
} }
@@ -205,7 +205,7 @@ trait PeriodOverview
$return = []; $return = [];
/** @var array $journal */ /** @var array $journal */
foreach ($journals as $journal) { foreach ($journals as $journal) {
if ($account->id === (int)$journal['destination_account_id']) { if ($account->id === (int) $journal['destination_account_id']) {
$return[] = $journal; $return[] = $journal;
} }
} }
@@ -224,7 +224,7 @@ trait PeriodOverview
$return = []; $return = [];
/** @var array $journal */ /** @var array $journal */
foreach ($journals as $journal) { foreach ($journals as $journal) {
$currencyId = (int)$journal['currency_id']; $currencyId = (int) $journal['currency_id'];
$foreignCurrencyId = $journal['foreign_currency_id']; $foreignCurrencyId = $journal['foreign_currency_id'];
if (!array_key_exists($currencyId, $return)) { if (!array_key_exists($currencyId, $return)) {
$return[$currencyId] = [ $return[$currencyId] = [
@@ -245,7 +245,7 @@ trait PeriodOverview
$return[$foreignCurrencyId] = [ $return[$foreignCurrencyId] = [
'amount' => '0', 'amount' => '0',
'count' => 0, 'count' => 0,
'currency_id' => (int)$foreignCurrencyId, 'currency_id' => (int) $foreignCurrencyId,
'currency_name' => $journal['foreign_currency_name'], 'currency_name' => $journal['foreign_currency_name'],
'currency_code' => $journal['foreign_currency_code'], 'currency_code' => $journal['foreign_currency_code'],
'currency_symbol' => $journal['foreign_currency_symbol'], 'currency_symbol' => $journal['foreign_currency_symbol'],

View File

@@ -59,10 +59,10 @@ trait RenderPartialViews
/** @var BudgetRepositoryInterface $budgetRepository */ /** @var BudgetRepositoryInterface $budgetRepository */
$budgetRepository = app(BudgetRepositoryInterface::class); $budgetRepository = app(BudgetRepositoryInterface::class);
$budget = $budgetRepository->find((int)$attributes['budgetId']); $budget = $budgetRepository->find((int) $attributes['budgetId']);
$accountRepos = app(AccountRepositoryInterface::class); $accountRepos = app(AccountRepositoryInterface::class);
$account = $accountRepos->find((int)$attributes['accountId']); $account = $accountRepos->find((int) $attributes['accountId']);
$journals = $popupHelper->balanceForBudget($budget, $account, $attributes); $journals = $popupHelper->balanceForBudget($budget, $account, $attributes);
@@ -112,7 +112,7 @@ trait RenderPartialViews
/** @var PopupReportInterface $popupHelper */ /** @var PopupReportInterface $popupHelper */
$popupHelper = app(PopupReportInterface::class); $popupHelper = app(PopupReportInterface::class);
$budget = $budgetRepository->find((int)$attributes['budgetId']); $budget = $budgetRepository->find((int) $attributes['budgetId']);
if (null === $budget) { if (null === $budget) {
$budget = new Budget; $budget = new Budget;
} }
@@ -142,7 +142,7 @@ trait RenderPartialViews
/** @var CategoryRepositoryInterface $categoryRepository */ /** @var CategoryRepositoryInterface $categoryRepository */
$categoryRepository = app(CategoryRepositoryInterface::class); $categoryRepository = app(CategoryRepositoryInterface::class);
$category = $categoryRepository->find((int)$attributes['categoryId']); $category = $categoryRepository->find((int) $attributes['categoryId']);
$journals = $popupHelper->byCategory($category, $attributes); $journals = $popupHelper->byCategory($category, $attributes);
try { try {
@@ -232,7 +232,7 @@ trait RenderPartialViews
/** @var PopupReportInterface $popupHelper */ /** @var PopupReportInterface $popupHelper */
$popupHelper = app(PopupReportInterface::class); $popupHelper = app(PopupReportInterface::class);
$account = $accountRepository->find((int)$attributes['accountId']); $account = $accountRepository->find((int) $attributes['accountId']);
if (null === $account) { if (null === $account) {
return 'This is an unknown account. Apologies.'; return 'This is an unknown account. Apologies.';
@@ -304,7 +304,7 @@ trait RenderPartialViews
foreach ($operators as $key => $operator) { foreach ($operators as $key => $operator) {
if ('user_action' !== $key && false === $operator['alias']) { if ('user_action' !== $key && false === $operator['alias']) {
$triggers[$key] = (string)trans(sprintf('firefly.rule_trigger_%s_choice', $key)); $triggers[$key] = (string) trans(sprintf('firefly.rule_trigger_%s_choice', $key));
} }
} }
asort($triggers); asort($triggers);
@@ -354,7 +354,7 @@ trait RenderPartialViews
/** @var PopupReportInterface $popupHelper */ /** @var PopupReportInterface $popupHelper */
$popupHelper = app(PopupReportInterface::class); $popupHelper = app(PopupReportInterface::class);
$account = $accountRepository->find((int)$attributes['accountId']); $account = $accountRepository->find((int) $attributes['accountId']);
if (null === $account) { if (null === $account) {
return 'This is an unknown category. Apologies.'; return 'This is an unknown category. Apologies.';

View File

@@ -73,7 +73,7 @@ trait RequestInformation
$triggers[] = [ $triggers[] = [
'type' => $triggerInfo['type'] ?? '', 'type' => $triggerInfo['type'] ?? '',
'value' => $triggerInfo['value'] ?? '', 'value' => $triggerInfo['value'] ?? '',
'stop_processing' => 1 === (int)($triggerInfo['stop_processing'] ?? '0'), 'stop_processing' => 1 === (int) ($triggerInfo['stop_processing'] ?? '0'),
]; ];
} }
} }
@@ -198,11 +198,11 @@ trait RequestInformation
final protected function validatePassword(User $user, string $current, string $new): bool //get request info final protected function validatePassword(User $user, string $current, string $new): bool //get request info
{ {
if (!Hash::check($current, $user->password)) { if (!Hash::check($current, $user->password)) {
throw new ValidationException((string)trans('firefly.invalid_current_password')); throw new ValidationException((string) trans('firefly.invalid_current_password'));
} }
if ($current === $new) { if ($current === $new) {
throw new ValidationException((string)trans('firefly.should_change')); throw new ValidationException((string) trans('firefly.should_change'));
} }
return true; return true;

View File

@@ -114,7 +114,7 @@ class ParseDateString
return new Carbon('1984-09-17'); return new Carbon('1984-09-17');
} }
// maybe a year, nothing else? // maybe a year, nothing else?
if (4 === strlen($date) && is_numeric($date) && (int)$date > 1000 && (int)$date <= 3000) { if (4 === strlen($date) && is_numeric($date) && (int) $date > 1000 && (int) $date <= 3000) {
return new Carbon(sprintf('%d-01-01', $date)); return new Carbon(sprintf('%d-01-01', $date));
} }
@@ -194,7 +194,7 @@ class ParseDateString
} }
$direction = str_starts_with($part, '+') ? 1 : 0; $direction = str_starts_with($part, '+') ? 1 : 0;
$period = $part[strlen($part) - 1]; $period = $part[strlen($part) - 1];
$number = (int)substr($part, 1, -1); $number = (int) substr($part, 1, -1);
if (!array_key_exists($period, $functions[$direction])) { if (!array_key_exists($period, $functions[$direction])) {
Log::error(sprintf('No method for direction %d and period "%s".', $direction, $period)); Log::error(sprintf('No method for direction %d and period "%s".', $direction, $period));
continue; continue;

View File

@@ -110,8 +110,8 @@ class BudgetReportGenerator
*/ */
private function processBudgetExpenses(array $expenses, array $budget): void private function processBudgetExpenses(array $expenses, array $budget): void
{ {
$budgetId = (int)$budget['id']; $budgetId = (int) $budget['id'];
$currencyId = (int)$expenses['currency_id']; $currencyId = (int) $expenses['currency_id'];
foreach ($budget['transaction_journals'] as $journal) { foreach ($budget['transaction_journals'] as $journal) {
$sourceAccountId = $journal['source_account_id']; $sourceAccountId = $journal['source_account_id'];
@@ -167,7 +167,7 @@ class BudgetReportGenerator
*/ */
private function processBudget(Budget $budget): void private function processBudget(Budget $budget): void
{ {
$budgetId = (int)$budget->id; $budgetId = (int) $budget->id;
$this->report['budgets'][$budgetId] = $this->report['budgets'][$budgetId] ?? [ $this->report['budgets'][$budgetId] = $this->report['budgets'][$budgetId] ?? [
'budget_id' => $budgetId, 'budget_id' => $budgetId,
'budget_name' => $budget->name, 'budget_name' => $budget->name,
@@ -191,10 +191,10 @@ class BudgetReportGenerator
*/ */
private function processLimit(Budget $budget, BudgetLimit $limit): void private function processLimit(Budget $budget, BudgetLimit $limit): void
{ {
$budgetId = (int)$budget->id; $budgetId = (int) $budget->id;
$limitId = (int)$limit->id; $limitId = (int) $limit->id;
$limitCurrency = $limit->transactionCurrency ?? $this->currency; $limitCurrency = $limit->transactionCurrency ?? $this->currency;
$currencyId = (int)$limitCurrency->id; $currencyId = (int) $limitCurrency->id;
$expenses = $this->opsRepository->sumExpenses($limit->start_date, $limit->end_date, $this->accounts, new Collection([$budget])); $expenses = $this->opsRepository->sumExpenses($limit->start_date, $limit->end_date, $this->accounts, new Collection([$budget]));
$spent = $expenses[$currencyId]['sum'] ?? '0'; $spent = $expenses[$currencyId]['sum'] ?? '0';
$left = -1 === bccomp(bcadd($limit->amount, $spent), '0') ? '0' : bcadd($limit->amount, $spent); $left = -1 === bccomp(bcadd($limit->amount, $spent), '0') ? '0' : bcadd($limit->amount, $spent);
@@ -253,7 +253,7 @@ class BudgetReportGenerator
foreach ($noBudget as $noBudgetEntry) { foreach ($noBudget as $noBudgetEntry) {
// currency information: // currency information:
$nbCurrencyId = (int)($noBudgetEntry['currency_id'] ?? $this->currency->id); $nbCurrencyId = (int) ($noBudgetEntry['currency_id'] ?? $this->currency->id);
$nbCurrencyCode = $noBudgetEntry['currency_code'] ?? $this->currency->code; $nbCurrencyCode = $noBudgetEntry['currency_code'] ?? $this->currency->code;
$nbCurrencyName = $noBudgetEntry['currency_name'] ?? $this->currency->name; $nbCurrencyName = $noBudgetEntry['currency_name'] ?? $this->currency->name;
$nbCurrencySymbol = $noBudgetEntry['currency_symbol'] ?? $this->currency->symbol; $nbCurrencySymbol = $noBudgetEntry['currency_symbol'] ?? $this->currency->symbol;
@@ -298,9 +298,9 @@ class BudgetReportGenerator
// make percentages based on total amount. // make percentages based on total amount.
foreach ($this->report['budgets'] as $budgetId => $data) { foreach ($this->report['budgets'] as $budgetId => $data) {
foreach ($data['budget_limits'] as $limitId => $entry) { foreach ($data['budget_limits'] as $limitId => $entry) {
$budgetId = (int)$budgetId; $budgetId = (int) $budgetId;
$limitId = (int)$limitId; $limitId = (int) $limitId;
$currencyId = (int)$entry['currency_id']; $currencyId = (int) $entry['currency_id'];
$spent = $entry['spent']; $spent = $entry['spent'];
$totalSpent = $this->report['sums'][$currencyId]['spent'] ?? '0'; $totalSpent = $this->report['sums'][$currencyId]['spent'] ?? '0';
$spentPct = '0'; $spentPct = '0';
@@ -309,10 +309,10 @@ class BudgetReportGenerator
$budgetedPct = '0'; $budgetedPct = '0';
if (0 !== bccomp($spent, '0') && 0 !== bccomp($totalSpent, '0')) { if (0 !== bccomp($spent, '0') && 0 !== bccomp($totalSpent, '0')) {
$spentPct = round((float)bcmul(bcdiv($spent, $totalSpent), '100')); $spentPct = round((float) bcmul(bcdiv($spent, $totalSpent), '100'));
} }
if (0 !== bccomp($budgeted, '0') && 0 !== bccomp($totalBudgeted, '0')) { if (0 !== bccomp($budgeted, '0') && 0 !== bccomp($totalBudgeted, '0')) {
$budgetedPct = round((float)bcmul(bcdiv($budgeted, $totalBudgeted), '100')); $budgetedPct = round((float) bcmul(bcdiv($budgeted, $totalBudgeted), '100'));
} }
$this->report['sums'][$currencyId]['budgeted'] = $this->report['sums'][$currencyId]['budgeted'] ?? '0'; $this->report['sums'][$currencyId]['budgeted'] = $this->report['sums'][$currencyId]['budgeted'] ?? '0';
$this->report['budgets'][$budgetId]['budget_limits'][$limitId]['spent_pct'] = $spentPct; $this->report['budgets'][$budgetId]['budget_limits'][$limitId]['spent_pct'] = $spentPct;

View File

@@ -64,12 +64,12 @@ class CategoryReportGenerator
*/ */
public function operations(): void public function operations(): void
{ {
$earnedWith = $this->opsRepository->listIncome($this->start, $this->end, $this->accounts); $earnedWith = $this->opsRepository->listIncome($this->start, $this->end, $this->accounts);
$spentWith = $this->opsRepository->listExpenses($this->start, $this->end, $this->accounts); $spentWith = $this->opsRepository->listExpenses($this->start, $this->end, $this->accounts);
// also transferred out and transferred into these accounts in this category: // also transferred out and transferred into these accounts in this category:
$transferredIn = $this->opsRepository->listTransferredIn($this->start, $this->end, $this->accounts); $transferredIn = $this->opsRepository->listTransferredIn($this->start, $this->end, $this->accounts);
$transferredOut = $this->opsRepository->listTransferredOut($this->start, $this->end, $this->accounts); $transferredOut = $this->opsRepository->listTransferredOut($this->start, $this->end, $this->accounts);
$earnedWithout = $this->noCatRepository->listIncome($this->start, $this->end, $this->accounts); $earnedWithout = $this->noCatRepository->listIncome($this->start, $this->end, $this->accounts);
$spentWithout = $this->noCatRepository->listExpenses($this->start, $this->end, $this->accounts); $spentWithout = $this->noCatRepository->listExpenses($this->start, $this->end, $this->accounts);

View File

@@ -72,7 +72,7 @@ trait CalculateRangeOccurrences
{ {
$return = []; $return = [];
$attempts = 0; $attempts = 0;
$dayOfMonth = (int)$moment; $dayOfMonth = (int) $moment;
if ($start->day > $dayOfMonth) { if ($start->day > $dayOfMonth) {
// day has passed already, add a month. // day has passed already, add a month.
$start->addMonth(); $start->addMonth();
@@ -140,7 +140,7 @@ trait CalculateRangeOccurrences
Log::debug('Rep is weekly.'); Log::debug('Rep is weekly.');
// monday = 1 // monday = 1
// sunday = 7 // sunday = 7
$dayOfWeek = (int)$moment; $dayOfWeek = (int) $moment;
Log::debug(sprintf('DoW in repetition is %d, in mutator is %d', $dayOfWeek, $start->dayOfWeekIso)); Log::debug(sprintf('DoW in repetition is %d, in mutator is %d', $dayOfWeek, $start->dayOfWeekIso));
if ($start->dayOfWeekIso > $dayOfWeek) { if ($start->dayOfWeekIso > $dayOfWeek) {
// day has already passed this week, add one week: // day has already passed this week, add one week:

View File

@@ -47,7 +47,7 @@ trait FiltersWeekends
protected function filterWeekends(RecurrenceRepetition $repetition, array $dates): array protected function filterWeekends(RecurrenceRepetition $repetition, array $dates): array
{ {
Log::debug(sprintf('Now in %s', __METHOD__)); Log::debug(sprintf('Now in %s', __METHOD__));
if ((int)$repetition->weekend === RecurrenceRepetition::WEEKEND_DO_NOTHING) { if ((int) $repetition->weekend === RecurrenceRepetition::WEEKEND_DO_NOTHING) {
Log::debug('Repetition will not be filtered on weekend days.'); Log::debug('Repetition will not be filtered on weekend days.');
return $dates; return $dates;

View File

@@ -30,6 +30,15 @@ use Log;
*/ */
trait AppendsLocationData trait AppendsLocationData
{ {
/**
* Abstract method.
*
* @param $key
*
* @return bool
*/
abstract public function has($key);
/** /**
* Read the submitted Request data and add new or updated Location data to the array. * Read the submitted Request data and add new or updated Location data to the array.
* *
@@ -148,25 +157,6 @@ trait AppendsLocationData
return false; return false;
} }
/**
* Abstract method stolen from "InteractsWithInput".
*
* @param null $key
* @param bool $default
*
* @return mixed
*/
abstract public function boolean($key = null, $default = false);
/**
* Abstract method.
*
* @param $key
*
* @return bool
*/
abstract public function has($key);
/** /**
* Abstract method. * Abstract method.
* *
@@ -183,6 +173,16 @@ trait AppendsLocationData
*/ */
abstract public function routeIs(...$patterns); abstract public function routeIs(...$patterns);
/**
* Abstract method stolen from "InteractsWithInput".
*
* @param null $key
* @param bool $default
*
* @return mixed
*/
abstract public function boolean($key = null, $default = false);
/** /**
* @param string|null $prefix * @param string|null $prefix
* *

View File

@@ -42,7 +42,7 @@ trait GetRecurrenceData
$return['amount'] = $transaction['amount']; $return['amount'] = $transaction['amount'];
} }
if (array_key_exists('currency_id', $transaction)) { if (array_key_exists('currency_id', $transaction)) {
$return['currency_id'] = (int)$transaction['currency_id']; $return['currency_id'] = (int) $transaction['currency_id'];
} }
if (array_key_exists('currency_code', $transaction)) { if (array_key_exists('currency_code', $transaction)) {
$return['currency_code'] = $transaction['currency_code']; $return['currency_code'] = $transaction['currency_code'];
@@ -53,17 +53,17 @@ trait GetRecurrenceData
$return['foreign_amount'] = $transaction['foreign_amount']; $return['foreign_amount'] = $transaction['foreign_amount'];
} }
if (array_key_exists('foreign_currency_id', $transaction)) { if (array_key_exists('foreign_currency_id', $transaction)) {
$return['foreign_currency_id'] = (int)$transaction['foreign_currency_id']; $return['foreign_currency_id'] = (int) $transaction['foreign_currency_id'];
} }
if (array_key_exists('foreign_currency_code', $transaction)) { if (array_key_exists('foreign_currency_code', $transaction)) {
$return['foreign_currency_code'] = $transaction['foreign_currency_code']; $return['foreign_currency_code'] = $transaction['foreign_currency_code'];
} }
// source + dest // source + dest
if (array_key_exists('source_id', $transaction)) { if (array_key_exists('source_id', $transaction)) {
$return['source_id'] = (int)$transaction['source_id']; $return['source_id'] = (int) $transaction['source_id'];
} }
if (array_key_exists('destination_id', $transaction)) { if (array_key_exists('destination_id', $transaction)) {
$return['destination_id'] = (int)$transaction['destination_id']; $return['destination_id'] = (int) $transaction['destination_id'];
} }
// description // description
if (array_key_exists('description', $transaction)) { if (array_key_exists('description', $transaction)) {
@@ -71,17 +71,17 @@ trait GetRecurrenceData
} }
if (array_key_exists('piggy_bank_id', $transaction)) { if (array_key_exists('piggy_bank_id', $transaction)) {
$return['piggy_bank_id'] = (int)$transaction['piggy_bank_id']; $return['piggy_bank_id'] = (int) $transaction['piggy_bank_id'];
} }
if (array_key_exists('tags', $transaction)) { if (array_key_exists('tags', $transaction)) {
$return['tags'] = $transaction['tags']; $return['tags'] = $transaction['tags'];
} }
if (array_key_exists('budget_id', $transaction)) { if (array_key_exists('budget_id', $transaction)) {
$return['budget_id'] = (int)$transaction['budget_id']; $return['budget_id'] = (int) $transaction['budget_id'];
} }
if (array_key_exists('category_id', $transaction)) { if (array_key_exists('category_id', $transaction)) {
$return['category_id'] = (int)$transaction['category_id']; $return['category_id'] = (int) $transaction['category_id'];
} }
return $return; return $return;

View File

@@ -53,7 +53,7 @@ trait GeneratesInstallationId
if (null === $config) { if (null === $config) {
$uuid4 = Uuid::uuid4(); $uuid4 = Uuid::uuid4();
$uniqueId = (string)$uuid4; $uniqueId = (string) $uuid4;
Log::info(sprintf('Created Firefly III installation ID %s', $uniqueId)); Log::info(sprintf('Created Firefly III installation ID %s', $uniqueId));
app('fireflyconfig')->set('installation_id', $uniqueId); app('fireflyconfig')->set('installation_id', $uniqueId);
} }

View File

@@ -72,9 +72,9 @@ class OAuthKeys
// better check if keys are in the database: // better check if keys are in the database:
if (app('fireflyconfig')->has(self::PRIVATE_KEY) && app('fireflyconfig')->has(self::PUBLIC_KEY)) { if (app('fireflyconfig')->has(self::PRIVATE_KEY) && app('fireflyconfig')->has(self::PUBLIC_KEY)) {
try { try {
$privateKey = (string)app('fireflyconfig')->get(self::PRIVATE_KEY)?->data; $privateKey = (string) app('fireflyconfig')->get(self::PRIVATE_KEY)?->data;
$publicKey = (string)app('fireflyconfig')->get(self::PUBLIC_KEY)?->data; $publicKey = (string) app('fireflyconfig')->get(self::PUBLIC_KEY)?->data;
} catch (ContainerExceptionInterface | NotFoundExceptionInterface | FireflyException $e) { } catch (ContainerExceptionInterface|NotFoundExceptionInterface|FireflyException $e) {
Log::error(sprintf('Could not validate keysInDatabase(): %s', $e->getMessage())); Log::error(sprintf('Could not validate keysInDatabase(): %s', $e->getMessage()));
Log::error($e->getTraceAsString()); Log::error($e->getTraceAsString());
} }
@@ -122,12 +122,12 @@ class OAuthKeys
*/ */
public static function restoreKeysFromDB(): bool public static function restoreKeysFromDB(): bool
{ {
$privateKey = (string)app('fireflyconfig')->get(self::PRIVATE_KEY)?->data; $privateKey = (string) app('fireflyconfig')->get(self::PRIVATE_KEY)?->data;
$publicKey = (string)app('fireflyconfig')->get(self::PUBLIC_KEY)?->data; $publicKey = (string) app('fireflyconfig')->get(self::PUBLIC_KEY)?->data;
try { try {
$privateContent = Crypt::decrypt($privateKey); $privateContent = Crypt::decrypt($privateKey);
$publicContent = Crypt::decrypt($publicKey); $publicContent = Crypt::decrypt($publicKey);
} catch(DecryptException $e) { } catch (DecryptException $e) {
Log::error('Could not decrypt pub/private keypair.'); Log::error('Could not decrypt pub/private keypair.');
Log::error($e->getMessage()); Log::error($e->getMessage());
@@ -137,8 +137,8 @@ class OAuthKeys
return false; return false;
} }
$private = storage_path('oauth-private.key'); $private = storage_path('oauth-private.key');
$public = storage_path('oauth-public.key'); $public = storage_path('oauth-public.key');
file_put_contents($private, $privateContent); file_put_contents($private, $privateContent);
file_put_contents($public, $publicContent); file_put_contents($public, $publicContent);
return true; return true;

View File

@@ -45,18 +45,6 @@ class AmountFormat extends AbstractExtension
]; ];
} }
/**
* {@inheritdoc}
*/
public function getFunctions(): array
{
return [
$this->formatAmountByAccount(),
$this->formatAmountBySymbol(),
$this->formatAmountByCurrency(),
];
}
/** /**
* @return TwigFilter * @return TwigFilter
*/ */
@@ -89,6 +77,18 @@ class AmountFormat extends AbstractExtension
); );
} }
/**
* {@inheritdoc}
*/
public function getFunctions(): array
{
return [
$this->formatAmountByAccount(),
$this->formatAmountBySymbol(),
$this->formatAmountByCurrency(),
];
}
/** /**
* Will format the amount by the currency related to the given account. * Will format the amount by the currency related to the given account.
* *

View File

@@ -53,25 +53,6 @@ class General extends AbstractExtension
]; ];
} }
/**
* {@inheritdoc}
*/
public function getFunctions(): array
{
return [
$this->phpdate(),
$this->activeRouteStrict(),
$this->activeRoutePartial(),
$this->activeRoutePartialObjectType(),
$this->menuOpenRoutePartial(),
$this->formatDate(),
$this->getMetaField(),
$this->hasRole(),
$this->getRootSearchOperator(),
$this->carbonize()
];
}
/** /**
* Show account balance. Only used on the front page of Firefly III. * Show account balance. Only used on the front page of Firefly III.
* *
@@ -93,24 +74,6 @@ class General extends AbstractExtension
); );
} }
/**
* Show URL host name
*
* @return TwigFilter
*/
protected function phpHostName(): TwigFilter
{
return new TwigFilter(
'phphost',
static function (string $string): string {
$proto = (string)parse_url($string, PHP_URL_SCHEME);
$host = (string)parse_url($string, PHP_URL_HOST);
return e(sprintf('%s://%s', $proto, $host));
}
);
}
/** /**
* Used to convert 1024 to 1kb etc. * Used to convert 1024 to 1kb etc.
* *
@@ -232,7 +195,7 @@ class General extends AbstractExtension
] ]
); );
return (string)$converter->convertToHtml($text); return (string) $converter->convertToHtml($text);
}, ['is_safe' => ['html']] }, ['is_safe' => ['html']]
); );
} }
@@ -245,11 +208,48 @@ class General extends AbstractExtension
return new TwigFilter( return new TwigFilter(
'floatval', 'floatval',
static function ($value): float { static function ($value): float {
return (float)$value; return (float) $value;
} }
); );
} }
/**
* Show URL host name
*
* @return TwigFilter
*/
protected function phpHostName(): TwigFilter
{
return new TwigFilter(
'phphost',
static function (string $string): string {
$proto = (string) parse_url($string, PHP_URL_SCHEME);
$host = (string) parse_url($string, PHP_URL_HOST);
return e(sprintf('%s://%s', $proto, $host));
}
);
}
/**
* {@inheritdoc}
*/
public function getFunctions(): array
{
return [
$this->phpdate(),
$this->activeRouteStrict(),
$this->activeRoutePartial(),
$this->activeRoutePartialObjectType(),
$this->menuOpenRoutePartial(),
$this->formatDate(),
$this->getMetaField(),
$this->hasRole(),
$this->getRootSearchOperator(),
$this->carbonize(),
];
}
/** /**
* Basic example thing for some views. * Basic example thing for some views.
* *
@@ -396,19 +396,6 @@ class General extends AbstractExtension
); );
} }
/**
* @return TwigFunction
*/
protected function carbonize(): TwigFunction
{
return new TwigFunction(
'carbonize',
static function (string $date): Carbon {
return new Carbon($date);
}
);
}
/** /**
* Will return true if the user is of role X. * Will return true if the user is of role X.
* *
@@ -438,4 +425,17 @@ class General extends AbstractExtension
} }
); );
} }
/**
* @return TwigFunction
*/
protected function carbonize(): TwigFunction
{
return new TwigFunction(
'carbonize',
static function (string $date): Carbon {
return new Carbon($date);
}
);
}
} }

View File

@@ -52,8 +52,8 @@ class Rule extends AbstractExtension
'allJournalTriggers', 'allJournalTriggers',
static function () { static function () {
return [ return [
'store-journal' => (string)trans('firefly.rule_trigger_store_journal'), 'store-journal' => (string) trans('firefly.rule_trigger_store_journal'),
'update-journal' => (string)trans('firefly.rule_trigger_update_journal'), 'update-journal' => (string) trans('firefly.rule_trigger_update_journal'),
]; ];
} }
); );
@@ -71,7 +71,7 @@ class Rule extends AbstractExtension
$possibleTriggers = []; $possibleTriggers = [];
foreach ($ruleTriggers as $key) { foreach ($ruleTriggers as $key) {
if ('user_action' !== $key) { if ('user_action' !== $key) {
$possibleTriggers[$key] = (string)trans('firefly.rule_trigger_' . $key . '_choice'); $possibleTriggers[$key] = (string) trans('firefly.rule_trigger_' . $key . '_choice');
} }
} }
unset($ruleTriggers); unset($ruleTriggers);
@@ -94,7 +94,7 @@ class Rule extends AbstractExtension
$ruleActions = array_keys(Config::get('firefly.rule-actions')); $ruleActions = array_keys(Config::get('firefly.rule-actions'));
$possibleActions = []; $possibleActions = [];
foreach ($ruleActions as $key) { foreach ($ruleActions as $key) {
$possibleActions[$key] = (string)trans('firefly.rule_action_' . $key . '_choice'); $possibleActions[$key] = (string) trans('firefly.rule_action_' . $key . '_choice');
} }
unset($ruleActions); unset($ruleActions);
asort($possibleActions); asort($possibleActions);

View File

@@ -40,7 +40,7 @@ class Translation extends AbstractExtension
new TwigFilter( new TwigFilter(
'_', '_',
static function ($name) { static function ($name) {
return (string)trans(sprintf('firefly.%s', $name)); return (string) trans(sprintf('firefly.%s', $name));
}, },
['is_safe' => ['html']] ['is_safe' => ['html']]
), ),
@@ -65,7 +65,7 @@ class Translation extends AbstractExtension
return new TwigFunction( return new TwigFunction(
'journalLinkTranslation', 'journalLinkTranslation',
static function (string $direction, string $original) { static function (string $direction, string $original) {
$key = sprintf('firefly.%s_%s', $original, $direction); $key = sprintf('firefly.%s_%s', $original, $direction);
$translation = trans($key); $translation = trans($key);
if ($key === $translation) { if ($key === $translation) {
return $original; return $original;

View File

@@ -52,12 +52,12 @@ class AppendNotes implements ActionInterface
{ {
$dbNote = Note $dbNote = Note
:: ::
where('noteable_id', (int)$journal['transaction_journal_id']) where('noteable_id', (int) $journal['transaction_journal_id'])
->where('noteable_type', TransactionJournal::class) ->where('noteable_type', TransactionJournal::class)
->first(['notes.*']); ->first(['notes.*']);
if (null === $dbNote) { if (null === $dbNote) {
$dbNote = new Note; $dbNote = new Note;
$dbNote->noteable_id = (int)$journal['transaction_journal_id']; $dbNote->noteable_id = (int) $journal['transaction_journal_id'];
$dbNote->noteable_type = TransactionJournal::class; $dbNote->noteable_type = TransactionJournal::class;
$dbNote->text = ''; $dbNote->text = '';
} }

View File

@@ -58,7 +58,7 @@ class LinkToBill implements ActionInterface
/** @var BillRepositoryInterface $repository */ /** @var BillRepositoryInterface $repository */
$repository = app(BillRepositoryInterface::class); $repository = app(BillRepositoryInterface::class);
$repository->setUser($user); $repository->setUser($user);
$billName = (string)$this->action->action_value; $billName = (string) $this->action->action_value;
$bill = $repository->findByName($billName); $bill = $repository->findByName($billName);
if (null !== $bill && $journal['transaction_type_type'] === TransactionType::WITHDRAWAL) { if (null !== $bill && $journal['transaction_type_type'] === TransactionType::WITHDRAWAL) {

View File

@@ -52,12 +52,12 @@ class PrependNotes implements ActionInterface
{ {
$dbNote = Note $dbNote = Note
:: ::
where('noteable_id', (int)$journal['transaction_journal_id']) where('noteable_id', (int) $journal['transaction_journal_id'])
->where('noteable_type', TransactionJournal::class) ->where('noteable_type', TransactionJournal::class)
->first(['notes.*']); ->first(['notes.*']);
if (null === $dbNote) { if (null === $dbNote) {
$dbNote = new Note; $dbNote = new Note;
$dbNote->noteable_id = (int)$journal['transaction_journal_id']; $dbNote->noteable_id = (int) $journal['transaction_journal_id'];
$dbNote->noteable_type = TransactionJournal::class; $dbNote->noteable_type = TransactionJournal::class;
$dbNote->text = ''; $dbNote->text = '';
} }

View File

@@ -58,7 +58,7 @@ class SetDestinationAccount implements ActionInterface
$user = User::find($journal['user_id']); $user = User::find($journal['user_id']);
$type = $journal['transaction_type_type']; $type = $journal['transaction_type_type'];
/** @var TransactionJournal|null $object */ /** @var TransactionJournal|null $object */
$object = $user->transactionJournals()->find((int)$journal['transaction_journal_id']); $object = $user->transactionJournals()->find((int) $journal['transaction_journal_id']);
$this->repository = app(AccountRepositoryInterface::class); $this->repository = app(AccountRepositoryInterface::class);
if (null === $object) { if (null === $object) {
@@ -95,7 +95,7 @@ class SetDestinationAccount implements ActionInterface
return false; return false;
} }
if (null !== $newAccount && (int)$newAccount->id === (int)$source->account_id) { if (null !== $newAccount && (int) $newAccount->id === (int) $source->account_id) {
Log::error( Log::error(
sprintf( sprintf(
'New destination account ID #%d and current source account ID #%d are the same. Do nothing.', $newAccount->id, 'New destination account ID #%d and current source account ID #%d are the same. Do nothing.', $newAccount->id,

View File

@@ -61,7 +61,7 @@ class UpdatePiggybank implements ActionInterface
// refresh the transaction type. // refresh the transaction type.
$user = User::find($journal['user_id']); $user = User::find($journal['user_id']);
$journalObj = $user->transactionJournals()->find($journal['transaction_journal_id']); $journalObj = $user->transactionJournals()->find($journal['transaction_journal_id']);
$type = TransactionType::find((int)$journalObj->transaction_type_id); $type = TransactionType::find((int) $journalObj->transaction_type_id);
$journal['transaction_type_type'] = $type->type; $journal['transaction_type_type'] = $type->type;
if (TransactionType::TRANSFER !== $journal['transaction_type_type']) { if (TransactionType::TRANSFER !== $journal['transaction_type_type']) {
@@ -86,13 +86,13 @@ class UpdatePiggybank implements ActionInterface
/** @var Transaction $destination */ /** @var Transaction $destination */
$destination = Transaction::where('transaction_journal_id', $journal['transaction_journal_id'])->where('amount', '>', 0)->first(); $destination = Transaction::where('transaction_journal_id', $journal['transaction_journal_id'])->where('amount', '>', 0)->first();
if ((int)$source->account_id === (int)$piggyBank->account_id) { if ((int) $source->account_id === (int) $piggyBank->account_id) {
Log::debug('Piggy bank account is linked to source, so remove amount.'); Log::debug('Piggy bank account is linked to source, so remove amount.');
$this->removeAmount($journal, $piggyBank, $destination->amount); $this->removeAmount($journal, $piggyBank, $destination->amount);
return true; return true;
} }
if ((int)$destination->account_id === (int)$piggyBank->account_id) { if ((int) $destination->account_id === (int) $piggyBank->account_id) {
Log::debug('Piggy bank account is linked to source, so add amount.'); Log::debug('Piggy bank account is linked to source, so add amount.');
$this->addAmount($journal, $piggyBank, $destination->amount); $this->addAmount($journal, $piggyBank, $destination->amount);

View File

@@ -86,84 +86,6 @@ class SearchRuleEngine implements RuleEngineInterface
return $collection->unique(); return $collection->unique();
} }
/**
* @inheritDoc
* @throws FireflyException
*/
public function fire(): void
{
$this->resultCount = [];
Log::debug('SearchRuleEngine::fire()!');
// if rules and no rule groups, file each rule separately.
if (0 !== $this->rules->count()) {
Log::debug(sprintf('SearchRuleEngine:: found %d rule(s) to fire.', $this->rules->count()));
foreach ($this->rules as $rule) {
$this->fireRule($rule);
}
Log::debug('SearchRuleEngine:: done processing all rules!');
return;
}
if (0 !== $this->groups->count()) {
Log::debug(sprintf('SearchRuleEngine:: found %d rule group(s) to fire.', $this->groups->count()));
// fire each group:
/** @var RuleGroup $group */
foreach ($this->groups as $group) {
$this->fireGroup($group);
}
}
Log::debug('SearchRuleEngine:: done processing all rules!');
}
/**
* Return the number of changed transactions from the previous "fire" action.
*
* @return int
*/
public function getResults(): int
{
return count($this->resultCount);
}
/**
* @inheritDoc
*/
public function setRuleGroups(Collection $ruleGroups): void
{
Log::debug(__METHOD__);
foreach ($ruleGroups as $group) {
if ($group instanceof RuleGroup) {
Log::debug(sprintf('Adding a rule group to the SearchRuleEngine: #%d ("%s")', $group->id, $group->title));
$this->groups->push($group);
}
}
}
/**
* @inheritDoc
*/
public function setRules(Collection $rules): void
{
Log::debug(__METHOD__);
foreach ($rules as $rule) {
if ($rule instanceof Rule) {
Log::debug(sprintf('Adding a rule to the SearchRuleEngine: #%d ("%s")', $rule->id, $rule->title));
$this->rules->push($rule);
}
}
}
/**
* @inheritDoc
*/
public function setUser(User $user): void
{
$this->user = $user;
$this->operators = [];
}
/** /**
* Finds the transactions a strict rule will execute on. * Finds the transactions a strict rule will execute on.
* *
@@ -266,7 +188,7 @@ class SearchRuleEngine implements RuleEngineInterface
$journalId = 0; $journalId = 0;
foreach ($array as $triggerName => $values) { foreach ($array as $triggerName => $values) {
if ('journal_id' === $triggerName && is_array($values) && 1 === count($values)) { if ('journal_id' === $triggerName && is_array($values) && 1 === count($values)) {
$journalId = (int)trim(($values[0] ?? '"0"'), '"'); // follows format "123". $journalId = (int) trim(($values[0] ?? '"0"'), '"'); // follows format "123".
Log::debug(sprintf('Found journal ID #%d', $journalId)); Log::debug(sprintf('Found journal ID #%d', $journalId));
} }
} }
@@ -365,6 +287,36 @@ class SearchRuleEngine implements RuleEngineInterface
return $unique; return $unique;
} }
/**
* @inheritDoc
* @throws FireflyException
*/
public function fire(): void
{
$this->resultCount = [];
Log::debug('SearchRuleEngine::fire()!');
// if rules and no rule groups, file each rule separately.
if (0 !== $this->rules->count()) {
Log::debug(sprintf('SearchRuleEngine:: found %d rule(s) to fire.', $this->rules->count()));
foreach ($this->rules as $rule) {
$this->fireRule($rule);
}
Log::debug('SearchRuleEngine:: done processing all rules!');
return;
}
if (0 !== $this->groups->count()) {
Log::debug(sprintf('SearchRuleEngine:: found %d rule group(s) to fire.', $this->groups->count()));
// fire each group:
/** @var RuleGroup $group */
foreach ($this->groups as $group) {
$this->fireGroup($group);
}
}
Log::debug('SearchRuleEngine:: done processing all rules!');
}
/** /**
* Returns true if the rule has been triggered. * Returns true if the rule has been triggered.
* *
@@ -460,7 +412,7 @@ class SearchRuleEngine implements RuleEngineInterface
$actions = $rule->ruleActions()->get(); $actions = $rule->ruleActions()->get();
/** @var RuleAction $ruleAction */ /** @var RuleAction $ruleAction */
foreach ($actions as $ruleAction) { foreach ($actions as $ruleAction) {
if(false === $ruleAction->active) { if (false === $ruleAction->active) {
continue; continue;
} }
$break = $this->processRuleAction($ruleAction, $transaction); $break = $this->processRuleAction($ruleAction, $transaction);
@@ -553,4 +505,52 @@ class SearchRuleEngine implements RuleEngineInterface
return $all; return $all;
} }
/**
* Return the number of changed transactions from the previous "fire" action.
*
* @return int
*/
public function getResults(): int
{
return count($this->resultCount);
}
/**
* @inheritDoc
*/
public function setRuleGroups(Collection $ruleGroups): void
{
Log::debug(__METHOD__);
foreach ($ruleGroups as $group) {
if ($group instanceof RuleGroup) {
Log::debug(sprintf('Adding a rule group to the SearchRuleEngine: #%d ("%s")', $group->id, $group->title));
$this->groups->push($group);
}
}
}
/**
* @inheritDoc
*/
public function setRules(Collection $rules): void
{
Log::debug(__METHOD__);
foreach ($rules as $rule) {
if ($rule instanceof Rule) {
Log::debug(sprintf('Adding a rule to the SearchRuleEngine: #%d ("%s")', $rule->id, $rule->title));
$this->rules->push($rule);
}
}
}
/**
* @inheritDoc
*/
public function setUser(User $user): void
{
$this->user = $user;
$this->operators = [];
}
} }

View File

@@ -62,8 +62,8 @@ class AccountTransformer extends AbstractTransformer
// get account type: // get account type:
$fullType = $account->accountType->type; $fullType = $account->accountType->type;
$accountType = (string)config(sprintf('firefly.shortNamesByFullName.%s', $fullType)); $accountType = (string) config(sprintf('firefly.shortNamesByFullName.%s', $fullType));
$liabilityType = (string)config(sprintf('firefly.shortLiabilityNameByFullName.%s', $fullType)); $liabilityType = (string) config(sprintf('firefly.shortLiabilityNameByFullName.%s', $fullType));
$liabilityType = '' === $liabilityType ? null : strtolower($liabilityType); $liabilityType = '' === $liabilityType ? null : strtolower($liabilityType);
$liabilityDirection = $this->repository->getMetaValue($account, 'liability_direction'); $liabilityDirection = $this->repository->getMetaValue($account, 'liability_direction');
@@ -77,7 +77,7 @@ class AccountTransformer extends AbstractTransformer
[$openingBalance, $openingBalanceDate] = $this->getOpeningBalance($account, $accountType); [$openingBalance, $openingBalanceDate] = $this->getOpeningBalance($account, $accountType);
[$interest, $interestPeriod] = $this->getInterest($account, $accountType); [$interest, $interestPeriod] = $this->getInterest($account, $accountType);
$openingBalance = number_format((float)$openingBalance, $decimalPlaces, '.', ''); $openingBalance = number_format((float) $openingBalance, $decimalPlaces, '.', '');
$includeNetWorth = '0' !== $this->repository->getMetaValue($account, 'include_net_worth'); $includeNetWorth = '0' !== $this->repository->getMetaValue($account, 'include_net_worth');
$longitude = null; $longitude = null;
$latitude = null; $latitude = null;
@@ -86,17 +86,17 @@ class AccountTransformer extends AbstractTransformer
if (null !== $location) { if (null !== $location) {
$longitude = $location->longitude; $longitude = $location->longitude;
$latitude = $location->latitude; $latitude = $location->latitude;
$zoomLevel = (int)$location->zoom_level; $zoomLevel = (int) $location->zoom_level;
} }
// no order for some accounts: // no order for some accounts:
$order = (int)$account->order; $order = (int) $account->order;
if (!in_array(strtolower($accountType), ['liability', 'liabilities', 'asset'])) { if (!in_array(strtolower($accountType), ['liability', 'liabilities', 'asset'])) {
$order = null; $order = null;
} }
return [ return [
'id' => (string)$account->id, 'id' => (string) $account->id,
'created_at' => $account->created_at->toAtomString(), 'created_at' => $account->created_at->toAtomString(),
'updated_at' => $account->updated_at->toAtomString(), 'updated_at' => $account->updated_at->toAtomString(),
'active' => $account->active, 'active' => $account->active,
@@ -108,7 +108,7 @@ class AccountTransformer extends AbstractTransformer
'currency_code' => $currencyCode, 'currency_code' => $currencyCode,
'currency_symbol' => $currencySymbol, 'currency_symbol' => $currencySymbol,
'currency_decimal_places' => $decimalPlaces, 'currency_decimal_places' => $decimalPlaces,
'current_balance' => number_format((float)app('steam')->balance($account, $date), $decimalPlaces, '.', ''), 'current_balance' => number_format((float) app('steam')->balance($account, $date), $decimalPlaces, '.', ''),
'current_balance_date' => $date->toAtomString(), 'current_balance_date' => $date->toAtomString(),
'notes' => $this->repository->getNoteText($account), 'notes' => $this->repository->getNoteText($account),
'monthly_payment_date' => $monthlyPaymentDate, 'monthly_payment_date' => $monthlyPaymentDate,
@@ -116,7 +116,7 @@ class AccountTransformer extends AbstractTransformer
'account_number' => $this->repository->getMetaValue($account, 'account_number'), 'account_number' => $this->repository->getMetaValue($account, 'account_number'),
'iban' => '' === $account->iban ? null : $account->iban, 'iban' => '' === $account->iban ? null : $account->iban,
'bic' => $this->repository->getMetaValue($account, 'BIC'), 'bic' => $this->repository->getMetaValue($account, 'BIC'),
'virtual_balance' => number_format((float)$account->virtual_balance, $decimalPlaces, '.', ''), 'virtual_balance' => number_format((float) $account->virtual_balance, $decimalPlaces, '.', ''),
'opening_balance' => $openingBalance, 'opening_balance' => $openingBalance,
'opening_balance_date' => $openingBalanceDate, 'opening_balance_date' => $openingBalanceDate,
'liability_type' => $liabilityType, 'liability_type' => $liabilityType,
@@ -147,7 +147,7 @@ class AccountTransformer extends AbstractTransformer
private function getAccountRole(Account $account, string $accountType): ?string private function getAccountRole(Account $account, string $accountType): ?string
{ {
$accountRole = $this->repository->getMetaValue($account, 'account_role'); $accountRole = $this->repository->getMetaValue($account, 'account_role');
if ('asset' !== $accountType || '' === (string)$accountRole) { if ('asset' !== $accountType || '' === (string) $accountRole) {
$accountRole = null; $accountRole = null;
} }
@@ -180,7 +180,7 @@ class AccountTransformer extends AbstractTransformer
if (null === $currency) { if (null === $currency) {
$currency = app('amount')->getDefaultCurrencyByUser($account->user); $currency = app('amount')->getDefaultCurrencyByUser($account->user);
} }
$currencyId = (string)$currency->id; $currencyId = (string) $currency->id;
$currencyCode = $currency->code; $currencyCode = $currency->code;
$decimalPlaces = $currency->decimal_places; $decimalPlaces = $currency->decimal_places;
$currencySymbol = $currency->symbol; $currencySymbol = $currency->symbol;

View File

@@ -55,10 +55,10 @@ class AttachmentTransformer extends AbstractTransformer
$this->repository->setUser($attachment->user); $this->repository->setUser($attachment->user);
return [ return [
'id' => (string)$attachment->id, 'id' => (string) $attachment->id,
'created_at' => $attachment->created_at->toAtomString(), 'created_at' => $attachment->created_at->toAtomString(),
'updated_at' => $attachment->updated_at->toAtomString(), 'updated_at' => $attachment->updated_at->toAtomString(),
'attachable_id' => (string)$attachment->attachable_id, 'attachable_id' => (string) $attachment->attachable_id,
'attachable_type' => str_replace('FireflyIII\\Models\\', '', $attachment->attachable_type), 'attachable_type' => str_replace('FireflyIII\\Models\\', '', $attachment->attachable_type),
'md5' => $attachment->md5, 'md5' => $attachment->md5,
'filename' => $attachment->filename, 'filename' => $attachment->filename,
@@ -67,7 +67,7 @@ class AttachmentTransformer extends AbstractTransformer
'title' => $attachment->title, 'title' => $attachment->title,
'notes' => $this->repository->getNoteText($attachment), 'notes' => $this->repository->getNoteText($attachment),
'mime' => $attachment->mime, 'mime' => $attachment->mime,
'size' => (int)$attachment->size, 'size' => (int) $attachment->size,
'links' => [ 'links' => [
[ [
'rel' => 'self', 'rel' => 'self',

View File

@@ -62,14 +62,14 @@ class AvailableBudgetTransformer extends AbstractTransformer
$currency = $availableBudget->transactionCurrency; $currency = $availableBudget->transactionCurrency;
$data = [ $data = [
'id' => (string)$availableBudget->id, 'id' => (string) $availableBudget->id,
'created_at' => $availableBudget->created_at->toAtomString(), 'created_at' => $availableBudget->created_at->toAtomString(),
'updated_at' => $availableBudget->updated_at->toAtomString(), 'updated_at' => $availableBudget->updated_at->toAtomString(),
'currency_id' => (string)$currency->id, 'currency_id' => (string) $currency->id,
'currency_code' => $currency->code, 'currency_code' => $currency->code,
'currency_symbol' => $currency->symbol, 'currency_symbol' => $currency->symbol,
'currency_decimal_places' => (int)$currency->decimal_places, 'currency_decimal_places' => (int) $currency->decimal_places,
'amount' => number_format((float)$availableBudget->amount, $currency->decimal_places, '.', ''), 'amount' => number_format((float) $availableBudget->amount, $currency->decimal_places, '.', ''),
'start' => $availableBudget->start_date->toAtomString(), 'start' => $availableBudget->start_date->toAtomString(),
'end' => $availableBudget->end_date->endOfDay()->toAtomString(), 'end' => $availableBudget->end_date->endOfDay()->toAtomString(),
'spent_in_budgets' => [], 'spent_in_budgets' => [],

View File

@@ -71,8 +71,8 @@ class BillTransformer extends AbstractTransformer
/** @var ObjectGroup $objectGroup */ /** @var ObjectGroup $objectGroup */
$objectGroup = $bill->objectGroups->first(); $objectGroup = $bill->objectGroups->first();
if (null !== $objectGroup) { if (null !== $objectGroup) {
$objectGroupId = (int)$objectGroup->id; $objectGroupId = (int) $objectGroup->id;
$objectGroupOrder = (int)$objectGroup->order; $objectGroupOrder = (int) $objectGroup->order;
$objectGroupTitle = $objectGroup->title; $objectGroupTitle = $objectGroup->title;
} }
@@ -106,25 +106,25 @@ class BillTransformer extends AbstractTransformer
unset($temp, $temp2); unset($temp, $temp2);
return [ return [
'id' => (int)$bill->id, 'id' => (int) $bill->id,
'created_at' => $bill->created_at->toAtomString(), 'created_at' => $bill->created_at->toAtomString(),
'updated_at' => $bill->updated_at->toAtomString(), 'updated_at' => $bill->updated_at->toAtomString(),
'currency_id' => (string)$bill->transaction_currency_id, 'currency_id' => (string) $bill->transaction_currency_id,
'currency_code' => $currency->code, 'currency_code' => $currency->code,
'currency_symbol' => $currency->symbol, 'currency_symbol' => $currency->symbol,
'currency_decimal_places' => (int)$currency->decimal_places, 'currency_decimal_places' => (int) $currency->decimal_places,
'name' => $bill->name, 'name' => $bill->name,
'amount_min' => number_format((float)$bill->amount_min, $currency->decimal_places, '.', ''), 'amount_min' => number_format((float) $bill->amount_min, $currency->decimal_places, '.', ''),
'amount_max' => number_format((float)$bill->amount_max, $currency->decimal_places, '.', ''), 'amount_max' => number_format((float) $bill->amount_max, $currency->decimal_places, '.', ''),
'date' => $bill->date->toAtomString(), 'date' => $bill->date->toAtomString(),
'end_date' => $bill->end_date?->toAtomString(), 'end_date' => $bill->end_date?->toAtomString(),
'extension_date' => $bill->extension_date?->toAtomString(), 'extension_date' => $bill->extension_date?->toAtomString(),
'repeat_freq' => $bill->repeat_freq, 'repeat_freq' => $bill->repeat_freq,
'skip' => (int)$bill->skip, 'skip' => (int) $bill->skip,
'active' => $bill->active, 'active' => $bill->active,
'order' => (int)$bill->order, 'order' => (int) $bill->order,
'notes' => $notes, 'notes' => $notes,
'object_group_id' => $objectGroupId ? (string)$objectGroupId : null, 'object_group_id' => $objectGroupId ? (string) $objectGroupId : null,
'object_group_order' => $objectGroupOrder, 'object_group_order' => $objectGroupOrder,
'object_group_title' => $objectGroupTitle, 'object_group_title' => $objectGroupTitle,
@@ -202,8 +202,8 @@ class BillTransformer extends AbstractTransformer
$result = []; $result = [];
foreach ($set as $entry) { foreach ($set as $entry) {
$result[] = [ $result[] = [
'transaction_group_id' => (int)$entry->transaction_group_id, 'transaction_group_id' => (int) $entry->transaction_group_id,
'transaction_journal_id' => (int)$entry->id, 'transaction_journal_id' => (int) $entry->id,
'date' => $entry->date->format('Y-m-d'), 'date' => $entry->date->format('Y-m-d'),
]; ];
} }
@@ -267,7 +267,7 @@ class BillTransformer extends AbstractTransformer
$nextExpectedMatch->addDay(); $nextExpectedMatch->addDay();
$currentStart = clone $nextExpectedMatch; $currentStart = clone $nextExpectedMatch;
$loop++; $loop++;
if($loop > 4) { if ($loop > 4) {
break; break;
} }
} }

View File

@@ -74,22 +74,22 @@ class BudgetLimitTransformer extends AbstractTransformer
$currencySymbol = null; $currencySymbol = null;
if (null !== $currency) { if (null !== $currency) {
$amount = $budgetLimit->amount; $amount = $budgetLimit->amount;
$currencyId = (int)$currency->id; $currencyId = (int) $currency->id;
$currencyName = $currency->name; $currencyName = $currency->name;
$currencyCode = $currency->code; $currencyCode = $currency->code;
$currencySymbol = $currency->symbol; $currencySymbol = $currency->symbol;
$currencyDecimalPlaces = $currency->decimal_places; $currencyDecimalPlaces = $currency->decimal_places;
} }
$amount = number_format((float)$amount, $currencyDecimalPlaces, '.', ''); $amount = number_format((float) $amount, $currencyDecimalPlaces, '.', '');
return [ return [
'id' => (string)$budgetLimit->id, 'id' => (string) $budgetLimit->id,
'created_at' => $budgetLimit->created_at->toAtomString(), 'created_at' => $budgetLimit->created_at->toAtomString(),
'updated_at' => $budgetLimit->updated_at->toAtomString(), 'updated_at' => $budgetLimit->updated_at->toAtomString(),
'start' => $budgetLimit->start_date->toAtomString(), 'start' => $budgetLimit->start_date->toAtomString(),
'end' => $budgetLimit->end_date->endOfDay()->toAtomString(), 'end' => $budgetLimit->end_date->endOfDay()->toAtomString(),
'budget_id' => (string)$budgetLimit->budget_id, 'budget_id' => (string) $budgetLimit->budget_id,
'currency_id' => (string)$currencyId, 'currency_id' => (string) $currencyId,
'currency_code' => $currencyCode, 'currency_code' => $currencyCode,
'currency_name' => $currencyName, 'currency_name' => $currencyName,
'currency_decimal_places' => $currencyDecimalPlaces, 'currency_decimal_places' => $currencyDecimalPlaces,

View File

@@ -70,7 +70,7 @@ class CategoryTransformer extends AbstractTransformer
$notes = $this->repository->getNoteText($category); $notes = $this->repository->getNoteText($category);
return [ return [
'id' => (int)$category->id, 'id' => (int) $category->id,
'created_at' => $category->created_at->toAtomString(), 'created_at' => $category->created_at->toAtomString(),
'updated_at' => $category->updated_at->toAtomString(), 'updated_at' => $category->updated_at->toAtomString(),
'name' => $category->name, 'name' => $category->name,
@@ -95,7 +95,7 @@ class CategoryTransformer extends AbstractTransformer
{ {
$return = []; $return = [];
foreach ($array as $data) { foreach ($array as $data) {
$data['sum'] = number_format((float)$data['sum'], (int)$data['currency_decimal_places'], '.', ''); $data['sum'] = number_format((float) $data['sum'], (int) $data['currency_decimal_places'], '.', '');
$return[] = $data; $return[] = $data;
} }

View File

@@ -43,11 +43,11 @@ class CurrencyTransformer extends AbstractTransformer
$isDefault = false; $isDefault = false;
$defaultCurrency = $this->parameters->get('defaultCurrency'); $defaultCurrency = $this->parameters->get('defaultCurrency');
if (null !== $defaultCurrency) { if (null !== $defaultCurrency) {
$isDefault = (int)$defaultCurrency->id === (int)$currency->id; $isDefault = (int) $defaultCurrency->id === (int) $currency->id;
} }
return [ return [
'id' => (int)$currency->id, 'id' => (int) $currency->id,
'created_at' => $currency->created_at->toAtomString(), 'created_at' => $currency->created_at->toAtomString(),
'updated_at' => $currency->updated_at->toAtomString(), 'updated_at' => $currency->updated_at->toAtomString(),
'default' => $isDefault, 'default' => $isDefault,
@@ -55,7 +55,7 @@ class CurrencyTransformer extends AbstractTransformer
'name' => $currency->name, 'name' => $currency->name,
'code' => $currency->code, 'code' => $currency->code,
'symbol' => $currency->symbol, 'symbol' => $currency->symbol,
'decimal_places' => (int)$currency->decimal_places, 'decimal_places' => (int) $currency->decimal_places,
'links' => [ 'links' => [
[ [
'rel' => 'self', 'rel' => 'self',

View File

@@ -41,7 +41,7 @@ class LinkTypeTransformer extends AbstractTransformer
public function transform(LinkType $linkType): array public function transform(LinkType $linkType): array
{ {
return [ return [
'id' => (int)$linkType->id, 'id' => (int) $linkType->id,
'created_at' => $linkType->created_at->toAtomString(), 'created_at' => $linkType->created_at->toAtomString(),
'updated_at' => $linkType->updated_at->toAtomString(), 'updated_at' => $linkType->updated_at->toAtomString(),
'name' => $linkType->name, 'name' => $linkType->name,

View File

@@ -56,11 +56,11 @@ class ObjectGroupTransformer extends AbstractTransformer
$this->repository->setUser($objectGroup->user); $this->repository->setUser($objectGroup->user);
return [ return [
'id' => (string)$objectGroup->id, 'id' => (string) $objectGroup->id,
'created_at' => $objectGroup->created_at->toAtomString(), 'created_at' => $objectGroup->created_at->toAtomString(),
'updated_at' => $objectGroup->updated_at->toAtomString(), 'updated_at' => $objectGroup->updated_at->toAtomString(),
'title' => $objectGroup->title, 'title' => $objectGroup->title,
'order' => (int)$objectGroup->order, 'order' => (int) $objectGroup->order,
'links' => [ 'links' => [
[ [
'rel' => 'self', 'rel' => 'self',

View File

@@ -72,22 +72,22 @@ class PiggyBankEventTransformer extends AbstractTransformer
// get associated journal and transaction, if any: // get associated journal and transaction, if any:
$journalId = $event->transaction_journal_id; $journalId = $event->transaction_journal_id;
$groupId = null; $groupId = null;
if (0 !== (int)$journalId) { if (0 !== (int) $journalId) {
$groupId = (int)$event->transactionJournal->transaction_group_id; $groupId = (int) $event->transactionJournal->transaction_group_id;
$journalId = (int)$journalId; $journalId = (int) $journalId;
} }
return [ return [
'id' => (string)$event->id, 'id' => (string) $event->id,
'created_at' => $event->created_at->toAtomString(), 'created_at' => $event->created_at->toAtomString(),
'updated_at' => $event->updated_at->toAtomString(), 'updated_at' => $event->updated_at->toAtomString(),
'amount' => number_format((float)$event->amount, $currency->decimal_places, '.', ''), 'amount' => number_format((float) $event->amount, $currency->decimal_places, '.', ''),
'currency_id' => (string)$currency->id, 'currency_id' => (string) $currency->id,
'currency_code' => $currency->code, 'currency_code' => $currency->code,
'currency_symbol' => $currency->symbol, 'currency_symbol' => $currency->symbol,
'currency_decimal_places' => (int)$currency->decimal_places, 'currency_decimal_places' => (int) $currency->decimal_places,
'transaction_journal_id' => $journalId ? (string)$journalId : null, 'transaction_journal_id' => $journalId ? (string) $journalId : null,
'transaction_group_id' => $groupId ? (string)$groupId : null, 'transaction_group_id' => $groupId ? (string) $groupId : null,
'links' => [ 'links' => [
[ [
'rel' => 'self', 'rel' => 'self',

View File

@@ -40,7 +40,7 @@ class PreferenceTransformer extends AbstractTransformer
public function transform(Preference $preference): array public function transform(Preference $preference): array
{ {
return [ return [
'id' => (int)$preference->id, 'id' => (int) $preference->id,
'created_at' => $preference->created_at->toAtomString(), 'created_at' => $preference->created_at->toAtomString(),
'updated_at' => $preference->updated_at->toAtomString(), 'updated_at' => $preference->updated_at->toAtomString(),
'name' => $preference->name, 'name' => $preference->name,

View File

@@ -80,14 +80,14 @@ class RecurrenceTransformer extends AbstractTransformer
$this->budgetRepos->setUser($recurrence->user); $this->budgetRepos->setUser($recurrence->user);
Log::debug('Set user.'); Log::debug('Set user.');
$shortType = (string)config(sprintf('firefly.transactionTypesToShort.%s', $recurrence->transactionType->type)); $shortType = (string) config(sprintf('firefly.transactionTypesToShort.%s', $recurrence->transactionType->type));
$notes = $this->repository->getNoteText($recurrence); $notes = $this->repository->getNoteText($recurrence);
$reps = 0 === (int)$recurrence->repetitions ? null : (int)$recurrence->repetitions; $reps = 0 === (int) $recurrence->repetitions ? null : (int) $recurrence->repetitions;
Log::debug('Get basic data.'); Log::debug('Get basic data.');
// basic data. // basic data.
return [ return [
'id' => (string)$recurrence->id, 'id' => (string) $recurrence->id,
'created_at' => $recurrence->created_at->toAtomString(), 'created_at' => $recurrence->created_at->toAtomString(),
'updated_at' => $recurrence->updated_at->toAtomString(), 'updated_at' => $recurrence->updated_at->toAtomString(),
'type' => $shortType, 'type' => $shortType,
@@ -126,13 +126,13 @@ class RecurrenceTransformer extends AbstractTransformer
/** @var RecurrenceRepetition $repetition */ /** @var RecurrenceRepetition $repetition */
foreach ($recurrence->recurrenceRepetitions as $repetition) { foreach ($recurrence->recurrenceRepetitions as $repetition) {
$repetitionArray = [ $repetitionArray = [
'id' => (string)$repetition->id, 'id' => (string) $repetition->id,
'created_at' => $repetition->created_at->toAtomString(), 'created_at' => $repetition->created_at->toAtomString(),
'updated_at' => $repetition->updated_at->toAtomString(), 'updated_at' => $repetition->updated_at->toAtomString(),
'type' => $repetition->repetition_type, 'type' => $repetition->repetition_type,
'moment' => $repetition->repetition_moment, 'moment' => $repetition->repetition_moment,
'skip' => (int)$repetition->repetition_skip, 'skip' => (int) $repetition->repetition_skip,
'weekend' => (int)$repetition->weekend, 'weekend' => (int) $repetition->weekend,
'description' => $this->repository->repetitionDescription($repetition), 'description' => $this->repository->repetitionDescription($repetition),
'occurrences' => [], 'occurrences' => [],
]; ];
@@ -171,10 +171,10 @@ class RecurrenceTransformer extends AbstractTransformer
$foreignCurrencyDp = null; $foreignCurrencyDp = null;
$foreignCurrencyId = null; $foreignCurrencyId = null;
if (null !== $transaction->foreign_currency_id) { if (null !== $transaction->foreign_currency_id) {
$foreignCurrencyId = (int)$transaction->foreign_currency_id; $foreignCurrencyId = (int) $transaction->foreign_currency_id;
$foreignCurrencyCode = $transaction->foreignCurrency->code; $foreignCurrencyCode = $transaction->foreignCurrency->code;
$foreignCurrencySymbol = $transaction->foreignCurrency->symbol; $foreignCurrencySymbol = $transaction->foreignCurrency->symbol;
$foreignCurrencyDp = (int)$transaction->foreignCurrency->decimal_places; $foreignCurrencyDp = (int) $transaction->foreignCurrency->decimal_places;
} }
// source info: // source info:
@@ -184,7 +184,7 @@ class RecurrenceTransformer extends AbstractTransformer
$sourceIban = null; $sourceIban = null;
if (null !== $sourceAccount) { if (null !== $sourceAccount) {
$sourceName = $sourceAccount->name; $sourceName = $sourceAccount->name;
$sourceId = (int)$sourceAccount->id; $sourceId = (int) $sourceAccount->id;
$sourceType = $sourceAccount->accountType->type; $sourceType = $sourceAccount->accountType->type;
$sourceIban = $sourceAccount->iban; $sourceIban = $sourceAccount->iban;
} }
@@ -194,29 +194,29 @@ class RecurrenceTransformer extends AbstractTransformer
$destinationIban = null; $destinationIban = null;
if (null !== $destinationAccount) { if (null !== $destinationAccount) {
$destinationName = $destinationAccount->name; $destinationName = $destinationAccount->name;
$destinationId = (int)$destinationAccount->id; $destinationId = (int) $destinationAccount->id;
$destinationType = $destinationAccount->accountType->type; $destinationType = $destinationAccount->accountType->type;
$destinationIban = $destinationAccount->iban; $destinationIban = $destinationAccount->iban;
} }
$amount = number_format((float)$transaction->amount, $transaction->transactionCurrency->decimal_places, '.', ''); $amount = number_format((float) $transaction->amount, $transaction->transactionCurrency->decimal_places, '.', '');
$foreignAmount = null; $foreignAmount = null;
if (null !== $transaction->foreign_currency_id && null !== $transaction->foreign_amount) { if (null !== $transaction->foreign_currency_id && null !== $transaction->foreign_amount) {
$foreignAmount = number_format((float)$transaction->foreign_amount, $foreignCurrencyDp, '.', ''); $foreignAmount = number_format((float) $transaction->foreign_amount, $foreignCurrencyDp, '.', '');
} }
$transactionArray = [ $transactionArray = [
'currency_id' => (string)$transaction->transaction_currency_id, 'currency_id' => (string) $transaction->transaction_currency_id,
'currency_code' => $transaction->transactionCurrency->code, 'currency_code' => $transaction->transactionCurrency->code,
'currency_symbol' => $transaction->transactionCurrency->symbol, 'currency_symbol' => $transaction->transactionCurrency->symbol,
'currency_decimal_places' => (int)$transaction->transactionCurrency->decimal_places, 'currency_decimal_places' => (int) $transaction->transactionCurrency->decimal_places,
'foreign_currency_id' => null === $foreignCurrencyId ? null : (string)$foreignCurrencyId, 'foreign_currency_id' => null === $foreignCurrencyId ? null : (string) $foreignCurrencyId,
'foreign_currency_code' => $foreignCurrencyCode, 'foreign_currency_code' => $foreignCurrencyCode,
'foreign_currency_symbol' => $foreignCurrencySymbol, 'foreign_currency_symbol' => $foreignCurrencySymbol,
'foreign_currency_decimal_places' => $foreignCurrencyDp, 'foreign_currency_decimal_places' => $foreignCurrencyDp,
'source_id' => (string)$sourceId, 'source_id' => (string) $sourceId,
'source_name' => $sourceName, 'source_name' => $sourceName,
'source_iban' => $sourceIban, 'source_iban' => $sourceIban,
'source_type' => $sourceType, 'source_type' => $sourceType,
'destination_id' => (string)$destinationId, 'destination_id' => (string) $destinationId,
'destination_name' => $destinationName, 'destination_name' => $destinationName,
'destination_iban' => $destinationIban, 'destination_iban' => $destinationIban,
'destination_type' => $destinationType, 'destination_type' => $destinationType,
@@ -264,9 +264,9 @@ class RecurrenceTransformer extends AbstractTransformer
default: default:
throw new FireflyException(sprintf('Recurrence transformer cant handle field "%s"', $transactionMeta->name)); throw new FireflyException(sprintf('Recurrence transformer cant handle field "%s"', $transactionMeta->name));
case 'bill_id': case 'bill_id':
$bill = $this->billRepos->find((int)$transactionMeta->value); $bill = $this->billRepos->find((int) $transactionMeta->value);
if (null !== $bill) { if (null !== $bill) {
$array['bill_id'] = (string)$bill->id; $array['bill_id'] = (string) $bill->id;
$array['bill_name'] = $bill->name; $array['bill_name'] = $bill->name;
} }
break; break;
@@ -274,30 +274,30 @@ class RecurrenceTransformer extends AbstractTransformer
$array['tags'] = json_decode($transactionMeta->value); $array['tags'] = json_decode($transactionMeta->value);
break; break;
case 'piggy_bank_id': case 'piggy_bank_id':
$piggy = $this->piggyRepos->find((int)$transactionMeta->value); $piggy = $this->piggyRepos->find((int) $transactionMeta->value);
if (null !== $piggy) { if (null !== $piggy) {
$array['piggy_bank_id'] = (string)$piggy->id; $array['piggy_bank_id'] = (string) $piggy->id;
$array['piggy_bank_name'] = $piggy->name; $array['piggy_bank_name'] = $piggy->name;
} }
break; break;
case 'category_id': case 'category_id':
$category = $this->factory->findOrCreate((int)$transactionMeta->value, null); $category = $this->factory->findOrCreate((int) $transactionMeta->value, null);
if (null !== $category) { if (null !== $category) {
$array['category_id'] = (string)$category->id; $array['category_id'] = (string) $category->id;
$array['category_name'] = $category->name; $array['category_name'] = $category->name;
} }
break; break;
case 'category_name': case 'category_name':
$category = $this->factory->findOrCreate(null, $transactionMeta->value); $category = $this->factory->findOrCreate(null, $transactionMeta->value);
if (null !== $category) { if (null !== $category) {
$array['category_id'] = (string)$category->id; $array['category_id'] = (string) $category->id;
$array['category_name'] = $category->name; $array['category_name'] = $category->name;
} }
break; break;
case 'budget_id': case 'budget_id':
$budget = $this->budgetRepos->find((int)$transactionMeta->value); $budget = $this->budgetRepos->find((int) $transactionMeta->value);
if (null !== $budget) { if (null !== $budget) {
$array['budget_id'] = (string)$budget->id; $array['budget_id'] = (string) $budget->id;
$array['budget_name'] = $budget->name; $array['budget_name'] = $budget->name;
} }
break; break;

View File

@@ -41,7 +41,7 @@ class RuleGroupTransformer extends AbstractTransformer
public function transform(RuleGroup $ruleGroup): array public function transform(RuleGroup $ruleGroup): array
{ {
return [ return [
'id' => (int)$ruleGroup->id, 'id' => (int) $ruleGroup->id,
'created_at' => $ruleGroup->created_at->toAtomString(), 'created_at' => $ruleGroup->created_at->toAtomString(),
'updated_at' => $ruleGroup->updated_at->toAtomString(), 'updated_at' => $ruleGroup->updated_at->toAtomString(),
'title' => $ruleGroup->title, 'title' => $ruleGroup->title,

View File

@@ -60,21 +60,21 @@ class RuleTransformer extends AbstractTransformer
$this->ruleRepository->setUser($rule->user); $this->ruleRepository->setUser($rule->user);
return [ return [
'id' => (string)$rule->id, 'id' => (string) $rule->id,
'created_at' => $rule->created_at->toAtomString(), 'created_at' => $rule->created_at->toAtomString(),
'updated_at' => $rule->updated_at->toAtomString(), 'updated_at' => $rule->updated_at->toAtomString(),
'rule_group_id' => (string)$rule->rule_group_id, 'rule_group_id' => (string) $rule->rule_group_id,
'rule_group_title' => (string)$rule->ruleGroup->title, 'rule_group_title' => (string) $rule->ruleGroup->title,
'title' => $rule->title, 'title' => $rule->title,
'description' => $rule->description, 'description' => $rule->description,
'order' => (int)$rule->order, 'order' => (int) $rule->order,
'active' => $rule->active, 'active' => $rule->active,
'strict' => $rule->strict, 'strict' => $rule->strict,
'stop_processing' => $rule->stop_processing, 'stop_processing' => $rule->stop_processing,
'trigger' => $this->getRuleTrigger($rule), 'trigger' => $this->getRuleTrigger($rule),
'triggers' => $this->triggers($rule), 'triggers' => $this->triggers($rule),
'actions' => $this->actions($rule), 'actions' => $this->actions($rule),
'links' => [ 'links' => [
[ [
'rel' => 'self', 'rel' => 'self',
'uri' => '/rules/' . $rule->id, 'uri' => '/rules/' . $rule->id,
@@ -121,7 +121,7 @@ class RuleTransformer extends AbstractTransformer
continue; continue;
} }
$result[] = [ $result[] = [
'id' => (string)$ruleTrigger->id, 'id' => (string) $ruleTrigger->id,
'created_at' => $ruleTrigger->created_at->toAtomString(), 'created_at' => $ruleTrigger->created_at->toAtomString(),
'updated_at' => $ruleTrigger->updated_at->toAtomString(), 'updated_at' => $ruleTrigger->updated_at->toAtomString(),
'type' => $ruleTrigger->trigger_type, 'type' => $ruleTrigger->trigger_type,
@@ -147,7 +147,7 @@ class RuleTransformer extends AbstractTransformer
/** @var RuleAction $ruleAction */ /** @var RuleAction $ruleAction */
foreach ($actions as $ruleAction) { foreach ($actions as $ruleAction) {
$result[] = [ $result[] = [
'id' => (string)$ruleAction->id, 'id' => (string) $ruleAction->id,
'created_at' => $ruleAction->created_at->toAtomString(), 'created_at' => $ruleAction->created_at->toAtomString(),
'updated_at' => $ruleAction->updated_at->toAtomString(), 'updated_at' => $ruleAction->updated_at->toAtomString(),
'type' => $ruleAction->action_type, 'type' => $ruleAction->action_type,

View File

@@ -52,11 +52,11 @@ class TagTransformer extends AbstractTransformer
if (null !== $location) { if (null !== $location) {
$latitude = $location->latitude; $latitude = $location->latitude;
$longitude = $location->longitude; $longitude = $location->longitude;
$zoomLevel = (int)$location->zoom_level; $zoomLevel = (int) $location->zoom_level;
} }
return [ return [
'id' => (int)$tag->id, 'id' => (int) $tag->id,
'created_at' => $tag->created_at->toAtomString(), 'created_at' => $tag->created_at->toAtomString(),
'updated_at' => $tag->updated_at->toAtomString(), 'updated_at' => $tag->updated_at->toAtomString(),
'tag' => $tag->tag, 'tag' => $tag->tag,

View File

@@ -75,10 +75,10 @@ class TransactionGroupTransformer extends AbstractTransformer
$first = new NullArrayObject(reset($group['transactions'])); $first = new NullArrayObject(reset($group['transactions']));
return [ return [
'id' => (int)$first['transaction_group_id'], 'id' => (int) $first['transaction_group_id'],
'created_at' => $first['created_at']->toAtomString(), 'created_at' => $first['created_at']->toAtomString(),
'updated_at' => $first['updated_at']->toAtomString(), 'updated_at' => $first['updated_at']->toAtomString(),
'user' => (string)$data['user_id'], 'user' => (string) $data['user_id'],
'group_title' => $data['title'], 'group_title' => $data['title'],
'transactions' => $this->transformTransactions($data), 'transactions' => $this->transformTransactions($data),
'links' => [ 'links' => [
@@ -123,13 +123,13 @@ class TransactionGroupTransformer extends AbstractTransformer
$foreignAmount = app('steam')->positive($row['foreign_amount']); $foreignAmount = app('steam')->positive($row['foreign_amount']);
} }
$metaFieldData = $this->groupRepos->getMetaFields((int)$row['transaction_journal_id'], $this->metaFields); $metaFieldData = $this->groupRepos->getMetaFields((int) $row['transaction_journal_id'], $this->metaFields);
$metaDateData = $this->groupRepos->getMetaDateFields((int)$row['transaction_journal_id'], $this->metaDateFields); $metaDateData = $this->groupRepos->getMetaDateFields((int) $row['transaction_journal_id'], $this->metaDateFields);
$longitude = null; $longitude = null;
$latitude = null; $latitude = null;
$zoomLevel = null; $zoomLevel = null;
$location = $this->getLocationById((int)$row['transaction_journal_id']); $location = $this->getLocationById((int) $row['transaction_journal_id']);
if (null !== $location) { if (null !== $location) {
$longitude = $location->longitude; $longitude = $location->longitude;
$latitude = $location->latitude; $latitude = $location->latitude;
@@ -137,17 +137,17 @@ class TransactionGroupTransformer extends AbstractTransformer
} }
return [ return [
'user' => (string)$row['user_id'], 'user' => (string) $row['user_id'],
'transaction_journal_id' => (string)$row['transaction_journal_id'], 'transaction_journal_id' => (string) $row['transaction_journal_id'],
'type' => strtolower($type), 'type' => strtolower($type),
'date' => $row['date']->toAtomString(), 'date' => $row['date']->toAtomString(),
'order' => $row['order'], 'order' => $row['order'],
'currency_id' => (string)$row['currency_id'], 'currency_id' => (string) $row['currency_id'],
'currency_code' => $row['currency_code'], 'currency_code' => $row['currency_code'],
'currency_name' => $row['currency_name'], 'currency_name' => $row['currency_name'],
'currency_symbol' => $row['currency_symbol'], 'currency_symbol' => $row['currency_symbol'],
'currency_decimal_places' => (int)$row['currency_decimal_places'], 'currency_decimal_places' => (int) $row['currency_decimal_places'],
'foreign_currency_id' => $this->stringFromArray($transaction, 'foreign_currency_id', null), 'foreign_currency_id' => $this->stringFromArray($transaction, 'foreign_currency_id', null),
'foreign_currency_code' => $row['foreign_currency_code'], 'foreign_currency_code' => $row['foreign_currency_code'],
@@ -159,12 +159,12 @@ class TransactionGroupTransformer extends AbstractTransformer
'description' => $row['description'], 'description' => $row['description'],
'source_id' => (string)$row['source_account_id'], 'source_id' => (string) $row['source_account_id'],
'source_name' => $row['source_account_name'], 'source_name' => $row['source_account_name'],
'source_iban' => $row['source_account_iban'], 'source_iban' => $row['source_account_iban'],
'source_type' => $row['source_account_type'], 'source_type' => $row['source_account_type'],
'destination_id' => (string)$row['destination_account_id'], 'destination_id' => (string) $row['destination_account_id'],
'destination_name' => $row['destination_account_name'], 'destination_name' => $row['destination_account_name'],
'destination_iban' => $row['destination_account_iban'], 'destination_iban' => $row['destination_account_iban'],
'destination_type' => $row['destination_account_type'], 'destination_type' => $row['destination_account_type'],
@@ -179,8 +179,8 @@ class TransactionGroupTransformer extends AbstractTransformer
'bill_name' => $row['bill_name'], 'bill_name' => $row['bill_name'],
'reconciled' => $row['reconciled'], 'reconciled' => $row['reconciled'],
'notes' => $this->groupRepos->getNoteText((int)$row['transaction_journal_id']), 'notes' => $this->groupRepos->getNoteText((int) $row['transaction_journal_id']),
'tags' => $this->groupRepos->getTags((int)$row['transaction_journal_id']), 'tags' => $this->groupRepos->getTags((int) $row['transaction_journal_id']),
'internal_reference' => $metaFieldData['internal_reference'], 'internal_reference' => $metaFieldData['internal_reference'],
'external_id' => $metaFieldData['external_id'], 'external_id' => $metaFieldData['external_id'],
@@ -213,7 +213,7 @@ class TransactionGroupTransformer extends AbstractTransformer
'latitude' => $latitude, 'latitude' => $latitude,
'zoom_level' => $zoomLevel, 'zoom_level' => $zoomLevel,
'has_attachments' => $this->hasAttachments((int)$row['transaction_journal_id']), 'has_attachments' => $this->hasAttachments((int) $row['transaction_journal_id']),
]; ];
} }
@@ -230,11 +230,11 @@ class TransactionGroupTransformer extends AbstractTransformer
return null; return null;
} }
if (array_key_exists($key, $array) && null !== $array[$key]) { if (array_key_exists($key, $array) && null !== $array[$key]) {
return (string)$array[$key]; return (string) $array[$key];
} }
if (null !== $default) { if (null !== $default) {
return (string)$default; return (string) $default;
} }
return null; return null;
@@ -250,16 +250,6 @@ class TransactionGroupTransformer extends AbstractTransformer
return $this->groupRepos->getLocation($journalId); return $this->groupRepos->getLocation($journalId);
} }
/**
* @param int $journalId
*
* @return bool
*/
private function hasAttachments(int $journalId): bool
{
return $this->groupRepos->countAttachments($journalId) > 0;
}
/** /**
* @param array $array * @param array $array
* @param string $key * @param string $key
@@ -269,7 +259,7 @@ class TransactionGroupTransformer extends AbstractTransformer
private function integerFromArray(array $array, string $key): ?int private function integerFromArray(array $array, string $key): ?int
{ {
if (array_key_exists($key, $array)) { if (array_key_exists($key, $array)) {
return (int)$array[$key]; return (int) $array[$key];
} }
return null; return null;
@@ -290,6 +280,16 @@ class TransactionGroupTransformer extends AbstractTransformer
return $object[$key]->toAtomString(); return $object[$key]->toAtomString();
} }
/**
* @param int $journalId
*
* @return bool
*/
private function hasAttachments(int $journalId): bool
{
return $this->groupRepos->countAttachments($journalId) > 0;
}
/** /**
* @param TransactionGroup $group * @param TransactionGroup $group
* *
@@ -300,10 +300,10 @@ class TransactionGroupTransformer extends AbstractTransformer
{ {
try { try {
$result = [ $result = [
'id' => (int)$group->id, 'id' => (int) $group->id,
'created_at' => $group->created_at->toAtomString(), 'created_at' => $group->created_at->toAtomString(),
'updated_at' => $group->updated_at->toAtomString(), 'updated_at' => $group->updated_at->toAtomString(),
'user' => (int)$group->user_id, 'user' => (int) $group->user_id,
'group_title' => $group->title, 'group_title' => $group->title,
'transactions' => $this->transformJournals($group->transactionJournals), 'transactions' => $this->transformJournals($group->transactionJournals),
'links' => [ 'links' => [
@@ -363,7 +363,7 @@ class TransactionGroupTransformer extends AbstractTransformer
$bill = $this->getBill($journal->bill); $bill = $this->getBill($journal->bill);
if (null !== $foreignAmount && null !== $foreignCurrency) { if (null !== $foreignAmount && null !== $foreignCurrency) {
$foreignAmount = number_format((float)$foreignAmount, $foreignCurrency['decimal_places'] ?? 0, '.', ''); $foreignAmount = number_format((float) $foreignAmount, $foreignCurrency['decimal_places'] ?? 0, '.', '');
} }
$longitude = null; $longitude = null;
@@ -377,33 +377,33 @@ class TransactionGroupTransformer extends AbstractTransformer
} }
return [ return [
'user' => (int)$journal->user_id, 'user' => (int) $journal->user_id,
'transaction_journal_id' => (int)$journal->id, 'transaction_journal_id' => (int) $journal->id,
'type' => strtolower($type), 'type' => strtolower($type),
'date' => $journal->date->toAtomString(), 'date' => $journal->date->toAtomString(),
'order' => $journal->order, 'order' => $journal->order,
'currency_id' => (int)$currency->id, 'currency_id' => (int) $currency->id,
'currency_code' => $currency->code, 'currency_code' => $currency->code,
'currency_symbol' => $currency->symbol, 'currency_symbol' => $currency->symbol,
'currency_decimal_places' => (int)$currency->decimal_places, 'currency_decimal_places' => (int) $currency->decimal_places,
'foreign_currency_id' => $foreignCurrency['id'], 'foreign_currency_id' => $foreignCurrency['id'],
'foreign_currency_code' => $foreignCurrency['code'], 'foreign_currency_code' => $foreignCurrency['code'],
'foreign_currency_symbol' => $foreignCurrency['symbol'], 'foreign_currency_symbol' => $foreignCurrency['symbol'],
'foreign_currency_decimal_places' => $foreignCurrency['decimal_places'], 'foreign_currency_decimal_places' => $foreignCurrency['decimal_places'],
'amount' => number_format((float)$amount, $currency->decimal_places, '.', ''), 'amount' => number_format((float) $amount, $currency->decimal_places, '.', ''),
'foreign_amount' => $foreignAmount, 'foreign_amount' => $foreignAmount,
'description' => $journal->description, 'description' => $journal->description,
'source_id' => (int)$source->account_id, 'source_id' => (int) $source->account_id,
'source_name' => $source->account->name, 'source_name' => $source->account->name,
'source_iban' => $source->account->iban, 'source_iban' => $source->account->iban,
'source_type' => $source->account->accountType->type, 'source_type' => $source->account->accountType->type,
'destination_id' => (int)$destination->account_id, 'destination_id' => (int) $destination->account_id,
'destination_name' => $destination->account->name, 'destination_name' => $destination->account->name,
'destination_iban' => $destination->account->iban, 'destination_iban' => $destination->account->iban,
'destination_type' => $destination->account->accountType->type, 'destination_type' => $destination->account->accountType->type,
@@ -461,7 +461,7 @@ class TransactionGroupTransformer extends AbstractTransformer
{ {
$result = $journal->transactions->first( $result = $journal->transactions->first(
static function (Transaction $transaction) { static function (Transaction $transaction) {
return (float)$transaction->amount < 0; return (float) $transaction->amount < 0;
} }
); );
if (null === $result) { if (null === $result) {
@@ -481,7 +481,7 @@ class TransactionGroupTransformer extends AbstractTransformer
{ {
$result = $journal->transactions->first( $result = $journal->transactions->first(
static function (Transaction $transaction) { static function (Transaction $transaction) {
return (float)$transaction->amount > 0; return (float) $transaction->amount > 0;
} }
); );
if (null === $result) { if (null === $result) {
@@ -565,10 +565,10 @@ class TransactionGroupTransformer extends AbstractTransformer
if (null === $currency) { if (null === $currency) {
return $array; return $array;
} }
$array['id'] = (int)$currency->id; $array['id'] = (int) $currency->id;
$array['code'] = $currency->code; $array['code'] = $currency->code;
$array['symbol'] = $currency->symbol; $array['symbol'] = $currency->symbol;
$array['decimal_places'] = (int)$currency->decimal_places; $array['decimal_places'] = (int) $currency->decimal_places;
return $array; return $array;
} }
@@ -587,7 +587,7 @@ class TransactionGroupTransformer extends AbstractTransformer
if (null === $budget) { if (null === $budget) {
return $array; return $array;
} }
$array['id'] = (int)$budget->id; $array['id'] = (int) $budget->id;
$array['name'] = $budget->name; $array['name'] = $budget->name;
return $array; return $array;
@@ -607,7 +607,7 @@ class TransactionGroupTransformer extends AbstractTransformer
if (null === $category) { if (null === $category) {
return $array; return $array;
} }
$array['id'] = (int)$category->id; $array['id'] = (int) $category->id;
$array['name'] = $category->name; $array['name'] = $category->name;
return $array; return $array;
@@ -627,7 +627,7 @@ class TransactionGroupTransformer extends AbstractTransformer
if (null === $bill) { if (null === $bill) {
return $array; return $array;
} }
$array['id'] = (string)$bill->id; $array['id'] = (string) $bill->id;
$array['name'] = $bill->name; $array['name'] = $bill->name;
return $array; return $array;

View File

@@ -55,12 +55,12 @@ class TransactionLinkTransformer extends AbstractTransformer
$notes = $this->repository->getLinkNoteText($link); $notes = $this->repository->getLinkNoteText($link);
return [ return [
'id' => (string)$link->id, 'id' => (string) $link->id,
'created_at' => $link->created_at->toAtomString(), 'created_at' => $link->created_at->toAtomString(),
'updated_at' => $link->updated_at->toAtomString(), 'updated_at' => $link->updated_at->toAtomString(),
'inward_id' => (string)$link->source_id, 'inward_id' => (string) $link->source_id,
'outward_id' => (string)$link->destination_id, 'outward_id' => (string) $link->destination_id,
'link_type_id' => (string)$link->link_type_id, 'link_type_id' => (string) $link->link_type_id,
'notes' => '' === $notes ? null : $notes, 'notes' => '' === $notes ? null : $notes,
'links' => [ 'links' => [
[ [

View File

@@ -46,11 +46,11 @@ class UserTransformer extends AbstractTransformer
$this->repository = $this->repository ?? app(UserRepositoryInterface::class); $this->repository = $this->repository ?? app(UserRepositoryInterface::class);
return [ return [
'id' => (int)$user->id, 'id' => (int) $user->id,
'created_at' => $user->created_at->toAtomString(), 'created_at' => $user->created_at->toAtomString(),
'updated_at' => $user->updated_at->toAtomString(), 'updated_at' => $user->updated_at->toAtomString(),
'email' => $user->email, 'email' => $user->email,
'blocked' => 1 === (int)$user->blocked, 'blocked' => 1 === (int) $user->blocked,
'blocked_code' => '' === $user->blocked_code ? null : $user->blocked_code, 'blocked_code' => '' === $user->blocked_code ? null : $user->blocked_code,
'role' => $this->repository->getRoleByUser($user), 'role' => $this->repository->getRoleByUser($user),
'links' => [ 'links' => [

View File

@@ -40,11 +40,11 @@ class WebhookAttemptTransformer extends AbstractTransformer
public function transform(WebhookAttempt $attempt): array public function transform(WebhookAttempt $attempt): array
{ {
return [ return [
'id' => (string)$attempt->id, 'id' => (string) $attempt->id,
'created_at' => $attempt->created_at->toAtomString(), 'created_at' => $attempt->created_at->toAtomString(),
'updated_at' => $attempt->updated_at->toAtomString(), 'updated_at' => $attempt->updated_at->toAtomString(),
'webhook_message_id' => (string)$attempt->webhook_message_id, 'webhook_message_id' => (string) $attempt->webhook_message_id,
'status_code' => (int)$attempt->status_code, 'status_code' => (int) $attempt->status_code,
'logs' => $attempt->logs, 'logs' => $attempt->logs,
'response' => $attempt->response, 'response' => $attempt->response,
]; ];

View File

@@ -50,12 +50,12 @@ class WebhookMessageTransformer extends AbstractTransformer
} }
return [ return [
'id' => (string)$message->id, 'id' => (string) $message->id,
'created_at' => $message->created_at->toAtomString(), 'created_at' => $message->created_at->toAtomString(),
'updated_at' => $message->updated_at->toAtomString(), 'updated_at' => $message->updated_at->toAtomString(),
'sent' => $message->sent, 'sent' => $message->sent,
'errored' => $message->errored, 'errored' => $message->errored,
'webhook_id' => (string)$message->webhook_id, 'webhook_id' => (string) $message->webhook_id,
'uuid' => $message->uuid, 'uuid' => $message->uuid,
'message' => $json, 'message' => $json,
]; ];

View File

@@ -52,7 +52,7 @@ class WebhookTransformer extends AbstractTransformer
public function transform(Webhook $webhook): array public function transform(Webhook $webhook): array
{ {
return [ return [
'id' => (int)$webhook->id, 'id' => (int) $webhook->id,
'created_at' => $webhook->created_at->toAtomString(), 'created_at' => $webhook->created_at->toAtomString(),
'updated_at' => $webhook->updated_at->toAtomString(), 'updated_at' => $webhook->updated_at->toAtomString(),
'active' => $webhook->active, 'active' => $webhook->active,

View File

@@ -40,7 +40,7 @@ trait DepositValidation
abstract protected function canCreateTypes(array $accountTypes): bool; abstract protected function canCreateTypes(array $accountTypes): bool;
/** /**
* @param array $validTypes * @param array $validTypes
* @param array $data * @param array $data
* *
* @return Account|null * @return Account|null
@@ -65,7 +65,7 @@ trait DepositValidation
if (null === $accountId && null === $accountName && false === $this->canCreateTypes($validTypes)) { if (null === $accountId && null === $accountName && 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');
Log::error('Both values are NULL, cant create deposit destination.'); Log::error('Both values are NULL, cant create deposit destination.');
$result = false; $result = false;
} }
@@ -80,7 +80,7 @@ trait DepositValidation
$search = $this->findExistingAccount($validTypes, $array); $search = $this->findExistingAccount($validTypes, $array);
if (null === $search) { if (null === $search) {
Log::debug('findExistingAccount() returned NULL, so the result is false.'); 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) {
@@ -114,7 +114,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;
} }

View File

@@ -48,7 +48,7 @@ trait LiabilityValidation
$validTypes = config('firefly.valid_liabilities'); $validTypes = config('firefly.valid_liabilities');
if (null === $accountId) { if (null === $accountId) {
$this->sourceError = (string)trans('validation.lc_destination_need_data'); $this->sourceError = (string) trans('validation.lc_destination_need_data');
$result = false; $result = false;
} }
@@ -82,7 +82,7 @@ trait LiabilityValidation
protected function validateLCSource(array $array): bool protected function validateLCSource(array $array): bool
{ {
$accountName = array_key_exists('name', $array) ? $array['name'] : null; $accountName = array_key_exists('name', $array) ? $array['name'] : null;
$result = true; $result = true;
Log::debug('Now in validateLCDestination', $array); Log::debug('Now in validateLCDestination', $array);
if ('' === $accountName || null === $accountName) { if ('' === $accountName || null === $accountName) {
$result = false; $result = false;

View File

@@ -57,7 +57,7 @@ trait OBValidation
if (null === $accountId && null === $accountName && false === $this->canCreateTypes($validTypes)) { if (null === $accountId && null === $accountName && 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.ob_dest_need_data'); $this->destError = (string) trans('validation.ob_dest_need_data');
Log::error('Both values are NULL, cant create OB destination.'); Log::error('Both values are NULL, cant create OB destination.');
$result = false; $result = false;
} }
@@ -72,7 +72,7 @@ trait OBValidation
$search = $this->findExistingAccount($validTypes, $array); $search = $this->findExistingAccount($validTypes, $array);
if (null === $search) { if (null === $search) {
Log::debug('findExistingAccount() returned NULL, so the result is false.', $validTypes); Log::debug('findExistingAccount() returned NULL, so the result is false.', $validTypes);
$this->destError = (string)trans('validation.ob_dest_bad_data', ['id' => $accountId, 'name' => $accountName]); $this->destError = (string) trans('validation.ob_dest_bad_data', ['id' => $accountId, 'name' => $accountName]);
$result = false; $result = false;
} }
if (null !== $search) { if (null !== $search) {
@@ -108,7 +108,7 @@ trait OBValidation
// 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.ob_source_need_data'); $this->sourceError = (string) trans('validation.ob_source_need_data');
$result = false; $result = false;
} }

View File

@@ -33,8 +33,9 @@ use Log;
*/ */
trait ReconciliationValidation trait ReconciliationValidation
{ {
public ?Account $destination; public ?Account $destination;
public ?Account $source; public ?Account $source;
/** /**
* @param array $array * @param array $array
* *
@@ -42,7 +43,7 @@ trait ReconciliationValidation
*/ */
protected function validateReconciliationDestination(array $array): bool protected function validateReconciliationDestination(array $array): bool
{ {
$accountId = array_key_exists('id', $array) ? $array['id'] : null; $accountId = array_key_exists('id', $array) ? $array['id'] : null;
Log::debug('Now in validateReconciliationDestination', $array); Log::debug('Now in validateReconciliationDestination', $array);
if (null === $accountId) { if (null === $accountId) {
Log::debug('Return FALSE'); Log::debug('Return FALSE');
@@ -51,7 +52,7 @@ trait ReconciliationValidation
} }
$result = $this->accountRepository->find($accountId); $result = $this->accountRepository->find($accountId);
if (null === $result) { if (null === $result) {
$this->destError = (string)trans('validation.deposit_dest_bad_data', ['id' => $accountId, 'name' => '']); $this->destError = (string) trans('validation.deposit_dest_bad_data', ['id' => $accountId, 'name' => '']);
Log::debug('Return FALSE'); Log::debug('Return FALSE');
return false; return false;
@@ -76,7 +77,7 @@ trait ReconciliationValidation
return true; return true;
} }
$this->destError = (string)trans('validation.deposit_dest_wrong_type'); $this->destError = (string) trans('validation.deposit_dest_wrong_type');
Log::debug('Return FALSE'); Log::debug('Return FALSE');
return false; return false;
@@ -89,7 +90,7 @@ trait ReconciliationValidation
*/ */
protected function validateReconciliationSource(array $array): bool protected function validateReconciliationSource(array $array): bool
{ {
$accountId = array_key_exists('id', $array) ? $array['id'] : null; $accountId = array_key_exists('id', $array) ? $array['id'] : null;
Log::debug('In validateReconciliationSource', $array); Log::debug('In validateReconciliationSource', $array);
if (null === $accountId) { if (null === $accountId) {
Log::debug('Return FALSE'); Log::debug('Return FALSE');

View File

@@ -39,7 +39,7 @@ trait TransferValidation
abstract protected function canCreateTypes(array $accountTypes): bool; abstract protected function canCreateTypes(array $accountTypes): bool;
/** /**
* @param array $validTypes * @param array $validTypes
* @param array $data * @param array $data
* *
* @return Account|null * @return Account|null
@@ -61,16 +61,16 @@ trait TransferValidation
if (null === $accountId && null === $accountName && false === $this->canCreateTypes($validTypes)) { if (null === $accountId && null === $accountName && 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 transfer can't be created. // because the destination of a transfer can't be created.
$this->destError = (string)trans('validation.transfer_dest_need_data'); $this->destError = (string) trans('validation.transfer_dest_need_data');
Log::error('Both values are NULL, cant create transfer destination.'); Log::error('Both values are NULL, cant create transfer destination.');
return false; return false;
} }
// or try to find the account: // or try to find the account:
$search = $this->findExistingAccount($validTypes,$array); $search = $this->findExistingAccount($validTypes, $array);
if (null === $search) { if (null === $search) {
$this->destError = (string)trans('validation.transfer_dest_bad_data', ['id' => $accountId, 'name' => $accountName]); $this->destError = (string) trans('validation.transfer_dest_bad_data', ['id' => $accountId, 'name' => $accountName]);
return false; return false;
} }
@@ -102,7 +102,7 @@ trait TransferValidation
if (null === $accountId && null === $accountName && false === $this->canCreateTypes($validTypes)) { if (null === $accountId && null === $accountName && false === $this->canCreateTypes($validTypes)) {
// if both values are NULL we return false, // if both values are NULL we return false,
// because the source of a withdrawal can't be created. // because the source of a withdrawal can't be created.
$this->sourceError = (string)trans('validation.transfer_source_need_data'); $this->sourceError = (string) trans('validation.transfer_source_need_data');
Log::warning('Not a valid source, need more data.'); Log::warning('Not a valid source, need more data.');
return false; return false;
@@ -111,7 +111,7 @@ trait TransferValidation
// otherwise try to find the account: // otherwise try to find the account:
$search = $this->findExistingAccount($validTypes, $array); $search = $this->findExistingAccount($validTypes, $array);
if (null === $search) { if (null === $search) {
$this->sourceError = (string)trans('validation.transfer_source_bad_data', ['id' => $accountId, 'name' => $accountName]); $this->sourceError = (string) trans('validation.transfer_source_bad_data', ['id' => $accountId, 'name' => $accountName]);
Log::warning('Not a valid source, cant find it.', $validTypes); Log::warning('Not a valid source, cant find it.', $validTypes);
return false; return false;

View File

@@ -40,7 +40,7 @@ trait WithdrawalValidation
abstract protected function canCreateTypes(array $accountTypes): bool; abstract protected function canCreateTypes(array $accountTypes): bool;
/** /**
* @param array $validTypes * @param array $validTypes
* @param array $data * @param array $data
* *
* @return Account|null * @return Account|null
@@ -62,7 +62,7 @@ trait WithdrawalValidation
if (null === $accountId && null === $accountName && false === $this->canCreateTypes($validTypes)) { if (null === $accountId && null === $accountName && false === $this->canCreateTypes($validTypes)) {
// if both values are NULL we return TRUE // if both values are NULL we return TRUE
// because we assume the user doesnt want to submit / change anything. // because we assume the user doesnt want to submit / change anything.
$this->sourceError = (string)trans('validation.withdrawal_source_need_data'); $this->sourceError = (string) trans('validation.withdrawal_source_need_data');
Log::warning('[a] Not a valid source. Need more data.'); Log::warning('[a] Not a valid source. Need more data.');
return false; return false;
@@ -71,7 +71,7 @@ trait WithdrawalValidation
// otherwise try to find the account: // otherwise try to find the account:
$search = $this->findExistingAccount($validTypes, $array); $search = $this->findExistingAccount($validTypes, $array);
if (null === $search) { if (null === $search) {
$this->sourceError = (string)trans('validation.withdrawal_source_bad_data', ['id' => $accountId, 'name' => $accountName]); $this->sourceError = (string) trans('validation.withdrawal_source_bad_data', ['id' => $accountId, 'name' => $accountName]);
Log::warning('Not a valid source. Cant find it.', $validTypes); Log::warning('Not a valid source. Cant find it.', $validTypes);
return false; return false;
@@ -97,7 +97,7 @@ trait WithdrawalValidation
if (null === $accountId && null === $accountName && false === $this->canCreateTypes($validTypes)) { if (null === $accountId && null === $accountName && false === $this->canCreateTypes($validTypes)) {
// if both values are NULL return false, // if both values are NULL return false,
// because the destination of a withdrawal can never be created automatically. // because the destination of a withdrawal can never be created automatically.
$this->destError = (string)trans('validation.withdrawal_dest_need_data'); $this->destError = (string) trans('validation.withdrawal_dest_need_data');
return false; return false;
} }
@@ -110,7 +110,7 @@ trait WithdrawalValidation
if (in_array($type, $validTypes, true)) { if (in_array($type, $validTypes, true)) {
return true; return true;
} }
$this->destError = (string)trans('validation.withdrawal_dest_bad_data', ['id' => $accountId, 'name' => $accountName]); $this->destError = (string) trans('validation.withdrawal_dest_bad_data', ['id' => $accountId, 'name' => $accountName]);
return false; return false;
} }
@@ -136,7 +136,7 @@ trait WithdrawalValidation
if (null === $accountId && null === $accountName && false === $this->canCreateTypes($validTypes)) { if (null === $accountId && null === $accountName && false === $this->canCreateTypes($validTypes)) {
// if both values are NULL we return false, // if both values are NULL we return false,
// because the source of a withdrawal can't be created. // because the source of a withdrawal can't be created.
$this->sourceError = (string)trans('validation.withdrawal_source_need_data'); $this->sourceError = (string) trans('validation.withdrawal_source_need_data');
Log::warning('[b] Not a valid source. Need more data.'); Log::warning('[b] Not a valid source. Need more data.');
return false; return false;
@@ -145,7 +145,7 @@ trait WithdrawalValidation
// otherwise try to find the account: // otherwise try to find the account:
$search = $this->findExistingAccount($validTypes, $array); $search = $this->findExistingAccount($validTypes, $array);
if (null === $search) { if (null === $search) {
$this->sourceError = (string)trans('validation.withdrawal_source_bad_data', ['id' => $accountId, 'name' => $accountName]); $this->sourceError = (string) trans('validation.withdrawal_source_bad_data', ['id' => $accountId, 'name' => $accountName]);
Log::warning('Not a valid source. Cant find it.', $validTypes); Log::warning('Not a valid source. Cant find it.', $validTypes);
return false; return false;

View File

@@ -198,6 +198,21 @@ class AccountValidator
return false; return false;
} }
/**
* @param string $accountType
*
* @return bool
*/
protected function canCreateType(string $accountType): bool
{
$canCreate = [AccountType::EXPENSE, AccountType::REVENUE, AccountType::INITIAL_BALANCE, AccountType::LIABILITY_CREDIT];
if (in_array($accountType, $canCreate, true)) {
return true;
}
return false;
}
/** /**
* @param array $validTypes * @param array $validTypes
* @param array $data * @param array $data
@@ -244,19 +259,4 @@ class AccountValidator
return null; return null;
} }
/**
* @param string $accountType
*
* @return bool
*/
protected function canCreateType(string $accountType): bool
{
$canCreate = [AccountType::EXPENSE, AccountType::REVENUE, AccountType::INITIAL_BALANCE, AccountType::LIABILITY_CREDIT];
if (in_array($accountType, $canCreate, true)) {
return true;
}
return false;
}
} }

View File

@@ -50,26 +50,26 @@ trait ValidatesBulkTransactionQuery
// find both accounts, must be same type. // find both accounts, must be same type.
// already validated: belongs to this user. // already validated: belongs to this user.
$repository = app(AccountRepositoryInterface::class); $repository = app(AccountRepositoryInterface::class);
$source = $repository->find((int)$json['where']['account_id']); $source = $repository->find((int) $json['where']['account_id']);
$dest = $repository->find((int)$json['update']['account_id']); $dest = $repository->find((int) $json['update']['account_id']);
if (null === $source) { if (null === $source) {
$validator->errors()->add('query', sprintf((string)trans('validation.invalid_query_data'), 'where', 'account_id')); $validator->errors()->add('query', sprintf((string) trans('validation.invalid_query_data'), 'where', 'account_id'));
return; return;
} }
if (null === $dest) { if (null === $dest) {
$validator->errors()->add('query', sprintf((string)trans('validation.invalid_query_data'), 'update', 'account_id')); $validator->errors()->add('query', sprintf((string) trans('validation.invalid_query_data'), 'update', 'account_id'));
return; return;
} }
if ($source->accountType->type !== $dest->accountType->type) { if ($source->accountType->type !== $dest->accountType->type) {
$validator->errors()->add('query', (string)trans('validation.invalid_query_account_type')); $validator->errors()->add('query', (string) trans('validation.invalid_query_account_type'));
return; return;
} }
// must have same currency: // must have same currency:
if ($repository->getAccountCurrency($source)->id !== $repository->getAccountCurrency($dest)->id) { if ($repository->getAccountCurrency($source)->id !== $repository->getAccountCurrency($dest)->id) {
$validator->errors()->add('query', (string)trans('validation.invalid_query_currency')); $validator->errors()->add('query', (string) trans('validation.invalid_query_currency'));
} }
} }
} }

View File

@@ -55,7 +55,7 @@ trait CurrencyValidation
) { ) {
$validator->errors()->add( $validator->errors()->add(
'transactions.' . $index . '.foreign_amount', 'transactions.' . $index . '.foreign_amount',
(string)trans('validation.require_currency_info') (string) trans('validation.require_currency_info')
); );
} }
// if the currency is present, then the amount must be present as well. // if the currency is present, then the amount must be present as well.
@@ -65,7 +65,7 @@ trait CurrencyValidation
)) { )) {
$validator->errors()->add( $validator->errors()->add(
'transactions.' . $index . '.foreign_amount', 'transactions.' . $index . '.foreign_amount',
(string)trans('validation.require_currency_amount') (string) trans('validation.require_currency_amount')
); );
} }
} }

View File

@@ -54,47 +54,6 @@ use function is_string;
class FireflyValidator extends Validator class FireflyValidator extends Validator
{ {
/**
* @param $attribute
* @param $value
* @return bool
*/
public function validateUniqueCurrencyName($attribute, $value): bool
{
return $this->validateUniqueCurrency('name', (string) $attribute, (string) $value);
}
/**
* @param $attribute
* @param $value
* @return bool
*/
public function validateUniqueCurrencyCode($attribute, $value): bool
{
return $this->validateUniqueCurrency('code', (string) $attribute, (string) $value);
}
/**
* @param $attribute
* @param $value
* @return bool
*/
public function validateUniqueCurrencySymbol($attribute, $value): bool
{
return $this->validateUniqueCurrency('symbol', (string) $attribute, (string) $value);
}
/**
* @param $attribute
* @param $value
* @return bool
*/
public function validateUniqueCurrency(string $field, string $attribute, string $value): bool
{
return 0 === DB::table('transaction_currencies')->where($field, $value)->whereNull('deleted_at')->count();
}
/** /**
* @param mixed $attribute * @param mixed $attribute
* @param mixed $value * @param mixed $value
@@ -648,6 +607,46 @@ class FireflyValidator extends Validator
return true; return true;
} }
/**
* @param $attribute
* @param $value
* @return bool
*/
public function validateUniqueCurrencyCode($attribute, $value): bool
{
return $this->validateUniqueCurrency('code', (string) $attribute, (string) $value);
}
/**
* @param $attribute
* @param $value
* @return bool
*/
public function validateUniqueCurrencyName($attribute, $value): bool
{
return $this->validateUniqueCurrency('name', (string) $attribute, (string) $value);
}
/**
* @param $attribute
* @param $value
* @return bool
*/
public function validateUniqueCurrency(string $field, string $attribute, string $value): bool
{
return 0 === DB::table('transaction_currencies')->where($field, $value)->whereNull('deleted_at')->count();
}
/**
* @param $attribute
* @param $value
* @return bool
*/
public function validateUniqueCurrencySymbol($attribute, $value): bool
{
return $this->validateUniqueCurrency('symbol', (string) $attribute, (string) $value);
}
/** /**
* @param mixed $value * @param mixed $value
* @param mixed $parameters * @param mixed $parameters

View File

@@ -43,6 +43,36 @@ trait GroupValidation
*/ */
abstract protected function getTransactionsArray(Validator $validator): array; abstract protected function getTransactionsArray(Validator $validator): array;
/**
* @param Validator $validator
*/
protected function preventNoAccountInfo(Validator $validator): void
{
$transactions = $this->getTransactionsArray($validator);
$keys = ['source_id', 'destination_id', 'source_name', 'destination_name', 'source_iban', 'destination_iban', 'source_number', 'destination_number'];
/** @var array $transaction */
foreach ($transactions as $index => $transaction) {
$hasAccountInfo = false;
$hasJournalId = array_key_exists('transaction_journal_id', $transaction);
foreach ($keys as $key) {
if (array_key_exists($key, $transaction) && '' !== (string) $transaction[$key]) {
$hasAccountInfo = true;
}
}
// set errors:
if (false === $hasAccountInfo && !$hasJournalId) {
$validator->errors()->add(
sprintf('transactions.%d.source_id', $index), (string) trans('validation.generic_no_source')
);
$validator->errors()->add(
sprintf('transactions.%d.destination_id', $index), (string) trans('validation.generic_no_destination')
);
}
}
// only an issue if there is no transaction_journal_id
}
/** /**
* Adds an error to the "description" field when the user has submitted no descriptions and no * Adds an error to the "description" field when the user has submitted no descriptions and no
* journal description. * journal description.
@@ -83,36 +113,6 @@ trait GroupValidation
} }
} }
/**
* @param Validator $validator
*/
protected function preventNoAccountInfo(Validator $validator): void
{
$transactions = $this->getTransactionsArray($validator);
$keys = ['source_id', 'destination_id', 'source_name', 'destination_name', 'source_iban', 'destination_iban', 'source_number', 'destination_number'];
/** @var array $transaction */
foreach ($transactions as $index => $transaction) {
$hasAccountInfo = false;
$hasJournalId = array_key_exists('transaction_journal_id', $transaction);
foreach ($keys as $key) {
if (array_key_exists($key, $transaction) && '' !== (string) $transaction[$key]) {
$hasAccountInfo = true;
}
}
// set errors:
if (false === $hasAccountInfo && !$hasJournalId) {
$validator->errors()->add(
sprintf('transactions.%d.source_id', $index), (string) trans('validation.generic_no_source')
);
$validator->errors()->add(
sprintf('transactions.%d.destination_id', $index), (string) trans('validation.generic_no_destination')
);
}
}
// only an issue if there is no transaction_journal_id
}
/** /**
* This method validates if the user has submitted transaction journal ID's for each array they submit, if they've submitted more than 1 transaction * This method validates if the user has submitted transaction journal ID's for each array they submit, if they've submitted more than 1 transaction
* journal. This check is necessary because Firefly III isn't able to distinguish between journals without the ID. * journal. This check is necessary because Firefly III isn't able to distinguish between journals without the ID.

View File

@@ -91,7 +91,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]);
@@ -103,7 +103,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:
@@ -127,7 +127,7 @@ trait RecurrenceValidation
$repetitions = $data['repetitions'] ?? []; $repetitions = $data['repetitions'] ?? [];
// need at least one transaction // need at least one transaction
if (!is_countable($repetitions) || empty($repetitions)) { if (!is_countable($repetitions) || empty($repetitions)) {
$validator->errors()->add('repetitions', (string)trans('validation.at_least_one_repetition')); $validator->errors()->add('repetitions', (string) trans('validation.at_least_one_repetition'));
} }
} }
@@ -145,7 +145,7 @@ trait RecurrenceValidation
} }
// need at least one transaction // need at least one transaction
if (empty($repetitions)) { if (empty($repetitions)) {
$validator->errors()->add('repetitions', (string)trans('validation.at_least_one_repetition')); $validator->errors()->add('repetitions', (string) trans('validation.at_least_one_repetition'));
} }
} }
@@ -162,15 +162,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) public function validateRecurringConfig(Validator $validator)
{ {
$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) {
@@ -193,7 +193,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;
} }
@@ -211,23 +211,23 @@ trait RecurrenceValidation
$repetition['moment'] = $repetition['moment'] ?? 'invalid'; $repetition['moment'] = $repetition['moment'] ?? 'invalid';
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;
} }
} }
@@ -243,7 +243,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'));
} }
} }
@@ -257,7 +257,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'));
} }
} }
@@ -273,19 +273,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'));
} }
} }
@@ -299,7 +299,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'));
} }
} }
@@ -316,7 +316,7 @@ trait RecurrenceValidation
Carbon::createFromFormat('Y-m-d', $moment); Carbon::createFromFormat('Y-m-d', $moment);
} catch (InvalidArgumentException $e) { } catch (InvalidArgumentException $e) {
Log::debug(sprintf('Invalid argument for Carbon: %s', $e->getMessage())); 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'));
} }
} }
} }

View File

@@ -100,10 +100,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;
$array = [ $array = [
'id' => $sourceId, 'id' => $sourceId,
'name' => $sourceName, 'name' => $sourceName,
@@ -120,10 +120,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;
$array = [ $array = [
'id' => $destinationId, 'id' => $destinationId,
'name' => $destinationName, 'name' => $destinationName,
@@ -188,7 +188,7 @@ trait TransactionValidation
// validate if the submitted source and / or name are valid // validate if the submitted source and / or name are valid
if (array_key_exists('source_id', $transaction) || array_key_exists('source_name', $transaction)) { if (array_key_exists('source_id', $transaction) || array_key_exists('source_name', $transaction)) {
Log::debug('Will try to validate source account information.'); 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;
$validSource = $accountValidator->validateSource(['id' => $sourceId, 'name' => $sourceName]); $validSource = $accountValidator->validateSource(['id' => $sourceId, 'name' => $sourceName]);
@@ -216,7 +216,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;
$array = ['id' => $destinationId, 'name' => $destinationName,]; $array = ['id' => $destinationId, 'name' => $destinationName,];
$validDestination = $accountValidator->validateDestination($array); $validDestination = $accountValidator->validateDestination($array);
@@ -257,7 +257,7 @@ trait TransactionValidation
} }
/** @var TransactionJournal $journal */ /** @var TransactionJournal $journal */
foreach ($transactionGroup->transactionJournals as $journal) { foreach ($transactionGroup->transactionJournals as $journal) {
if ((int)$journal->id === (int)$transaction['transaction_journal_id']) { if ((int) $journal->id === (int) $transaction['transaction_journal_id']) {
return $journal->transactions()->where('amount', '<', 0)->first()->account; return $journal->transactions()->where('amount', '<', 0)->first()->account;
} }
} }
@@ -277,7 +277,7 @@ trait TransactionValidation
// need at least one transaction // need at least one transaction
if (empty($transactions)) { if (empty($transactions)) {
$validator->errors()->add('transactions', (string)trans('validation.at_least_one_transaction')); $validator->errors()->add('transactions', (string) trans('validation.at_least_one_transaction'));
} }
} }
@@ -292,7 +292,7 @@ trait TransactionValidation
$transactions = $this->getTransactionsArray($validator); $transactions = $this->getTransactionsArray($validator);
// need at least one transaction // need at least one transaction
if (empty($transactions)) { if (empty($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'));
Log::debug('Added error: at_least_one_transaction.'); Log::debug('Added error: at_least_one_transaction.');
return; return;
@@ -308,7 +308,7 @@ trait TransactionValidation
$transactions = $this->getTransactionsArray($validator); $transactions = $this->getTransactionsArray($validator);
foreach ($transactions as $key => $value) { foreach ($transactions as $key => $value) {
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'));
Log::debug('Added error: at_least_one_transaction.'); Log::debug('Added error: at_least_one_transaction.');
return; return;
@@ -332,13 +332,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'));
} }
} }
@@ -353,14 +353,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) {
Log::warning('Add error for mismatch transaction types.'); 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;
} }
@@ -411,18 +411,18 @@ 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;
} }
@@ -453,14 +453,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'));
} }
Log::warning('Add error about equal accounts.'); Log::warning('Add error about equal accounts.');
@@ -483,7 +483,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];