Fix various phpstan issues.

This commit is contained in:
James Cole
2023-11-04 07:18:03 +01:00
parent dc45131f73
commit ef428a0226
42 changed files with 104 additions and 174 deletions

View File

@@ -77,7 +77,7 @@ class StoreRequest extends FormRequest
* Returns the transaction data as it is found in the submitted data. It's a complex method according to code * Returns the transaction data as it is found in the submitted data. It's a complex method according to code
* standards but it just has a lot of ??-statements because of the fields that may or may not exist. * standards but it just has a lot of ??-statements because of the fields that may or may not exist.
* *
* @return array * @return array|null
*/ */
private function getTransactionData(): array private function getTransactionData(): array
{ {

View File

@@ -125,16 +125,16 @@ class UpdateRequest extends FormRequest
* Returns the transaction data as it is found in the submitted data. It's a complex method according to code * Returns the transaction data as it is found in the submitted data. It's a complex method according to code
* standards but it just has a lot of ??-statements because of the fields that may or may not exist. * standards but it just has a lot of ??-statements because of the fields that may or may not exist.
* *
* @return array|null * @return array
*/ */
private function getTransactionData(): ?array private function getTransactionData(): array
{ {
$return = []; $return = [];
// transaction data: // transaction data:
/** @var array|null $transactions */ /** @var array|null $transactions */
$transactions = $this->get('transactions'); $transactions = $this->get('transactions');
if (null === $transactions) { if (null === $transactions) {
return null; return [];
} }
/** @var array $transaction */ /** @var array $transaction */
foreach ($transactions as $transaction) { foreach ($transactions as $transaction) {

View File

@@ -23,6 +23,7 @@ declare(strict_types=1);
namespace FireflyIII\Models; namespace FireflyIII\Models;
use Carbon\Carbon;
use Eloquent; use Eloquent;
use FireflyIII\User; use FireflyIII\User;
use Illuminate\Database\Eloquent\Collection; use Illuminate\Database\Eloquent\Collection;
@@ -32,7 +33,6 @@ use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\MorphMany; use Illuminate\Database\Eloquent\Relations\MorphMany;
use Illuminate\Database\Eloquent\SoftDeletes; use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Database\Query\Builder; use Illuminate\Database\Query\Builder;
use Carbon\Carbon;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
/** /**
@@ -46,7 +46,7 @@ use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
* @property int $transaction_type_id * @property int $transaction_type_id
* @property string $title * @property string $title
* @property string $description * @property string $description
* @property Carbon $first_date * @property Carbon|null $first_date
* @property Carbon|null $repeat_until * @property Carbon|null $repeat_until
* @property Carbon|null $latest_date * @property Carbon|null $latest_date
* @property int $repetitions * @property int $repetitions

View File

@@ -198,7 +198,7 @@ class JournalRepository implements JournalRepositoryInterface
*/ */
public function getSourceAccount(TransactionJournal $journal): Account public function getSourceAccount(TransactionJournal $journal): Account
{ {
/** @var Transaction $transaction */ /** @var Transaction|null $transaction */
$transaction = $journal->transactions()->with('account')->where('amount', '<', 0)->first(); $transaction = $journal->transactions()->with('account')->where('amount', '<', 0)->first();
if (null === $transaction) { if (null === $transaction) {
throw new FireflyException(sprintf('Your administration is broken. Transaction journal #%d has no source transaction.', $journal->id)); throw new FireflyException(sprintf('Your administration is broken. Transaction journal #%d has no source transaction.', $journal->id));
@@ -212,7 +212,7 @@ class JournalRepository implements JournalRepositoryInterface
*/ */
public function reconcileById(int $journalId): void public function reconcileById(int $journalId): void
{ {
/** @var TransactionJournal $journal */ /** @var TransactionJournal|null $journal */
$journal = $this->user->transactionJournals()->find($journalId); $journal = $this->user->transactionJournals()->find($journalId);
$journal?->transactions()->update(['reconciled' => true]); $journal?->transactions()->update(['reconciled' => true]);
} }
@@ -263,7 +263,7 @@ class JournalRepository implements JournalRepositoryInterface
*/ */
public function unreconcileById(int $journalId): void public function unreconcileById(int $journalId): void
{ {
/** @var TransactionJournal $journal */ /** @var TransactionJournal|null $journal */
$journal = $this->user->transactionJournals()->find($journalId); $journal = $this->user->transactionJournals()->find($journalId);
$journal?->transactions()->update(['reconciled' => false]); $journal?->transactions()->update(['reconciled' => false]);
} }

View File

@@ -300,13 +300,9 @@ class PiggyBankRepository implements PiggyBankRepositoryInterface
*/ */
public function getNoteText(PiggyBank $piggyBank): string public function getNoteText(PiggyBank $piggyBank): string
{ {
/** @var Note $note */ /** @var Note|null $note */
$note = $piggyBank->notes()->first(); $note = $piggyBank->notes()->first();
if (null === $note) { return (string)$note?->text;
return '';
}
return $note->text;
} }
/** /**

View File

@@ -266,13 +266,9 @@ class RecurringRepository implements RecurringRepositoryInterface
*/ */
public function getNoteText(Recurrence $recurrence): string public function getNoteText(Recurrence $recurrence): string
{ {
/** @var Note $note */ /** @var Note|null $note */
$note = $recurrence->notes()->first(); $note = $recurrence->notes()->first();
if (null !== $note) { return (string)$note?->text;
return (string)$note->text;
}
return '';
} }
/** /**
@@ -573,12 +569,7 @@ class RecurringRepository implements RecurringRepositoryInterface
/** @var RecurrenceFactory $factory */ /** @var RecurrenceFactory $factory */
$factory = app(RecurrenceFactory::class); $factory = app(RecurrenceFactory::class);
$factory->setUser($this->user); $factory->setUser($this->user);
$result = $factory->create($data); return $factory->create($data);
if (null === $result) {
throw new FireflyException($factory->getErrors()->first());
}
return $result;
} }
/** /**

View File

@@ -161,7 +161,7 @@ class TagRepository implements TagRepositoryInterface
return $set->each( return $set->each(
static function (Attachment $attachment) use ($disk) { static function (Attachment $attachment) use ($disk) {
/** @var Note $note */ /** @var Note|null $note */
$note = $attachment->notes()->first(); $note = $attachment->notes()->first();
// only used in v1 view of tags // only used in v1 view of tags
$attachment->file_exists = $disk->exists($attachment->fileName()); $attachment->file_exists = $disk->exists($attachment->fileName());

View File

@@ -226,7 +226,7 @@ class UserRepository implements UserRepositoryInterface
*/ */
public function getRolesInGroup(User $user, int $groupId): array public function getRolesInGroup(User $user, int $groupId): array
{ {
/** @var UserGroup $group */ /** @var UserGroup|null $group */
$group = UserGroup::find($groupId); $group = UserGroup::find($groupId);
if (null === $group) { if (null === $group) {
throw new FireflyException(sprintf('Could not find group #%d', $groupId)); throw new FireflyException(sprintf('Could not find group #%d', $groupId));

View File

@@ -52,7 +52,7 @@ class UserGroupRepository implements UserGroupRepositoryInterface
$memberships = $userGroup->groupMemberships()->get(); $memberships = $userGroup->groupMemberships()->get();
/** @var GroupMembership $membership */ /** @var GroupMembership $membership */
foreach ($memberships as $membership) { foreach ($memberships as $membership) {
/** @var User $user */ /** @var User|null $user */
$user = $membership->user()->first(); $user = $membership->user()->first();
if (null === $user) { if (null === $user) {
continue; continue;
@@ -242,7 +242,11 @@ class UserGroupRepository implements UserGroupRepositoryInterface
->where('user_role_id', $owner->id) ->where('user_role_id', $owner->id)
->where('user_id', '!=', $user->id)->count(); ->where('user_id', '!=', $user->id)->count();
// if there are no other owners and the current users does not get or keep the owner role, refuse. // if there are no other owners and the current users does not get or keep the owner role, refuse.
if (0 === $ownerCount && (0 === count($data['roles']) || (count($data['roles']) > 0 && !in_array(UserRoleEnum::OWNER->value, $data['roles'], true)))) { if (
0 === $ownerCount &&
(0 === count($data['roles']) ||
(count($data['roles']) > 0 && // @phpstan-ignore-line
!in_array(UserRoleEnum::OWNER->value, $data['roles'], true)))) {
app('log')->debug('User needs to keep owner role in this group, refuse to act'); app('log')->debug('User needs to keep owner role in this group, refuse to act');
throw new FireflyException('The last owner in this user group must keep the "owner" role.'); throw new FireflyException('The last owner in this user group must keep the "owner" role.');
} }

View File

@@ -53,7 +53,7 @@ class AccountRepository implements AccountRepositoryInterface
app('log')->debug(sprintf('Searching for account named "%s" (of user #%d) of the following type(s)', $name, $this->user->id), ['types' => $types]); app('log')->debug(sprintf('Searching for account named "%s" (of user #%d) of the following type(s)', $name, $this->user->id), ['types' => $types]);
$query->where('accounts.name', $name); $query->where('accounts.name', $name);
/** @var Account $account */ /** @var Account|null $account */
$account = $query->first(['accounts.*']); $account = $query->first(['accounts.*']);
if (null === $account) { if (null === $account) {
app('log')->debug(sprintf('There is no account with name "%s" of types', $name), $types); app('log')->debug(sprintf('There is no account with name "%s" of types', $name), $types);

View File

@@ -262,13 +262,10 @@ class CurrencyRepository implements CurrencyRepositoryInterface
if (null === $result) { if (null === $result) {
app('log')->debug('Grabbing default currency for this user...'); app('log')->debug('Grabbing default currency for this user...');
/** @var TransactionCurrency|null $result */
$result = app('amount')->getDefaultCurrencyByUserGroup($this->user->userGroup); $result = app('amount')->getDefaultCurrencyByUserGroup($this->user->userGroup);
} }
if (null === $result) {
app('log')->debug('Grabbing EUR as fallback.');
$result = $this->findByCode('EUR');
}
app('log')->debug(sprintf('Final result: %s', $result->code)); app('log')->debug(sprintf('Final result: %s', $result->code));
if (false === $result->enabled) { if (false === $result->enabled) {
app('log')->debug(sprintf('Also enabled currency %s', $result->code)); app('log')->debug(sprintf('Also enabled currency %s', $result->code));

View File

@@ -54,12 +54,12 @@ class IsDateOrTime implements ValidationRule
// probably a date format. // probably a date format.
try { try {
Carbon::createFromFormat('Y-m-d', $value); Carbon::createFromFormat('Y-m-d', $value);
} catch (InvalidDateException $e) { } catch (InvalidDateException $e) { // @phpstan-ignore-line
app('log')->error(sprintf('"%s" is not a valid date: %s', $value, $e->getMessage())); app('log')->error(sprintf('"%s" is not a valid date: %s', $value, $e->getMessage()));
$fail('validation.date_or_time')->translate();; $fail('validation.date_or_time')->translate();;
return; return;
} catch (InvalidFormatException $e) { } catch (InvalidFormatException $e) { // @phpstan-ignore-line
app('log')->error(sprintf('"%s" is of an invalid format: %s', $value, $e->getMessage())); app('log')->error(sprintf('"%s" is of an invalid format: %s', $value, $e->getMessage()));
$fail('validation.date_or_time')->translate();; $fail('validation.date_or_time')->translate();;
@@ -71,7 +71,7 @@ class IsDateOrTime implements ValidationRule
// is an atom string, I hope? // is an atom string, I hope?
try { try {
Carbon::parse($value); Carbon::parse($value);
} catch (InvalidDateException $e) { } catch (InvalidDateException $e) { // @phpstan-ignore-line
app('log')->error(sprintf('"%s" is not a valid date or time: %s', $value, $e->getMessage())); app('log')->error(sprintf('"%s" is not a valid date or time: %s', $value, $e->getMessage()));
$fail('validation.date_or_time')->translate();; $fail('validation.date_or_time')->translate();;

View File

@@ -129,7 +129,7 @@ class ValidRecurrenceRepetitionValue implements ValidationRule
$dateString = substr($value, 7); $dateString = substr($value, 7);
try { try {
Carbon::createFromFormat('Y-m-d', $dateString); Carbon::createFromFormat('Y-m-d', $dateString);
} catch (InvalidArgumentException $e) { } catch (InvalidArgumentException $e) { // @phpstan-ignore-line
app('log')->debug(sprintf('Could not parse date %s: %s', $dateString, $e->getMessage())); app('log')->debug(sprintf('Could not parse date %s: %s', $dateString, $e->getMessage()));
return false; return false;

View File

@@ -560,7 +560,7 @@ trait AccountServiceTrait
*/ */
private function getObJournal(TransactionGroup $group): TransactionJournal private function getObJournal(TransactionGroup $group): TransactionJournal
{ {
/** @var TransactionJournal $journal */ /** @var TransactionJournal|null $journal */
$journal = $group->transactionJournals()->first(); $journal = $group->transactionJournals()->first();
if (null === $journal) { if (null === $journal) {
throw new FireflyException(sprintf('Group #%d has no OB journal', $group->id)); throw new FireflyException(sprintf('Group #%d has no OB journal', $group->id));
@@ -580,7 +580,7 @@ trait AccountServiceTrait
*/ */
private function getOBTransaction(TransactionJournal $journal, Account $account): Transaction private function getOBTransaction(TransactionJournal $journal, Account $account): Transaction
{ {
/** @var Transaction $transaction */ /** @var Transaction|null $transaction */
$transaction = $journal->transactions()->where('account_id', '!=', $account->id)->first(); $transaction = $journal->transactions()->where('account_id', '!=', $account->id)->first();
if (null === $transaction) { if (null === $transaction) {
throw new FireflyException(sprintf('Could not get OB transaction for journal #%d', $journal->id)); throw new FireflyException(sprintf('Could not get OB transaction for journal #%d', $journal->id));
@@ -598,7 +598,7 @@ trait AccountServiceTrait
*/ */
private function getNotOBTransaction(TransactionJournal $journal, Account $account): Transaction private function getNotOBTransaction(TransactionJournal $journal, Account $account): Transaction
{ {
/** @var Transaction $transaction */ /** @var Transaction|null $transaction */
$transaction = $journal->transactions()->where('account_id', $account->id)->first(); $transaction = $journal->transactions()->where('account_id', $account->id)->first();
if (null === $transaction) { if (null === $transaction) {
throw new FireflyException(sprintf('Could not get non-OB transaction for journal #%d', $journal->id)); throw new FireflyException(sprintf('Could not get non-OB transaction for journal #%d', $journal->id));

View File

@@ -130,11 +130,12 @@ class CreditRecalculateService
*/ */
private function getAccountByDirection(TransactionJournal $journal, string $direction): Account private function getAccountByDirection(TransactionJournal $journal, string $direction): Account
{ {
/** @var Transaction $transaction */ /** @var Transaction|null $transaction */
$transaction = $journal->transactions()->where('amount', $direction, '0')->first(); $transaction = $journal->transactions()->where('amount', $direction, '0')->first();
if (null === $transaction) { if (null === $transaction) {
throw new FireflyException(sprintf('Cannot find "%s"-transaction of journal #%d', $direction, $journal->id)); throw new FireflyException(sprintf('Cannot find "%s"-transaction of journal #%d', $direction, $journal->id));
} }
/** @var Account|null $foundAccount */
$foundAccount = $transaction->account; $foundAccount = $transaction->account;
if (null === $foundAccount) { if (null === $foundAccount) {
throw new FireflyException(sprintf('Cannot find "%s"-account of transaction #%d of journal #%d', $direction, $transaction->id, $journal->id)); throw new FireflyException(sprintf('Cannot find "%s"-account of transaction #%d of journal #%d', $direction, $transaction->id, $journal->id));

View File

@@ -46,7 +46,6 @@ class AccountUpdateService
protected array $validCCFields; protected array $validCCFields;
protected array $validFields; protected array $validFields;
private array $canHaveOpeningBalance; private array $canHaveOpeningBalance;
private array $canHaveVirtual;
private User $user; private User $user;
/** /**
@@ -54,7 +53,6 @@ class AccountUpdateService
*/ */
public function __construct() public function __construct()
{ {
$this->canHaveVirtual = config('firefly.can_have_virtual_amounts');
$this->canHaveOpeningBalance = config('firefly.can_have_opening_balance'); $this->canHaveOpeningBalance = config('firefly.can_have_opening_balance');
$this->validAssetFields = config('firefly.valid_asset_fields'); $this->validAssetFields = config('firefly.valid_asset_fields');
$this->validCCFields = config('firefly.valid_cc_fields'); $this->validCCFields = config('firefly.valid_cc_fields');

View File

@@ -662,7 +662,7 @@ class JournalUpdateService
if ($this->hasFields([$field])) { if ($this->hasFields([$field])) {
try { try {
$value = '' === (string)$this->data[$field] ? null : new Carbon($this->data[$field]); $value = '' === (string)$this->data[$field] ? null : new Carbon($this->data[$field]);
} catch (InvalidDateException $e) { } catch (InvalidDateException $e) { // @phpstan-ignore-line
app('log')->debug(sprintf('%s is not a valid date value: %s', $this->data[$field], $e->getMessage())); app('log')->debug(sprintf('%s is not a valid date value: %s', $this->data[$field], $e->getMessage()));
return; return;

View File

@@ -291,7 +291,9 @@ class RecurrenceUpdateService
$currency = null; $currency = null;
$foreignCurrency = null; $foreignCurrency = null;
if (array_key_exists('currency_id', $submitted) || array_key_exists('currency_code', $submitted)) { if (array_key_exists('currency_id', $submitted) || array_key_exists('currency_code', $submitted)) {
$currency = $currencyFactory->find($submitted['currency_id'] ?? null, $currency['currency_code'] ?? null); $currency = $currencyFactory->find(
array_key_exists('currency_id', $submitted) ? (int)$submitted['currency_id'] : null,
array_key_exists('currency_code', $submitted) ? $submitted['currency_code'] : null);
} }
if (null === $currency) { if (null === $currency) {
unset($submitted['currency_id'], $submitted['currency_code']); unset($submitted['currency_id'], $submitted['currency_code']);
@@ -300,7 +302,9 @@ class RecurrenceUpdateService
$submitted['currency_id'] = (int)$currency->id; $submitted['currency_id'] = (int)$currency->id;
} }
if (array_key_exists('foreign_currency_id', $submitted) || array_key_exists('foreign_currency_code', $submitted)) { if (array_key_exists('foreign_currency_id', $submitted) || array_key_exists('foreign_currency_code', $submitted)) {
$foreignCurrency = $currencyFactory->find($submitted['foreign_currency_id'] ?? null, $currency['foreign_currency_code'] ?? null); $foreignCurrency = $currencyFactory->find(
array_key_exists('foreign_currency_id', $submitted) ? (int)$submitted['foreign_currency_id'] : null,
array_key_exists('foreign_currency_code', $submitted) ? $submitted['foreign_currency_code'] : null);
} }
if (null === $foreignCurrency) { if (null === $foreignCurrency) {
unset($submitted['foreign_currency_id'], $currency['foreign_currency_code']); unset($submitted['foreign_currency_id'], $currency['foreign_currency_code']);

View File

@@ -305,20 +305,4 @@ class Amount
return $format; return $format;
} }
/**
* @param string $value
*
* @return string
*/
private function tryDecrypt(string $value): string
{
try {
$value = Crypt::decrypt($value); // verified
} catch (DecryptException $e) {
// @ignoreException
}
return $value;
}
} }

View File

@@ -54,7 +54,7 @@ class RemoteUserGuard implements Guard
*/ */
public function __construct(UserProvider $provider, Application $app) public function __construct(UserProvider $provider, Application $app)
{ {
/** @var Request $request */ /** @var Request|null $request */
$request = $app->get('request'); $request = $app->get('request');
app('log')->debug(sprintf('Created RemoteUserGuard for %s "%s"', $request?->getMethod(), $request?->getRequestUri())); app('log')->debug(sprintf('Created RemoteUserGuard for %s "%s"', $request?->getMethod(), $request?->getRequestUri()));
$this->application = $app; $this->application = $app;

View File

@@ -54,7 +54,7 @@ class BudgetList implements BinderInterface
$list = array_unique(array_map('\intval', explode(',', $value))); $list = array_unique(array_map('\intval', explode(',', $value)));
if (0 === count($list)) { if (0 === count($list)) { // @phpstan-ignore-line
app('log')->warning('Budget list count is zero, return 404.'); app('log')->warning('Budget list count is zero, return 404.');
throw new NotFoundHttpException(); throw new NotFoundHttpException();
} }

View File

@@ -51,7 +51,7 @@ class CategoryList implements BinderInterface
} }
$list = array_unique(array_map('\intval', explode(',', $value))); $list = array_unique(array_map('\intval', explode(',', $value)));
if (0 === count($list)) { if (0 === count($list)) { // @phpstan-ignore-line
throw new NotFoundHttpException(); throw new NotFoundHttpException();
} }

View File

@@ -71,7 +71,7 @@ class Date implements BinderInterface
try { try {
$result = new Carbon($value); $result = new Carbon($value);
} catch (InvalidDateException $e) { } catch (InvalidDateException $e) { // @phpstan-ignore-line
$message = sprintf('Could not parse date "%s" for user #%d: %s', $value, auth()->user()->id, $e->getMessage()); $message = sprintf('Could not parse date "%s" for user #%d: %s', $value, auth()->user()->id, $e->getMessage());
app('log')->error($message); app('log')->error($message);
throw new NotFoundHttpException($message, $e); throw new NotFoundHttpException($message, $e);

View File

@@ -70,7 +70,7 @@ class JournalList implements BinderInterface
protected static function parseList(string $value): array protected static function parseList(string $value): array
{ {
$list = array_unique(array_map('\intval', explode(',', $value))); $list = array_unique(array_map('\intval', explode(',', $value)));
if (0 === count($list)) { if (0 === count($list)) { // @phpstan-ignore-line
throw new NotFoundHttpException(); throw new NotFoundHttpException();
} }

View File

@@ -52,7 +52,7 @@ class TagList implements BinderInterface
$list = array_unique(array_map('\strtolower', explode(',', $value))); $list = array_unique(array_map('\strtolower', explode(',', $value)));
app('log')->debug('List of tags is', $list); app('log')->debug('List of tags is', $list);
if (0 === count($list)) { if (0 === count($list)) { // @phpstan-ignore-line
app('log')->error('Tag list is empty.'); app('log')->error('Tag list is empty.');
throw new NotFoundHttpException(); throw new NotFoundHttpException();
} }

View File

@@ -266,10 +266,10 @@ trait ConvertsDataTypes
// probably a date format. // probably a date format.
try { try {
$carbon = Carbon::createFromFormat('Y-m-d', $value); $carbon = Carbon::createFromFormat('Y-m-d', $value);
} catch (InvalidDateException $e) { } catch (InvalidDateException $e) { // @phpstan-ignore-line
app('log')->error(sprintf('[1] "%s" is not a valid date: %s', $value, $e->getMessage())); app('log')->error(sprintf('[1] "%s" is not a valid date: %s', $value, $e->getMessage()));
return null; return null;
} catch (InvalidFormatException $e) { } catch (InvalidFormatException $e) { // @phpstan-ignore-line
app('log')->error(sprintf('[2] "%s" is of an invalid format: %s', $value, $e->getMessage())); app('log')->error(sprintf('[2] "%s" is of an invalid format: %s', $value, $e->getMessage()));
return null; return null;
@@ -279,7 +279,7 @@ trait ConvertsDataTypes
// is an atom string, I hope? // is an atom string, I hope?
try { try {
$carbon = Carbon::parse($value); $carbon = Carbon::parse($value);
} catch (InvalidDateException $e) { } catch (InvalidDateException $e) { // @phpstan-ignore-line
app('log')->error(sprintf('[3] "%s" is not a valid date or time: %s', $value, $e->getMessage())); app('log')->error(sprintf('[3] "%s" is not a valid date or time: %s', $value, $e->getMessage()));
return null; return null;

View File

@@ -312,9 +312,9 @@ class Steam
continue; continue;
} }
// otherwise, convert 'amount' to the necessary currency: // otherwise, convert 'amount' to the necessary currency:
$currencyId = (int)$transaction['transaction_currency_id']; $currencyId = (int)$transaction['transaction_currency_id'];
$currency = $currencies[$currencyId] ?? TransactionCurrency::find($currencyId); $currency = $currencies[$currencyId] ?? TransactionCurrency::find($currencyId);
$currencies[$currencyId] = $currency;
$rate = $converter->getCurrencyRate($currency, $native, $day); $rate = $converter->getCurrencyRate($currency, $native, $day);
$convertedAmount = bcmul($transaction['amount'], $rate); $convertedAmount = bcmul($transaction['amount'], $rate);
@@ -322,15 +322,15 @@ class Steam
$balances[$format] = $currentBalance; $balances[$format] = $currentBalance;
app('log')->debug(sprintf( app('log')->debug(sprintf(
'%s: transaction in %s(!). Conversion rate is %s. %s %s = %s %s', '%s: transaction in %s(!). Conversion rate is %s. %s %s = %s %s',
$format, $format,
$currency->code, $currency->code,
$rate, $rate,
$currency->code, $currency->code,
$transaction['amount'], $transaction['amount'],
$native->code, $native->code,
$convertedAmount $convertedAmount
)); ));
} }

View File

@@ -56,7 +56,7 @@ class AppendNotesToDescription implements ActionInterface
public function actOnArray(array $journal): bool public function actOnArray(array $journal): bool
{ {
app('log')->debug('Now in AppendNotesToDescription'); app('log')->debug('Now in AppendNotesToDescription');
/** @var TransactionJournal $object */ /** @var TransactionJournal|null $object */
$object = TransactionJournal::where('user_id', $journal['user_id'])->find($journal['transaction_journal_id']); $object = TransactionJournal::where('user_id', $journal['user_id'])->find($journal['transaction_journal_id']);
if (null === $object) { if (null === $object) {
app('log')->error(sprintf('No journal #%d belongs to user #%d.', $journal['transaction_journal_id'], $journal['user_id'])); app('log')->error(sprintf('No journal #%d belongs to user #%d.', $journal['transaction_journal_id'], $journal['user_id']));

View File

@@ -134,23 +134,20 @@ class ConvertToTransfer implements ActionInterface
} }
return $res; return $res;
} }
if (TransactionType::DEPOSIT === $type) { // can only be a deposit at this point.
app('log')->debug('Going to transform a deposit to a transfer.'); app('log')->debug('Going to transform a deposit to a transfer.');
try { try {
$res = $this->convertDepositArray($object, $opposing); $res = $this->convertDepositArray($object, $opposing);
} catch (FireflyException $e) { } catch (FireflyException $e) {
app('log')->debug('Could not convert deposit to transfer.'); app('log')->debug('Could not convert deposit to transfer.');
app('log')->error($e->getMessage()); app('log')->error($e->getMessage());
event(new RuleActionFailedOnArray($this->action, $journal, trans('rules.complex_error'))); event(new RuleActionFailedOnArray($this->action, $journal, trans('rules.complex_error')));
return false; return false;
}
if (false !== $res) {
event(new TriggeredAuditLog($this->action->rule, $object, 'update_transaction_type', TransactionType::DEPOSIT, TransactionType::TRANSFER));
}
return $res;
} }
event(new RuleActionFailedOnArray($this->action, $journal, trans('rules.unsupported_transaction_type_transfer', ['type' => $type]))); if (false !== $res) {
return false; event(new TriggeredAuditLog($this->action->rule, $object, 'update_transaction_type', TransactionType::DEPOSIT, TransactionType::TRANSFER));
}
return $res;
} }
/** /**
@@ -176,7 +173,7 @@ class ConvertToTransfer implements ActionInterface
*/ */
private function getDestinationType(int $journalId): string private function getDestinationType(int $journalId): string
{ {
/** @var TransactionJournal $journal */ /** @var TransactionJournal|null $journal */
$journal = TransactionJournal::find($journalId); $journal = TransactionJournal::find($journalId);
if (null === $journal) { if (null === $journal) {
app('log')->error(sprintf('Journal #%d does not exist. Cannot convert to transfer.', $journalId)); app('log')->error(sprintf('Journal #%d does not exist. Cannot convert to transfer.', $journalId));

View File

@@ -99,23 +99,20 @@ class ConvertToWithdrawal implements ActionInterface
return $res; return $res;
} }
if (TransactionType::TRANSFER === $type) { // can only be transfer at this point.
app('log')->debug('Going to transform a transfer to a withdrawal.'); app('log')->debug('Going to transform a transfer to a withdrawal.');
try { try {
$res = $this->convertTransferArray($object); $res = $this->convertTransferArray($object);
} catch (JsonException | FireflyException $e) { } catch (JsonException | FireflyException $e) {
app('log')->debug('Could not convert transfer to deposit.'); app('log')->debug('Could not convert transfer to deposit.');
app('log')->error($e->getMessage()); app('log')->error($e->getMessage());
event(new RuleActionFailedOnArray($this->action, $journal, trans('rules.complex_error'))); event(new RuleActionFailedOnArray($this->action, $journal, trans('rules.complex_error')));
return false; return false;
}
event(new TriggeredAuditLog($this->action->rule, $object, 'update_transaction_type', TransactionType::TRANSFER, TransactionType::WITHDRAWAL));
return $res;
} }
event(new RuleActionFailedOnArray($this->action, $journal, trans('rules.unsupported_transaction_type_withdrawal', ['type' => $type]))); event(new TriggeredAuditLog($this->action->rule, $object, 'update_transaction_type', TransactionType::TRANSFER, TransactionType::WITHDRAWAL));
return false;
return $res;
} }
/** /**

View File

@@ -53,13 +53,14 @@ class MoveDescriptionToNotes implements ActionInterface
*/ */
public function actOnArray(array $journal): bool public function actOnArray(array $journal): bool
{ {
/** @var TransactionJournal $object */ /** @var TransactionJournal|null $object */
$object = TransactionJournal::where('user_id', $journal['user_id'])->find($journal['transaction_journal_id']); $object = TransactionJournal::where('user_id', $journal['user_id'])->find($journal['transaction_journal_id']);
if (null === $object) { if (null === $object) {
app('log')->error(sprintf('No journal #%d belongs to user #%d.', $journal['transaction_journal_id'], $journal['user_id'])); app('log')->error(sprintf('No journal #%d belongs to user #%d.', $journal['transaction_journal_id'], $journal['user_id']));
event(new RuleActionFailedOnArray($this->action, $journal, trans('rules.journal_other_user'))); event(new RuleActionFailedOnArray($this->action, $journal, trans('rules.journal_other_user')));
return false; return false;
} }
/** @var Note|null $note */
$note = $object->notes()->first(); $note = $object->notes()->first();
if (null === $note) { if (null === $note) {
$note = new Note(); $note = new Note();

View File

@@ -59,7 +59,7 @@ class MoveNotesToDescription implements ActionInterface
*/ */
public function actOnArray(array $journal): bool public function actOnArray(array $journal): bool
{ {
/** @var TransactionJournal $object */ /** @var TransactionJournal|null $object */
$object = TransactionJournal::where('user_id', $journal['user_id'])->find($journal['transaction_journal_id']); $object = TransactionJournal::where('user_id', $journal['user_id'])->find($journal['transaction_journal_id']);
if (null === $object) { if (null === $object) {
app('log')->error(sprintf('No journal #%d belongs to user #%d.', $journal['transaction_journal_id'], $journal['user_id'])); app('log')->error(sprintf('No journal #%d belongs to user #%d.', $journal['transaction_journal_id'], $journal['user_id']));

View File

@@ -75,9 +75,9 @@ class SwitchAccounts implements ActionInterface
return false; return false;
} }
/** @var Transaction $sourceTransaction */ /** @var Transaction|null $sourceTransaction */
$sourceTransaction = $object->transactions()->where('amount', '<', 0)->first(); $sourceTransaction = $object->transactions()->where('amount', '<', 0)->first();
/** @var Transaction $destTransaction */ /** @var Transaction|null $destTransaction */
$destTransaction = $object->transactions()->where('amount', '>', 0)->first(); $destTransaction = $object->transactions()->where('amount', '>', 0)->first();
if (null === $sourceTransaction || null === $destTransaction) { if (null === $sourceTransaction || null === $destTransaction) {
app('log')->error(sprintf('Journal #%d has no source or destination transaction (rule #%d), cannot switch accounts.', $journal['transaction_journal_id'], $this->action->rule_id)); app('log')->error(sprintf('Journal #%d has no source or destination transaction (rule #%d), cannot switch accounts.', $journal['transaction_journal_id'], $this->action->rule_id));

View File

@@ -31,7 +31,6 @@ use FireflyIII\Models\ObjectGroup;
use FireflyIII\Models\Transaction; use FireflyIII\Models\Transaction;
use FireflyIII\Models\TransactionCurrency; use FireflyIII\Models\TransactionCurrency;
use FireflyIII\Models\TransactionJournal; use FireflyIII\Models\TransactionJournal;
use FireflyIII\Repositories\Bill\BillRepositoryInterface;
use FireflyIII\Support\Http\Api\ExchangeRateConverter; use FireflyIII\Support\Http\Api\ExchangeRateConverter;
use Illuminate\Support\Collection; use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\DB;
@@ -41,23 +40,12 @@ use Illuminate\Support\Facades\DB;
*/ */
class BillTransformer extends AbstractTransformer class BillTransformer extends AbstractTransformer
{ {
private ExchangeRateConverter $converter; private ExchangeRateConverter $converter;
private array $currencies; private array $currencies;
private TransactionCurrency $default; private TransactionCurrency $default;
private array $groups; private array $groups;
private array $notes; private array $notes;
private array $paidDates; private array $paidDates;
private BillRepositoryInterface $repository;
/**
* BillTransformer constructor.
*
*/
public function __construct()
{
$this->repository = app(BillRepositoryInterface::class);
}
/** /**
* @inheritDoc * @inheritDoc

View File

@@ -116,19 +116,4 @@ class BudgetTransformer extends AbstractTransformer
]; ];
} }
/**
* @param array $array
*
* @return array
*/
private function beautify(array $array): array
{
$return = [];
foreach ($array as $data) {
$data['sum'] = number_format((float)$data['sum'], (int)$data['currency_decimal_places'], '.', '');
$return[] = $data;
}
return $return;
}
} }

View File

@@ -34,8 +34,6 @@ use FireflyIII\Models\Webhook;
*/ */
class WebhookTransformer extends AbstractTransformer class WebhookTransformer extends AbstractTransformer
{ {
private array $enums;
/** /**
* WebhookTransformer constructor. * WebhookTransformer constructor.
*/ */

View File

@@ -48,7 +48,7 @@ trait LiabilityValidation
// if the ID is not null the source account should be a dummy account of the type liability credit. // if the ID is not null the source account should be a dummy account of the type liability credit.
// the ID of the destination must belong to a liability. // the ID of the destination must belong to a liability.
if (null !== $accountId) { if (null !== $accountId) {
if (AccountType::LIABILITY_CREDIT !== $this?->source?->accountType?->type) { if (AccountType::LIABILITY_CREDIT !== $this->source?->accountType?->type) {
app('log')->error('Source account is not a liability.'); app('log')->error('Source account is not a liability.');
return false; return false;
} }

View File

@@ -58,8 +58,6 @@ class AccountValidator
private array $combinations; private array $combinations;
private string $transactionType; private string $transactionType;
private bool $useUserGroupRepository = false; private bool $useUserGroupRepository = false;
private User $user;
private UserGroup $userGroup;
private UserGroupAccountRepositoryInterface $userGroupAccountRepository; private UserGroupAccountRepositoryInterface $userGroupAccountRepository;
/** /**
@@ -127,7 +125,6 @@ class AccountValidator
*/ */
public function setUser(User $user): void public function setUser(User $user): void
{ {
$this->user = $user;
$this->accountRepository->setUser($user); $this->accountRepository->setUser($user);
$this->useUserGroupRepository = false; $this->useUserGroupRepository = false;
} }
@@ -139,7 +136,6 @@ class AccountValidator
*/ */
public function setUserGroup(UserGroup $userGroup): void public function setUserGroup(UserGroup $userGroup): void
{ {
$this->userGroup = $userGroup;
$this->userGroupAccountRepository->setUserGroup($userGroup); $this->userGroupAccountRepository->setUserGroup($userGroup);
$this->useUserGroupRepository = true; $this->useUserGroupRepository = true;
} }

View File

@@ -54,7 +54,7 @@ trait ValidatesAutoBudgetRequest
return; return;
} }
if ('' === $amount) { if ('' === (string) $amount) {
$validator->errors()->add('auto_budget_amount', (string)trans('validation.amount_required_for_auto_budget')); $validator->errors()->add('auto_budget_amount', (string)trans('validation.amount_required_for_auto_budget'));
} }
if (1 !== bccomp((string)$amount, '0')) { if (1 !== bccomp((string)$amount, '0')) {

View File

@@ -226,7 +226,7 @@ class FireflyValidator extends Validator
} }
try { try {
$checksum = bcmod($iban, '97'); $checksum = bcmod($iban, '97');
} catch (ValueError $e) { } catch (ValueError $e) { // @phpstan-ignore-line
$message = sprintf('Could not validate IBAN check value "%s" (IBAN "%s")', $iban, $value); $message = sprintf('Could not validate IBAN check value "%s" (IBAN "%s")', $iban, $value);
app('log')->error($message); app('log')->error($message);
app('log')->error($e->getTraceAsString()); app('log')->error($e->getTraceAsString());

View File

@@ -229,7 +229,7 @@ trait GroupValidation
} }
$journalId = (int)$journalId; $journalId = (int)$journalId;
$count = $transactionGroup->transactionJournals()->where('transaction_journals.id', $journalId)->count(); $count = $transactionGroup->transactionJournals()->where('transaction_journals.id', $journalId)->count();
if (null === $journalId || 0 === $count) { if (0 === $journalId || 0 === $count) {
app('log')->warning(sprintf('Transaction group #%d has %d journals with ID %d', $transactionGroup->id, $count, $journalId)); app('log')->warning(sprintf('Transaction group #%d has %d journals with ID %d', $transactionGroup->id, $count, $journalId));
app('log')->warning('Invalid submission: Each split must have transaction_journal_id (either valid ID or 0).'); app('log')->warning('Invalid submission: Each split must have transaction_journal_id (either valid ID or 0).');
$validator->errors()->add(sprintf('transactions.%d.source_name', $index), (string)trans('validation.need_id_in_edit')); $validator->errors()->add(sprintf('transactions.%d.source_name', $index), (string)trans('validation.need_id_in_edit'));

View File

@@ -212,7 +212,6 @@ trait RecurrenceValidation
if (null === $repetition['moment']) { if (null === $repetition['moment']) {
$repetition['moment'] = ''; $repetition['moment'] = '';
} }
$repetition['moment'] = $repetition['moment'] ?? 'invalid';
switch ($repetition['type'] ?? 'empty') { switch ($repetition['type'] ?? 'empty') {
default: default:
@@ -319,7 +318,7 @@ trait RecurrenceValidation
{ {
try { try {
Carbon::createFromFormat('Y-m-d', $moment); Carbon::createFromFormat('Y-m-d', $moment);
} catch (InvalidArgumentException $e) { } catch (InvalidArgumentException $e) { // @phpstan-ignore-line
app('log')->debug(sprintf('Invalid argument for Carbon: %s', $e->getMessage())); app('log')->debug(sprintf('Invalid argument for Carbon: %s', $e->getMessage()));
$validator->errors()->add(sprintf('repetitions.%d.moment', $index), (string)trans('validation.valid_recurrence_rep_moment')); $validator->errors()->add(sprintf('repetitions.%d.moment', $index), (string)trans('validation.valid_recurrence_rep_moment'));
} }
@@ -337,12 +336,6 @@ trait RecurrenceValidation
$transactions = $this->getTransactionData(); $transactions = $this->getTransactionData();
$submittedTrCount = count($transactions); $submittedTrCount = count($transactions);
//$recurrence = $validator->get
if (null === $transactions) {
app('log')->warning('[a] User submitted no transactions.');
$validator->errors()->add('transactions', (string)trans('validation.at_least_one_transaction'));
return;
}
if (0 === $submittedTrCount) { if (0 === $submittedTrCount) {
app('log')->warning('[b] User submitted no transactions.'); app('log')->warning('[b] User submitted no transactions.');
$validator->errors()->add('transactions', (string)trans('validation.at_least_one_transaction')); $validator->errors()->add('transactions', (string)trans('validation.at_least_one_transaction'));