From 68183a0a0ea12f0570184bcc086ac7fb58de7bd6 Mon Sep 17 00:00:00 2001 From: James Cole Date: Sun, 9 Nov 2025 09:08:03 +0100 Subject: [PATCH] Fix code quality with rector [skip ci] --- app/Models/RecurrenceRepetition.php | 6 +- app/Models/RecurrenceTransaction.php | 14 ++-- app/Models/RecurrenceTransactionMeta.php | 2 +- app/Models/Rule.php | 6 +- app/Models/RuleAction.php | 4 +- app/Models/RuleGroup.php | 2 +- app/Models/RuleTrigger.php | 4 +- app/Models/Transaction.php | 10 +-- app/Models/TransactionCurrency.php | 2 +- app/Models/TransactionJournal.php | 4 +- app/Models/TransactionJournalLink.php | 6 +- app/Models/TransactionJournalMeta.php | 4 +- app/Models/WebhookAttempt.php | 2 +- app/Models/WebhookDelivery.php | 2 +- app/Models/WebhookMessage.php | 4 +- app/Models/WebhookResponse.php | 2 +- app/Models/WebhookTrigger.php | 2 +- app/Notifications/User/NewAccessToken.php | 2 - app/Notifications/User/UserRegistration.php | 2 - app/Providers/AppServiceProvider.php | 10 +-- app/Providers/AuthServiceProvider.php | 4 +- app/Providers/CurrencyServiceProvider.php | 2 +- app/Providers/FireflyServiceProvider.php | 24 +++--- app/Providers/FireflySessionProvider.php | 2 +- .../Account/AccountRepository.php | 4 +- .../Attachment/AttachmentRepository.php | 5 +- app/Repositories/Bill/BillRepository.php | 44 +++++------ .../Budget/AvailableBudgetRepository.php | 2 +- .../Budget/BudgetLimitRepository.php | 2 +- app/Repositories/Budget/BudgetRepository.php | 4 +- .../Budget/OperationsRepository.php | 6 +- .../Category/CategoryRepository.php | 12 +-- .../Currency/CurrencyRepository.php | 11 ++- .../Journal/JournalAPIRepository.php | 2 +- .../Journal/JournalRepository.php | 12 +-- .../LinkType/LinkTypeRepository.php | 9 ++- .../ObjectGroup/ObjectGroupRepository.php | 7 +- .../PiggyBank/PiggyBankRepository.php | 2 +- .../Recurring/RecurringRepository.php | 12 +-- app/Repositories/Rule/RuleRepository.php | 11 +-- .../RuleGroup/RuleGroupRepository.php | 8 +- app/Repositories/Tag/TagRepository.php | 6 +- .../TransactionGroupRepository.php | 11 +-- .../TransactionTypeRepository.php | 7 +- app/Repositories/User/UserRepository.php | 36 ++------- .../UserGroup/UserGroupRepository.php | 31 ++++---- .../Webhook/WebhookRepository.php | 2 +- app/Rules/Account/IsValidAccountTypeList.php | 1 - app/Rules/BelongsUser.php | 9 ++- app/Rules/BelongsUserGroup.php | 9 ++- app/Rules/IsAllowedGroupAction.php | 65 +--------------- app/Rules/IsDateOrTime.php | 9 ++- app/Rules/IsDefaultUserGroupName.php | 3 +- app/Rules/IsTransferAccount.php | 7 +- app/Rules/IsValidDateRange.php | 5 +- app/Rules/IsValidZeroOrMoreAmount.php | 2 +- .../IsValidTransactionTypeList.php | 1 - app/Rules/UniqueAccountNumber.php | 9 ++- app/Rules/UniqueIban.php | 8 +- app/Rules/ValidJournals.php | 7 +- app/Rules/ValidRecurrenceRepetitionValue.php | 3 +- .../FireflyIIIOrg/Update/UpdateRequest.php | 4 +- .../Destroy/AccountDestroyService.php | 13 ++-- .../Destroy/JournalDestroyService.php | 7 +- .../TransactionGroupDestroyService.php | 3 +- .../Internal/Support/AccountServiceTrait.php | 77 +++++++++---------- .../Internal/Support/BillServiceTrait.php | 3 +- .../Support/CreditRecalculateService.php | 28 ++----- .../Internal/Support/JournalServiceTrait.php | 2 +- .../Support/RecurringTransactionTrait.php | 10 +-- .../Internal/Support/TransactionTypeTrait.php | 3 +- .../Internal/Update/AccountUpdateService.php | 21 ++--- .../Internal/Update/BillUpdateService.php | 13 ++-- .../Internal/Update/CategoryUpdateService.php | 13 ++-- .../Internal/Update/GroupUpdateService.php | 16 ++-- .../Internal/Update/JournalUpdateService.php | 58 ++++++-------- .../Update/RecurrenceUpdateService.php | 33 ++++---- app/Services/Password/PwndVerifierV2.php | 13 ++-- app/Support/Amount.php | 4 +- .../Authentication/RemoteUserGuard.php | 6 +- .../Authentication/RemoteUserProvider.php | 17 ++-- app/Support/Binder/AccountList.php | 5 +- app/Support/Binder/BudgetList.php | 7 +- app/Support/Binder/CLIToken.php | 10 +-- app/Support/Binder/CategoryList.php | 2 +- app/Support/Binder/Date.php | 5 +- app/Support/Binder/JournalList.php | 2 +- app/Support/Binder/TagList.php | 10 +-- app/Support/Binder/TagOrId.php | 5 +- app/Support/Calendar/Calculator.php | 8 +- .../Chart/Budget/FrontpageChartGenerator.php | 5 +- .../Category/FrontpageChartGenerator.php | 3 +- app/Support/Chart/ChartData.php | 7 +- app/Support/Cronjobs/AbstractCronjob.php | 15 ++-- app/Support/ExpandedForm.php | 59 +++++++------- app/Support/Export/ExportDataGenerator.php | 45 +++++------ app/Support/Facades/Preferences.php | 3 +- app/Support/FireflyConfig.php | 2 +- app/Support/Form/AccountForm.php | 5 +- app/Support/Form/CurrencyForm.php | 17 ++-- app/Support/Form/FormSupport.php | 9 ++- app/Support/Form/RuleForm.php | 3 - .../Http/Api/AccountBalanceGrouped.php | 5 +- .../Http/Api/ExchangeRateConverter.php | 16 ++-- .../Http/Api/SummaryBalanceGrouped.php | 6 +- .../Http/Controllers/GetConfigurationData.php | 6 +- .../Http/Controllers/ModelInformation.php | 13 ++-- .../Http/Controllers/PeriodOverview.php | 12 +-- .../Http/Controllers/RenderPartialViews.php | 47 +++++------ .../Http/Controllers/RequestInformation.php | 6 +- .../Http/Controllers/RuleManagement.php | 13 ++-- .../Http/Controllers/UserNavigation.php | 23 +++--- .../JsonApi/Enrichments/AccountEnrichment.php | 2 +- .../Enrichments/AvailableBudgetEnrichment.php | 8 +- .../JsonApi/Enrichments/BudgetEnrichment.php | 4 +- .../Enrichments/BudgetLimitEnrichment.php | 19 ++--- .../Enrichments/CategoryEnrichment.php | 2 +- .../Enrichments/PiggyBankEnrichment.php | 6 +- .../Enrichments/PiggyBankEventEnrichment.php | 6 +- .../Enrichments/RecurringEnrichment.php | 10 +-- .../Enrichments/SubscriptionEnrichment.php | 11 +-- .../TransactionGroupEnrichment.php | 9 +-- .../JsonApi/Enrichments/WebhookEnrichment.php | 6 +- app/Support/Models/ReturnsIntegerIdTrait.php | 2 +- .../Models/ReturnsIntegerUserIdTrait.php | 4 +- app/Support/ParseDateString.php | 6 +- .../Report/Budget/BudgetReportGenerator.php | 3 +- .../Summarizer/TransactionSummarizer.php | 2 +- .../Recurring/CalculateRangeOccurrences.php | 15 ++-- .../Recurring/CalculateXOccurrencesSince.php | 2 +- app/Support/Request/AppendsLocationData.php | 56 +++++++------- app/Support/Request/ChecksLogin.php | 17 ++-- app/Support/Request/ConvertsDataTypes.php | 6 +- app/Support/Request/ValidatesWebhooks.php | 2 +- app/Support/Search/AccountSearch.php | 12 +-- app/Support/Search/OperatorQuerySearch.php | 52 +++++-------- .../Search/QueryParser/GdbotsQueryParser.php | 8 +- app/Support/Steam.php | 33 ++++---- .../System/GeneratesInstallationId.php | 5 +- app/Support/System/OAuthKeys.php | 15 ++-- app/Support/Twig/General.php | 8 +- app/Support/Twig/Rule.php | 6 +- app/Support/Twig/TransactionGroupTwig.php | 5 +- app/Support/Twig/Translation.php | 7 +- app/TransactionRules/Actions/AddTag.php | 5 +- .../Actions/AppendDescriptionToNotes.php | 3 +- app/TransactionRules/Actions/AppendNotes.php | 3 +- .../Actions/AppendNotesToDescription.php | 9 ++- app/TransactionRules/Actions/ClearBudget.php | 5 +- .../Actions/ClearCategory.php | 5 +- app/TransactionRules/Actions/ClearNotes.php | 5 +- .../Actions/ConvertToDeposit.php | 29 +++---- .../Actions/ConvertToTransfer.php | 37 ++++----- .../Actions/ConvertToWithdrawal.php | 27 +++---- .../Actions/DeleteTransaction.php | 5 +- .../Actions/MoveDescriptionToNotes.php | 3 +- .../Actions/MoveNotesToDescription.php | 3 +- app/TransactionRules/Actions/PrependNotes.php | 3 +- .../Actions/RemoveAllTags.php | 5 +- app/TransactionRules/Actions/RemoveTag.php | 7 +- app/TransactionRules/Actions/SetAmount.php | 5 +- app/TransactionRules/Actions/SetBudget.php | 7 +- app/TransactionRules/Actions/SetCategory.php | 7 +- .../Actions/SetDescription.php | 2 +- .../Actions/SetDestinationAccount.php | 21 ++--- .../Actions/SetDestinationToCashAccount.php | 13 ++-- app/TransactionRules/Actions/SetNotes.php | 3 +- .../Actions/SetSourceAccount.php | 19 ++--- .../Actions/SetSourceToCashAccount.php | 13 ++-- .../Actions/SwitchAccounts.php | 9 ++- .../Engine/SearchRuleEngine.php | 28 +++---- .../Expressions/ActionExpression.php | 4 +- .../Factory/ActionFactory.php | 3 +- app/Transformers/AbstractTransformer.php | 9 +-- app/Transformers/BudgetLimitTransformer.php | 4 +- .../PiggyBankEventTransformer.php | 2 +- app/Transformers/RecurrenceTransformer.php | 5 -- .../TransactionGroupTransformer.php | 11 +-- app/Transformers/UserGroupTransformer.php | 13 +--- app/Transformers/WebhookTransformer.php | 5 -- app/Validation/Account/DepositValidation.php | 14 ++-- .../Account/LiabilityValidation.php | 33 ++++---- app/Validation/Account/OBValidation.php | 8 +- .../Account/ReconciliationValidation.php | 23 +++--- app/Validation/Account/TransferValidation.php | 27 +++---- .../Account/WithdrawalValidation.php | 22 +++--- app/Validation/AccountValidator.php | 29 +++---- .../Bulk/ValidatesBulkTransactionQuery.php | 2 +- .../AutoBudget/ValidatesAutoBudgetRequest.php | 8 +- app/Validation/CurrencyValidation.php | 4 +- app/Validation/FireflyValidator.php | 8 +- app/Validation/GroupValidation.php | 25 +++--- app/Validation/RecurrenceValidation.php | 49 ++++++------ app/Validation/TransactionValidation.php | 38 +++------ bootstrap/app.php | 8 -- config/app.php | 2 +- config/auth.php | 2 +- config/database.php | 16 ++-- config/debugbar.php | 2 +- config/session.php | 4 +- routes/channels.php | 2 +- routes/web.php | 2 +- .../Api/Chart/AccountControllerTest.php | 5 +- .../Api/Chart/BalanceControllerTest.php | 5 +- .../Api/Chart/BudgetControllerTest.php | 5 +- .../Api/Chart/CategoryControllerTest.php | 5 +- .../Api/Models/Account/ListControllerTest.php | 2 + .../Api/Models/Account/ShowControllerTest.php | 2 + .../Api/System/AboutControllerTest.php | 7 +- 209 files changed, 1021 insertions(+), 1248 deletions(-) diff --git a/app/Models/RecurrenceRepetition.php b/app/Models/RecurrenceRepetition.php index 52d8259877..3e11acc67e 100644 --- a/app/Models/RecurrenceRepetition.php +++ b/app/Models/RecurrenceRepetition.php @@ -82,21 +82,21 @@ class RecurrenceRepetition extends Model protected function recurrenceId(): Attribute { return Attribute::make( - get: static fn ($value) => (int)$value, + get: static fn ($value): int => (int)$value, ); } protected function repetitionSkip(): Attribute { return Attribute::make( - get: static fn ($value) => (int)$value, + get: static fn ($value): int => (int)$value, ); } protected function weekend(): Attribute { return Attribute::make( - get: static fn ($value) => (int)$value, + get: static fn ($value): int => (int)$value, ); } } diff --git a/app/Models/RecurrenceTransaction.php b/app/Models/RecurrenceTransaction.php index c2d91a54ad..c1a1892b83 100644 --- a/app/Models/RecurrenceTransaction.php +++ b/app/Models/RecurrenceTransaction.php @@ -91,7 +91,7 @@ class RecurrenceTransaction extends Model protected function amount(): Attribute { return Attribute::make( - get: static fn ($value) => (string)$value, + get: static fn ($value): string => (string)$value, ); } @@ -110,42 +110,42 @@ class RecurrenceTransaction extends Model protected function destinationId(): Attribute { return Attribute::make( - get: static fn ($value) => (int)$value, + get: static fn ($value): int => (int)$value, ); } protected function foreignAmount(): Attribute { return Attribute::make( - get: static fn ($value) => (string)$value, + get: static fn ($value): string => (string)$value, ); } protected function recurrenceId(): Attribute { return Attribute::make( - get: static fn ($value) => (int)$value, + get: static fn ($value): int => (int)$value, ); } protected function sourceId(): Attribute { return Attribute::make( - get: static fn ($value) => (int)$value, + get: static fn ($value): int => (int)$value, ); } protected function transactionCurrencyId(): Attribute { return Attribute::make( - get: static fn ($value) => (int)$value, + get: static fn ($value): int => (int)$value, ); } protected function userId(): Attribute { return Attribute::make( - get: static fn ($value) => (int)$value, + get: static fn ($value): int => (int)$value, ); } } diff --git a/app/Models/RecurrenceTransactionMeta.php b/app/Models/RecurrenceTransactionMeta.php index 442da02559..5ced2d13ae 100644 --- a/app/Models/RecurrenceTransactionMeta.php +++ b/app/Models/RecurrenceTransactionMeta.php @@ -58,7 +58,7 @@ class RecurrenceTransactionMeta extends Model protected function rtId(): Attribute { return Attribute::make( - get: static fn ($value) => (int)$value, + get: static fn ($value): int => (int)$value, ); } } diff --git a/app/Models/Rule.php b/app/Models/Rule.php index d2c235f532..cffe9515e3 100644 --- a/app/Models/Rule.php +++ b/app/Models/Rule.php @@ -113,20 +113,20 @@ class Rule extends Model protected function description(): Attribute { - return Attribute::make(set: fn ($value) => ['description' => e($value)]); + return Attribute::make(set: fn ($value): array => ['description' => e($value)]); } protected function order(): Attribute { return Attribute::make( - get: static fn ($value) => (int)$value, + get: static fn ($value): int => (int)$value, ); } protected function ruleGroupId(): Attribute { return Attribute::make( - get: static fn ($value) => (int)$value, + get: static fn ($value): int => (int)$value, ); } } diff --git a/app/Models/RuleAction.php b/app/Models/RuleAction.php index 0bb29a5236..3b706470b8 100644 --- a/app/Models/RuleAction.php +++ b/app/Models/RuleAction.php @@ -80,14 +80,14 @@ class RuleAction extends Model protected function order(): Attribute { return Attribute::make( - get: static fn ($value) => (int)$value, + get: static fn ($value): int => (int)$value, ); } protected function ruleId(): Attribute { return Attribute::make( - get: static fn ($value) => (int)$value, + get: static fn ($value): int => (int)$value, ); } } diff --git a/app/Models/RuleGroup.php b/app/Models/RuleGroup.php index 16c87815bd..2236efbf1a 100644 --- a/app/Models/RuleGroup.php +++ b/app/Models/RuleGroup.php @@ -99,7 +99,7 @@ class RuleGroup extends Model protected function order(): Attribute { return Attribute::make( - get: static fn ($value) => (int)$value, + get: static fn ($value): int => (int)$value, ); } } diff --git a/app/Models/RuleTrigger.php b/app/Models/RuleTrigger.php index c3de8048ba..303ca028bb 100644 --- a/app/Models/RuleTrigger.php +++ b/app/Models/RuleTrigger.php @@ -53,14 +53,14 @@ class RuleTrigger extends Model protected function order(): Attribute { return Attribute::make( - get: static fn ($value) => (int)$value, + get: static fn ($value): int => (int)$value, ); } protected function ruleId(): Attribute { return Attribute::make( - get: static fn ($value) => (int)$value, + get: static fn ($value): int => (int)$value, ); } } diff --git a/app/Models/Transaction.php b/app/Models/Transaction.php index e33cb0a1ac..90faba82d4 100644 --- a/app/Models/Transaction.php +++ b/app/Models/Transaction.php @@ -113,7 +113,7 @@ class Transaction extends Model protected function accountId(): Attribute { return Attribute::make( - get: static fn ($value) => (int)$value, + get: static fn ($value): int => (int)$value, ); } @@ -151,14 +151,14 @@ class Transaction extends Model protected function amount(): Attribute { return Attribute::make( - get: static fn ($value) => (string)$value, + get: static fn ($value): string => (string)$value, ); } protected function balanceDirty(): Attribute { return Attribute::make( - get: static fn ($value) => 1 === (int)$value, + get: static fn ($value): bool => 1 === (int)$value, ); } @@ -201,14 +201,14 @@ class Transaction extends Model protected function foreignAmount(): Attribute { return Attribute::make( - get: static fn ($value) => (string)$value, + get: static fn ($value): string => (string)$value, ); } protected function transactionJournalId(): Attribute { return Attribute::make( - get: static fn ($value) => (int)$value, + get: static fn ($value): int => (int)$value, ); } diff --git a/app/Models/TransactionCurrency.php b/app/Models/TransactionCurrency.php index 6f02375355..418442db77 100644 --- a/app/Models/TransactionCurrency.php +++ b/app/Models/TransactionCurrency.php @@ -115,7 +115,7 @@ class TransactionCurrency extends Model protected function decimalPlaces(): Attribute { return Attribute::make( - get: static fn ($value) => (int)$value, + get: static fn ($value): int => (int)$value, ); } } diff --git a/app/Models/TransactionJournal.php b/app/Models/TransactionJournal.php index f6bd140648..6cab9c4e52 100644 --- a/app/Models/TransactionJournal.php +++ b/app/Models/TransactionJournal.php @@ -232,14 +232,14 @@ class TransactionJournal extends Model protected function order(): Attribute { return Attribute::make( - get: static fn ($value) => (int)$value, + get: static fn ($value): int => (int)$value, ); } protected function transactionTypeId(): Attribute { return Attribute::make( - get: static fn ($value) => (int)$value, + get: static fn ($value): int => (int)$value, ); } diff --git a/app/Models/TransactionJournalLink.php b/app/Models/TransactionJournalLink.php index ab1a40c260..2bb5738c87 100644 --- a/app/Models/TransactionJournalLink.php +++ b/app/Models/TransactionJournalLink.php @@ -94,21 +94,21 @@ class TransactionJournalLink extends Model protected function destinationId(): Attribute { return Attribute::make( - get: static fn ($value) => (int)$value, + get: static fn ($value): int => (int)$value, ); } protected function linkTypeId(): Attribute { return Attribute::make( - get: static fn ($value) => (int)$value, + get: static fn ($value): int => (int)$value, ); } protected function sourceId(): Attribute { return Attribute::make( - get: static fn ($value) => (int)$value, + get: static fn ($value): int => (int)$value, ); } } diff --git a/app/Models/TransactionJournalMeta.php b/app/Models/TransactionJournalMeta.php index 4a748bfb8b..25272f084b 100644 --- a/app/Models/TransactionJournalMeta.php +++ b/app/Models/TransactionJournalMeta.php @@ -57,7 +57,7 @@ class TransactionJournalMeta extends Model protected function data(): Attribute { - return Attribute::make(get: fn ($value) => json_decode((string)$value, false), set: function ($value) { + return Attribute::make(get: fn ($value): mixed => json_decode((string)$value, false), set: function ($value): array { $data = json_encode($value); return ['data' => $data, 'hash' => hash('sha256', $data)]; @@ -67,7 +67,7 @@ class TransactionJournalMeta extends Model protected function transactionJournalId(): Attribute { return Attribute::make( - get: static fn ($value) => (int)$value, + get: static fn ($value): int => (int)$value, ); } } diff --git a/app/Models/WebhookAttempt.php b/app/Models/WebhookAttempt.php index a2de5dac3b..bd3f2b7866 100644 --- a/app/Models/WebhookAttempt.php +++ b/app/Models/WebhookAttempt.php @@ -68,7 +68,7 @@ class WebhookAttempt extends Model protected function webhookMessageId(): Attribute { return Attribute::make( - get: static fn ($value) => (int)$value, + get: static fn ($value): int => (int)$value, ); } } diff --git a/app/Models/WebhookDelivery.php b/app/Models/WebhookDelivery.php index 33acf3b9b7..8ac1514a0a 100644 --- a/app/Models/WebhookDelivery.php +++ b/app/Models/WebhookDelivery.php @@ -41,7 +41,7 @@ class WebhookDelivery extends Model protected function key(): Attribute { return Attribute::make( - get: static fn ($value) => (int)$value, + get: static fn ($value): int => (int)$value, ); } } diff --git a/app/Models/WebhookMessage.php b/app/Models/WebhookMessage.php index dbccb97cbd..0209109c7d 100644 --- a/app/Models/WebhookMessage.php +++ b/app/Models/WebhookMessage.php @@ -89,14 +89,14 @@ class WebhookMessage extends Model protected function sent(): Attribute { return Attribute::make( - get: static fn ($value) => (bool)$value, + get: static fn ($value): bool => (bool)$value, ); } protected function webhookId(): Attribute { return Attribute::make( - get: static fn ($value) => (int)$value, + get: static fn ($value): int => (int)$value, ); } } diff --git a/app/Models/WebhookResponse.php b/app/Models/WebhookResponse.php index 7b3e785a73..1cc885f9ef 100644 --- a/app/Models/WebhookResponse.php +++ b/app/Models/WebhookResponse.php @@ -41,7 +41,7 @@ class WebhookResponse extends Model protected function key(): Attribute { return Attribute::make( - get: static fn ($value) => (int)$value, + get: static fn ($value): int => (int)$value, ); } } diff --git a/app/Models/WebhookTrigger.php b/app/Models/WebhookTrigger.php index b7ccd7cfc5..7608d43d93 100644 --- a/app/Models/WebhookTrigger.php +++ b/app/Models/WebhookTrigger.php @@ -41,7 +41,7 @@ class WebhookTrigger extends Model protected function key(): Attribute { return Attribute::make( - get: static fn ($value) => (int)$value, + get: static fn ($value): int => (int)$value, ); } } diff --git a/app/Notifications/User/NewAccessToken.php b/app/Notifications/User/NewAccessToken.php index d6f4728e25..4c360da056 100644 --- a/app/Notifications/User/NewAccessToken.php +++ b/app/Notifications/User/NewAccessToken.php @@ -42,8 +42,6 @@ class NewAccessToken extends Notification { use Queueable; - public function __construct() {} - public function toArray(User $notifiable): array { return [ diff --git a/app/Notifications/User/UserRegistration.php b/app/Notifications/User/UserRegistration.php index fe0bbde10f..f00366f585 100644 --- a/app/Notifications/User/UserRegistration.php +++ b/app/Notifications/User/UserRegistration.php @@ -36,8 +36,6 @@ class UserRegistration extends Notification { use Queueable; - public function __construct() {} - /** * @SuppressWarnings("PHPMD.UnusedFormalParameter") */ diff --git a/app/Providers/AppServiceProvider.php b/app/Providers/AppServiceProvider.php index 263342b753..70eb14d731 100644 --- a/app/Providers/AppServiceProvider.php +++ b/app/Providers/AppServiceProvider.php @@ -61,7 +61,7 @@ class AppServiceProvider extends ServiceProvider }); // blade extension - Blade::directive('activeXRoutePartial', function (string $route) { + Blade::directive('activeXRoutePartial', function (string $route): string { $name = Route::getCurrentRoute()->getName() ?? ''; if (str_contains($name, $route)) { return 'menu-open'; @@ -69,7 +69,7 @@ class AppServiceProvider extends ServiceProvider return ''; }); - Blade::if('partialroute', function (string $route, string $firstParam = '') { + Blade::if('partialroute', function (string $route, string $firstParam = ''): bool { $name = Route::getCurrentRoute()->getName() ?? ''; if ('' === $firstParam && str_contains($name, $route)) { return true; @@ -79,11 +79,7 @@ class AppServiceProvider extends ServiceProvider $params = Route::getCurrentRoute()->parameters(); $params ??= []; $objectType = $params['objectType'] ?? ''; - if ($objectType === $firstParam && str_contains($name, $route)) { - return true; - } - - return false; + return $objectType === $firstParam && str_contains($name, $route); }); } diff --git a/app/Providers/AuthServiceProvider.php b/app/Providers/AuthServiceProvider.php index 9f39f3d8a8..621ed90117 100644 --- a/app/Providers/AuthServiceProvider.php +++ b/app/Providers/AuthServiceProvider.php @@ -48,12 +48,12 @@ class AuthServiceProvider extends ServiceProvider { Auth::provider( 'remote_user_provider', - static fn ($app, array $config) => new RemoteUserProvider() + static fn ($app, array $config): RemoteUserProvider => new RemoteUserProvider() ); Auth::extend( 'remote_user_guard', - static fn ($app, string $name, array $config) => new RemoteUserGuard(Auth::createUserProvider($config['provider']), $app) + static fn ($app, string $name, array $config): RemoteUserGuard => new RemoteUserGuard(Auth::createUserProvider($config['provider']), $app) ); Passport::tokensExpireIn(now()->addDays(14)); diff --git a/app/Providers/CurrencyServiceProvider.php b/app/Providers/CurrencyServiceProvider.php index 3b6a751b64..dbb917d293 100644 --- a/app/Providers/CurrencyServiceProvider.php +++ b/app/Providers/CurrencyServiceProvider.php @@ -51,7 +51,7 @@ class CurrencyServiceProvider extends ServiceProvider $this->app->bind( static function (Application $app): GroupCurrencyRepositoryInterface { /** @var CurrencyRepository $repository */ - $repository = app(CurrencyRepository::class); + $repository = app(GroupCurrencyRepository::class); // phpstan does not get the reference to auth if ($app->auth->check()) { // @phpstan-ignore-line $repository->setUser(auth()->user()); diff --git a/app/Providers/FireflyServiceProvider.php b/app/Providers/FireflyServiceProvider.php index cb9bebbbf4..7cd545d40f 100644 --- a/app/Providers/FireflyServiceProvider.php +++ b/app/Providers/FireflyServiceProvider.php @@ -93,7 +93,7 @@ class FireflyServiceProvider extends ServiceProvider public function boot(): void { Validator::resolver( - static fn ($translator, $data, $rules, $messages) => new FireflyValidator($translator, $data, $rules, $messages) + static fn ($translator, $data, $rules, $messages): FireflyValidator => new FireflyValidator($translator, $data, $rules, $messages) ); } @@ -107,52 +107,52 @@ class FireflyServiceProvider extends ServiceProvider { $this->app->bind( 'preferences', - static fn () => new Preferences() + static fn (): Preferences => new Preferences() ); $this->app->bind( 'fireflyconfig', - static fn () => new FireflyConfig() + static fn (): FireflyConfig => new FireflyConfig() ); $this->app->bind( 'navigation', - static fn () => new Navigation() + static fn (): Navigation => new Navigation() ); $this->app->bind( 'amount', - static fn () => new Amount() + static fn (): Amount => new Amount() ); $this->app->bind( 'steam', - static fn () => new Steam() + static fn (): Steam => new Steam() ); $this->app->bind( 'balance', - static fn () => new Balance() + static fn (): Balance => new Balance() ); $this->app->bind( 'expandedform', - static fn () => new ExpandedForm() + static fn (): ExpandedForm => new ExpandedForm() ); $this->app->bind( 'accountform', - static fn () => new AccountForm() + static fn (): AccountForm => new AccountForm() ); $this->app->bind( 'currencyform', - static fn () => new CurrencyForm() + static fn (): CurrencyForm => new CurrencyForm() ); $this->app->bind( 'piggybankform', - static fn () => new PiggyBankForm() + static fn (): PiggyBankForm => new PiggyBankForm() ); $this->app->bind( 'ruleform', - static fn () => new RuleForm() + static fn (): RuleForm => new RuleForm() ); // chart generator: diff --git a/app/Providers/FireflySessionProvider.php b/app/Providers/FireflySessionProvider.php index fee1b30ed6..6912eb254a 100644 --- a/app/Providers/FireflySessionProvider.php +++ b/app/Providers/FireflySessionProvider.php @@ -53,7 +53,7 @@ class FireflySessionProvider extends ServiceProvider { $this->app->singleton( 'session', - static fn ($app) => new SessionManager($app) + static fn ($app): SessionManager => new SessionManager($app) ); } diff --git a/app/Repositories/Account/AccountRepository.php b/app/Repositories/Account/AccountRepository.php index 8eacb438b4..546953a8c8 100644 --- a/app/Repositories/Account/AccountRepository.php +++ b/app/Repositories/Account/AccountRepository.php @@ -224,7 +224,7 @@ class AccountRepository implements AccountRepositoryInterface, UserGroupInterfac $disk = Storage::disk('upload'); return $set->each( - static function (Attachment $attachment) use ($disk) { // @phpstan-ignore-line + static function (Attachment $attachment) use ($disk): Attachment { // @phpstan-ignore-line $notes = $attachment->notes()->first(); $attachment->file_exists = $disk->exists($attachment->fileName()); $attachment->notes_text = null !== $notes ? $notes->text : ''; @@ -414,7 +414,7 @@ class AccountRepository implements AccountRepositoryInterface, UserGroupInterfac public function getMetaValue(Account $account, string $field): ?string { $result = $account->accountMeta->filter( - static fn (AccountMeta $meta) => strtolower($meta->name) === strtolower($field) + static fn (AccountMeta $meta): bool => strtolower($meta->name) === strtolower($field) ); if (0 === $result->count()) { return null; diff --git a/app/Repositories/Attachment/AttachmentRepository.php b/app/Repositories/Attachment/AttachmentRepository.php index cd0d3ea249..079b4b61dd 100644 --- a/app/Repositories/Attachment/AttachmentRepository.php +++ b/app/Repositories/Attachment/AttachmentRepository.php @@ -23,6 +23,7 @@ declare(strict_types=1); namespace FireflyIII\Repositories\Attachment; +use Illuminate\Support\Facades\Log; use Exception; use FireflyIII\Exceptions\FireflyException; use FireflyIII\Factory\AttachmentFactory; @@ -78,7 +79,7 @@ class AttachmentRepository implements AttachmentRepositoryInterface, UserGroupIn try { $unencryptedContent = Crypt::decrypt($encryptedContent); // verified } catch (DecryptException $e) { - app('log')->debug(sprintf('Could not decrypt attachment #%d but this is fine: %s', $attachment->id, $e->getMessage())); + Log::debug(sprintf('Could not decrypt attachment #%d but this is fine: %s', $attachment->id, $e->getMessage())); $unencryptedContent = $encryptedContent; } } @@ -161,7 +162,7 @@ class AttachmentRepository implements AttachmentRepositoryInterface, UserGroupIn try { $dbNote->delete(); } catch (LogicException $e) { - app('log')->error($e->getMessage()); + Log::error($e->getMessage()); } } diff --git a/app/Repositories/Bill/BillRepository.php b/app/Repositories/Bill/BillRepository.php index daa88a5a65..f33d339cc6 100644 --- a/app/Repositories/Bill/BillRepository.php +++ b/app/Repositories/Bill/BillRepository.php @@ -121,7 +121,7 @@ class BillRepository implements BillRepositoryInterface, UserGroupInterface if (null !== $billId) { $searchResult = $this->find($billId); if ($searchResult instanceof Bill) { - app('log')->debug(sprintf('Found bill based on #%d, will return it.', $billId)); + Log::debug(sprintf('Found bill based on #%d, will return it.', $billId)); return $searchResult; } @@ -129,12 +129,12 @@ class BillRepository implements BillRepositoryInterface, UserGroupInterface if (null !== $billName) { $searchResult = $this->findByName($billName); if ($searchResult instanceof Bill) { - app('log')->debug(sprintf('Found bill based on "%s", will return it.', $billName)); + Log::debug(sprintf('Found bill based on "%s", will return it.', $billName)); return $searchResult; } } - app('log')->debug('Found no bill in findBill()'); + Log::debug('Found no bill in findBill()'); return null; } @@ -166,7 +166,7 @@ class BillRepository implements BillRepositoryInterface, UserGroupInterface $disk = Storage::disk('upload'); return $set->each( - static function (Attachment $attachment) use ($disk) { // @phpstan-ignore-line + static function (Attachment $attachment) use ($disk): Attachment { // @phpstan-ignore-line $notes = $attachment->notes()->first(); $attachment->file_exists = $disk->exists($attachment->fileName()); $attachment->notes_text = null !== $notes ? $notes->text : ''; @@ -307,7 +307,7 @@ class BillRepository implements BillRepositoryInterface, UserGroupInterface */ public function getPaidDatesInRange(Bill $bill, Carbon $start, Carbon $end): Collection { - // app('log')->debug('Now in getPaidDatesInRange()'); + // \Illuminate\Support\Facades\Log::debug('Now in getPaidDatesInRange()'); Log::debug(sprintf('Search for linked journals between %s and %s', $start->toW3cString(), $end->toW3cString())); @@ -440,7 +440,7 @@ class BillRepository implements BillRepositoryInterface, UserGroupInterface $journal = $bill->user->transactionJournals()->find((int) $transaction['transaction_journal_id']); $journal->bill_id = $bill->id; $journal->save(); - app('log')->debug(sprintf('Linked journal #%d to bill #%d', $journal->id, $bill->id)); + Log::debug(sprintf('Linked journal #%d to bill #%d', $journal->id, $bill->id)); } } @@ -459,12 +459,12 @@ class BillRepository implements BillRepositoryInterface, UserGroupInterface // find the most recent date for this bill NOT in the future. Cache this date: $start = clone $bill->date; $start->startOfDay(); - app('log')->debug('nextExpectedMatch: Start is '.$start->format('Y-m-d')); + Log::debug('nextExpectedMatch: Start is '.$start->format('Y-m-d')); while ($start < $date) { - app('log')->debug(sprintf('$start (%s) < $date (%s)', $start->format('Y-m-d H:i:s'), $date->format('Y-m-d H:i:s'))); + Log::debug(sprintf('$start (%s) < $date (%s)', $start->format('Y-m-d H:i:s'), $date->format('Y-m-d H:i:s'))); $start = app('navigation')->addPeriod($start, $bill->repeat_freq, $bill->skip); - app('log')->debug('Start is now '.$start->format('Y-m-d H:i:s')); + Log::debug('Start is now '.$start->format('Y-m-d H:i:s')); } $end = app('navigation')->addPeriod($start, $bill->repeat_freq, $bill->skip); @@ -475,12 +475,12 @@ class BillRepository implements BillRepositoryInterface, UserGroupInterface if ($journalCount > 0) { // this period had in fact a bill. The new start is the current end, and we create a new end. - app('log')->debug(sprintf('Journal count is %d, so start becomes %s', $journalCount, $end->format('Y-m-d'))); + Log::debug(sprintf('Journal count is %d, so start becomes %s', $journalCount, $end->format('Y-m-d'))); $start = clone $end; $end = app('navigation')->addPeriod($start, $bill->repeat_freq, $bill->skip); } - app('log')->debug('nextExpectedMatch: Final start is '.$start->format('Y-m-d')); - app('log')->debug('nextExpectedMatch: Matching end is '.$end->format('Y-m-d')); + Log::debug('nextExpectedMatch: Final start is '.$start->format('Y-m-d')); + Log::debug('nextExpectedMatch: Matching end is '.$end->format('Y-m-d')); $cache->store($start); @@ -597,7 +597,7 @@ class BillRepository implements BillRepositoryInterface, UserGroupInterface public function sumUnpaidInRange(Carbon $start, Carbon $end): array { - app('log')->debug(sprintf('Now in sumUnpaidInRange("%s", "%s")', $start->format('Y-m-d'), $end->format('Y-m-d'))); + Log::debug(sprintf('Now in sumUnpaidInRange("%s", "%s")', $start->format('Y-m-d'), $end->format('Y-m-d'))); $bills = $this->getActiveBills(); $return = []; $convertToPrimary = Amount::convertToPrimary($this->user); @@ -605,12 +605,12 @@ class BillRepository implements BillRepositoryInterface, UserGroupInterface /** @var Bill $bill */ foreach ($bills as $bill) { - // app('log')->debug(sprintf('Processing bill #%d ("%s")', $bill->id, $bill->name)); + // \Illuminate\Support\Facades\Log::debug(sprintf('Processing bill #%d ("%s")', $bill->id, $bill->name)); $dates = $this->getPayDatesInRange($bill, $start, $end); $count = $bill->transactionJournals()->after($start)->before($end)->count(); $total = $dates->count() - $count; - // app('log')->debug(sprintf('Pay dates: %d, count: %d, left: %d', $dates->count(), $count, $total)); - // app('log')->debug('dates', $dates->toArray()); + // \Illuminate\Support\Facades\Log::debug(sprintf('Pay dates: %d, count: %d, left: %d', $dates->count(), $count, $total)); + // \Illuminate\Support\Facades\Log::debug('dates', $dates->toArray()); $minField = $convertToPrimary && $bill->transactionCurrency->id !== $primary->id ? 'native_amount_min' : 'amount_min'; $maxField = $convertToPrimary && $bill->transactionCurrency->id !== $primary->id ? 'native_amount_max' : 'amount_max'; @@ -642,21 +642,21 @@ class BillRepository implements BillRepositoryInterface, UserGroupInterface { $set = new Collection(); $currentStart = clone $start; - // app('log')->debug(sprintf('Now at bill "%s" (%s)', $bill->name, $bill->repeat_freq)); - // app('log')->debug(sprintf('First currentstart is %s', $currentStart->format('Y-m-d'))); + // \Illuminate\Support\Facades\Log::debug(sprintf('Now at bill "%s" (%s)', $bill->name, $bill->repeat_freq)); + // \Illuminate\Support\Facades\Log::debug(sprintf('First currentstart is %s', $currentStart->format('Y-m-d'))); while ($currentStart <= $end) { - // app('log')->debug(sprintf('Currentstart is now %s.', $currentStart->format('Y-m-d'))); + // \Illuminate\Support\Facades\Log::debug(sprintf('Currentstart is now %s.', $currentStart->format('Y-m-d'))); $nextExpectedMatch = $this->nextDateMatch($bill, $currentStart); - // app('log')->debug(sprintf('Next Date match after %s is %s', $currentStart->format('Y-m-d'), $nextExpectedMatch->format('Y-m-d'))); + // \Illuminate\Support\Facades\Log::debug(sprintf('Next Date match after %s is %s', $currentStart->format('Y-m-d'), $nextExpectedMatch->format('Y-m-d'))); if ($nextExpectedMatch > $end) {// If nextExpectedMatch is after end, we continue break; } $set->push(clone $nextExpectedMatch); - // app('log')->debug(sprintf('Now %d dates in set.', $set->count())); + // \Illuminate\Support\Facades\Log::debug(sprintf('Now %d dates in set.', $set->count())); $nextExpectedMatch->addDay(); - // app('log')->debug(sprintf('Currentstart (%s) has become %s.', $currentStart->format('Y-m-d'), $nextExpectedMatch->format('Y-m-d'))); + // \Illuminate\Support\Facades\Log::debug(sprintf('Currentstart (%s) has become %s.', $currentStart->format('Y-m-d'), $nextExpectedMatch->format('Y-m-d'))); $currentStart = clone $nextExpectedMatch; } diff --git a/app/Repositories/Budget/AvailableBudgetRepository.php b/app/Repositories/Budget/AvailableBudgetRepository.php index e992bff82d..1e1e7ed017 100644 --- a/app/Repositories/Budget/AvailableBudgetRepository.php +++ b/app/Repositories/Budget/AvailableBudgetRepository.php @@ -53,7 +53,7 @@ class AvailableBudgetRepository implements AvailableBudgetRepositoryInterface, U $end = $availableBudget->end_date->format('Y-m-d'); $key = sprintf('%s-%s-%s', $availableBudget->transaction_currency_id, $start, $end); if (array_key_exists($key, $exists)) { - app('log')->debug(sprintf('Found duplicate AB: %s %s, %s-%s. Has been deleted', $availableBudget->transaction_currency_id, $availableBudget->amount, $start, $end)); + Log::debug(sprintf('Found duplicate AB: %s %s, %s-%s. Has been deleted', $availableBudget->transaction_currency_id, $availableBudget->amount, $start, $end)); $availableBudget->delete(); } $exists[$key] = true; diff --git a/app/Repositories/Budget/BudgetLimitRepository.php b/app/Repositories/Budget/BudgetLimitRepository.php index ab80405609..443f25677c 100644 --- a/app/Repositories/Budget/BudgetLimitRepository.php +++ b/app/Repositories/Budget/BudgetLimitRepository.php @@ -130,7 +130,7 @@ class BudgetLimitRepository implements BudgetLimitRepositoryInterface, UserGroup public function getAllBudgetLimitsByCurrency(TransactionCurrency $currency, ?Carbon $start = null, ?Carbon $end = null): Collection { return $this->getAllBudgetLimits($start, $end)->filter( - static fn (BudgetLimit $budgetLimit) => $budgetLimit->transaction_currency_id === $currency->id + static fn (BudgetLimit $budgetLimit): bool => $budgetLimit->transaction_currency_id === $currency->id ); } diff --git a/app/Repositories/Budget/BudgetRepository.php b/app/Repositories/Budget/BudgetRepository.php index 0b2d41395d..3714176818 100644 --- a/app/Repositories/Budget/BudgetRepository.php +++ b/app/Repositories/Budget/BudgetRepository.php @@ -307,7 +307,7 @@ class BudgetRepository implements BudgetRepositoryInterface, UserGroupInterface $autoBudget = $this->getAutoBudget($budget); // first things first: delete when no longer required: - $autoBudgetType = array_key_exists('auto_budget_type', $data) ? $data['auto_budget_type'] : null; + $autoBudgetType = $data['auto_budget_type'] ?? null; if (0 === $autoBudgetType && $autoBudget instanceof AutoBudget) { // delete! @@ -534,7 +534,7 @@ class BudgetRepository implements BudgetRepositoryInterface, UserGroupInterface $disk = Storage::disk('upload'); return $set->each( - static function (Attachment $attachment) use ($disk) { // @phpstan-ignore-line + static function (Attachment $attachment) use ($disk): Attachment { // @phpstan-ignore-line $notes = $attachment->notes()->first(); $attachment->file_exists = $disk->exists($attachment->fileName()); $attachment->notes_text = null !== $notes ? $notes->text : ''; diff --git a/app/Repositories/Budget/OperationsRepository.php b/app/Repositories/Budget/OperationsRepository.php index badde3a9fb..157e9ca4af 100644 --- a/app/Repositories/Budget/OperationsRepository.php +++ b/app/Repositories/Budget/OperationsRepository.php @@ -54,7 +54,7 @@ class OperationsRepository implements OperationsRepositoryInterface, UserGroupIn */ public function budgetedPerDay(Budget $budget): string { - app('log')->debug(sprintf('Now with budget #%d "%s"', $budget->id, $budget->name)); + Log::debug(sprintf('Now with budget #%d "%s"', $budget->id, $budget->name)); $total = '0'; $count = 0; foreach ($budget->budgetlimits as $limit) { @@ -64,13 +64,13 @@ class OperationsRepository implements OperationsRepositoryInterface, UserGroupIn $perDay = bcdiv((string) $amount, (string) $diff); $total = bcadd($total, $perDay); ++$count; - app('log')->debug(sprintf('Found %d budget limits. Per day is %s, total is %s', $count, $perDay, $total)); + Log::debug(sprintf('Found %d budget limits. Per day is %s, total is %s', $count, $perDay, $total)); } $avg = $total; if ($count > 0) { $avg = bcdiv($total, (string) $count); } - app('log')->debug(sprintf('%s / %d = %s = average.', $total, $count, $avg)); + Log::debug(sprintf('%s / %d = %s = average.', $total, $count, $avg)); return $avg; } diff --git a/app/Repositories/Category/CategoryRepository.php b/app/Repositories/Category/CategoryRepository.php index 6b1f75a91c..360e2a5409 100644 --- a/app/Repositories/Category/CategoryRepository.php +++ b/app/Repositories/Category/CategoryRepository.php @@ -108,11 +108,11 @@ class CategoryRepository implements CategoryRepositoryInterface, UserGroupInterf */ public function findCategory(?int $categoryId, ?string $categoryName): ?Category { - app('log')->debug('Now in findCategory()'); - app('log')->debug(sprintf('Searching for category with ID #%d...', $categoryId)); + Log::debug('Now in findCategory()'); + Log::debug(sprintf('Searching for category with ID #%d...', $categoryId)); $result = $this->find((int) $categoryId); if (!$result instanceof Category) { - app('log')->debug(sprintf('Searching for category with name %s...', $categoryName)); + Log::debug(sprintf('Searching for category with name %s...', $categoryName)); $result = $this->findByName((string) $categoryName); if (!$result instanceof Category && '' !== (string) $categoryName) { // create it! @@ -120,9 +120,9 @@ class CategoryRepository implements CategoryRepositoryInterface, UserGroupInterf } } if ($result instanceof Category) { - app('log')->debug(sprintf('Found category #%d: %s', $result->id, $result->name)); + Log::debug(sprintf('Found category #%d: %s', $result->id, $result->name)); } - app('log')->debug(sprintf('Found category result is null? %s', var_export(!$result instanceof Category, true))); + Log::debug(sprintf('Found category result is null? %s', var_export(!$result instanceof Category, true))); return $result; } @@ -240,7 +240,7 @@ class CategoryRepository implements CategoryRepositoryInterface, UserGroupInterf $disk = Storage::disk('upload'); return $set->each( - static function (Attachment $attachment) use ($disk) { // @phpstan-ignore-line + static function (Attachment $attachment) use ($disk): Attachment { // @phpstan-ignore-line $notes = $attachment->notes()->first(); $attachment->file_exists = $disk->exists($attachment->fileName()); $attachment->notes_text = null !== $notes ? $notes->text : ''; diff --git a/app/Repositories/Currency/CurrencyRepository.php b/app/Repositories/Currency/CurrencyRepository.php index eacd820c34..942bdccd5d 100644 --- a/app/Repositories/Currency/CurrencyRepository.php +++ b/app/Repositories/Currency/CurrencyRepository.php @@ -183,9 +183,9 @@ class CurrencyRepository implements CurrencyRepositoryInterface, UserGroupInterf $all = TransactionCurrency::orderBy('code', 'ASC')->get(); $local = $this->get(); - return $all->map(static function (TransactionCurrency $current) use ($local) { - $hasId = $local->contains(static fn (TransactionCurrency $entry) => $entry->id === $current->id); - $isPrimary = $local->contains(static fn (TransactionCurrency $entry) => 1 === (int)$entry->pivot->group_default && $entry->id === $current->id); + return $all->map(static function (TransactionCurrency $current) use ($local): TransactionCurrency { + $hasId = $local->contains(static fn (TransactionCurrency $entry): bool => $entry->id === $current->id); + $isPrimary = $local->contains(static fn (TransactionCurrency $entry): bool => 1 === (int)$entry->pivot->group_default && $entry->id === $current->id); $current->userGroupEnabled = $hasId; $current->userGroupNative = $isPrimary; @@ -196,14 +196,13 @@ class CurrencyRepository implements CurrencyRepositoryInterface, UserGroupInterf public function get(): Collection { $all = $this->userGroup->currencies()->orderBy('code', 'ASC')->withPivot(['group_default'])->get(); - $all->map(static function (TransactionCurrency $current) { // @phpstan-ignore-line + $all->map(static function (TransactionCurrency $current): TransactionCurrency { // @phpstan-ignore-line $current->userGroupEnabled = true; $current->userGroupNative = 1 === (int)$current->pivot->group_default; return $current; }); - /** @var Collection */ return $all; } @@ -402,7 +401,7 @@ class CurrencyRepository implements CurrencyRepositoryInterface, UserGroupInterf { Log::debug('Now in update()'); // can be true, false, null - $enabled = array_key_exists('enabled', $data) ? $data['enabled'] : null; + $enabled = $data['enabled'] ?? null; // can be true, false, but method only responds to "true". $default = array_key_exists('default', $data) ? $data['default'] : false; diff --git a/app/Repositories/Journal/JournalAPIRepository.php b/app/Repositories/Journal/JournalAPIRepository.php index 97efb75814..5a6dccdb64 100644 --- a/app/Repositories/Journal/JournalAPIRepository.php +++ b/app/Repositories/Journal/JournalAPIRepository.php @@ -65,7 +65,7 @@ class JournalAPIRepository implements JournalAPIRepositoryInterface, UserGroupIn $disk = Storage::disk('upload'); return $set->each( - static function (Attachment $attachment) use ($disk) { + static function (Attachment $attachment) use ($disk): Attachment { $notes = $attachment->notes()->first(); $attachment->file_exists = $disk->exists($attachment->fileName()); $attachment->notes_text = null !== $notes ? $notes->text : ''; // TODO should not set notes like this. diff --git a/app/Repositories/Journal/JournalRepository.php b/app/Repositories/Journal/JournalRepository.php index aee44f902b..f6c99daa4b 100644 --- a/app/Repositories/Journal/JournalRepository.php +++ b/app/Repositories/Journal/JournalRepository.php @@ -78,11 +78,7 @@ class JournalRepository implements JournalRepositoryInterface, UserGroupInterfac { /** @var null|TransactionJournal $entry */ $entry = $this->user->transactionJournals()->orderBy('date', 'ASC')->first(['transaction_journals.*']); - if (null !== $entry) { - return $entry; - } - - return null; + return $entry; } public function getDestinationAccount(TransactionJournal $journal): Account @@ -120,11 +116,7 @@ class JournalRepository implements JournalRepositoryInterface, UserGroupInterfac { /** @var null|TransactionJournal $entry */ $entry = $this->user->transactionJournals()->orderBy('date', 'DESC')->first(['transaction_journals.*']); - if (null !== $entry) { - return $entry; - } - - return null; + return $entry; } public function getLinkNoteText(TransactionJournalLink $link): string diff --git a/app/Repositories/LinkType/LinkTypeRepository.php b/app/Repositories/LinkType/LinkTypeRepository.php index 1110eb62ee..e978381255 100644 --- a/app/Repositories/LinkType/LinkTypeRepository.php +++ b/app/Repositories/LinkType/LinkTypeRepository.php @@ -23,6 +23,7 @@ declare(strict_types=1); namespace FireflyIII\Repositories\LinkType; +use Illuminate\Support\Facades\Log; use Exception; use FireflyIII\Models\LinkType; use FireflyIII\Models\Note; @@ -85,7 +86,7 @@ class LinkTypeRepository implements LinkTypeRepositoryInterface, UserGroupInterf */ public function findLink(TransactionJournal $one, TransactionJournal $two): bool { - app('log')->debug(sprintf('Now in findLink(%d, %d)', $one->id, $two->id)); + Log::debug(sprintf('Now in findLink(%d, %d)', $one->id, $two->id)); $count = TransactionJournalLink::whereDestinationId($one->id)->whereSourceId($two->id)->count(); $opposingCount = TransactionJournalLink::whereDestinationId($two->id)->whereSourceId($one->id)->count(); @@ -150,7 +151,7 @@ class LinkTypeRepository implements LinkTypeRepositoryInterface, UserGroupInterf $merged = $outward->merge($inward); return $merged->filter( - static fn (TransactionJournalLink $link) => null !== $link->source && null !== $link->destination + static fn (TransactionJournalLink $link): bool => null !== $link->source && null !== $link->destination ); } @@ -192,13 +193,13 @@ class LinkTypeRepository implements LinkTypeRepositoryInterface, UserGroupInterf $link = new TransactionJournalLink(); $link->linkType()->associate($linkType); if ('inward' === $information['direction']) { - app('log')->debug(sprintf('Link type is inwards ("%s"), so %d is source and %d is destination.', $linkType->inward, $inward->id, $outward->id)); + Log::debug(sprintf('Link type is inwards ("%s"), so %d is source and %d is destination.', $linkType->inward, $inward->id, $outward->id)); $link->source()->associate($inward); $link->destination()->associate($outward); } if ('outward' === $information['direction']) { - app('log')->debug(sprintf('Link type is inwards ("%s"), so %d is source and %d is destination.', $linkType->outward, $outward->id, $inward->id)); + Log::debug(sprintf('Link type is inwards ("%s"), so %d is source and %d is destination.', $linkType->outward, $outward->id, $inward->id)); $link->source()->associate($outward); $link->destination()->associate($inward); } diff --git a/app/Repositories/ObjectGroup/ObjectGroupRepository.php b/app/Repositories/ObjectGroup/ObjectGroupRepository.php index 4299155670..cd996dea24 100644 --- a/app/Repositories/ObjectGroup/ObjectGroupRepository.php +++ b/app/Repositories/ObjectGroup/ObjectGroupRepository.php @@ -24,6 +24,7 @@ declare(strict_types=1); namespace FireflyIII\Repositories\ObjectGroup; +use Illuminate\Support\Facades\Log; use FireflyIII\Models\ObjectGroup; use FireflyIII\Models\PiggyBank; use FireflyIII\Support\Repositories\UserGroup\UserGroupInterface; @@ -96,14 +97,14 @@ class ObjectGroupRepository implements ObjectGroupRepositoryInterface, UserGroup public function resetOrder(): void { - app('log')->debug('Now in resetOrder'); + Log::debug('Now in resetOrder'); $list = $this->get(); $index = 1; /** @var ObjectGroup $objectGroup */ foreach ($list as $objectGroup) { if ($index !== $objectGroup->order) { - app('log')->debug( + Log::debug( sprintf('objectGroup #%d ("%s"): order should %d be but is %d.', $objectGroup->id, $objectGroup->title, $index, $objectGroup->order) ); $objectGroup->order = $index; @@ -166,7 +167,7 @@ class ObjectGroupRepository implements ObjectGroupRepositoryInterface, UserGroup $objectGroup->save(); } - app('log')->debug(sprintf('Objectgroup #%d order is now %d', $objectGroup->id, $newOrder)); + Log::debug(sprintf('Objectgroup #%d order is now %d', $objectGroup->id, $newOrder)); return $objectGroup; } diff --git a/app/Repositories/PiggyBank/PiggyBankRepository.php b/app/Repositories/PiggyBank/PiggyBankRepository.php index 022de3a98c..fb4c4e7305 100644 --- a/app/Repositories/PiggyBank/PiggyBankRepository.php +++ b/app/Repositories/PiggyBank/PiggyBankRepository.php @@ -118,7 +118,7 @@ class PiggyBankRepository implements PiggyBankRepositoryInterface, UserGroupInte $disk = Storage::disk('upload'); return $set->each( - static function (Attachment $attachment) use ($disk) { // @phpstan-ignore-line + static function (Attachment $attachment) use ($disk): Attachment { // @phpstan-ignore-line $notes = $attachment->notes()->first(); $attachment->file_exists = $disk->exists($attachment->fileName()); $attachment->notes_text = null !== $notes ? $notes->text : ''; diff --git a/app/Repositories/Recurring/RecurringRepository.php b/app/Repositories/Recurring/RecurringRepository.php index 4e8a67ec0d..9726e41297 100644 --- a/app/Repositories/Recurring/RecurringRepository.php +++ b/app/Repositories/Recurring/RecurringRepository.php @@ -79,7 +79,7 @@ class RecurringRepository implements RecurringRepositoryInterface, UserGroupInte foreach ($set as $journalMeta) { $count = TransactionJournalMeta::where(static function (Builder $q2) use ($date): void { $string = (string) $date; - app('log')->debug(sprintf('Search for date: %s', json_encode($string))); + Log::debug(sprintf('Search for date: %s', json_encode($string))); $q2->where('name', 'recurrence_date'); $q2->where('data', json_encode($string)); }) @@ -87,7 +87,7 @@ class RecurringRepository implements RecurringRepositoryInterface, UserGroupInte ->count() ; if ($count > 0) { - app('log')->debug(sprintf('Looks like journal #%d was already created', $journalMeta->transaction_journal_id)); + Log::debug(sprintf('Looks like journal #%d was already created', $journalMeta->transaction_journal_id)); return true; } @@ -373,7 +373,7 @@ class RecurringRepository implements RecurringRepositoryInterface, UserGroupInte */ public function getXOccurrencesSince(RecurrenceRepetition $repetition, Carbon $date, Carbon $afterDate, int $count): array { - app('log')->debug('Now in getXOccurrencesSince()'); + Log::debug('Now in getXOccurrencesSince()'); $skipMod = $repetition->repetition_skip + 1; $occurrences = []; @@ -433,7 +433,7 @@ class RecurringRepository implements RecurringRepositoryInterface, UserGroupInte */ public function repetitionDescription(RecurrenceRepetition $repetition): string { - app('log')->debug('Now in repetitionDescription()'); + Log::debug('Now in repetitionDescription()'); /** @var Preference $pref */ $pref = app('preferences')->getForUser($this->user, 'language', config('firefly.default_language', 'en_US')); @@ -546,8 +546,8 @@ class RecurringRepository implements RecurringRepositoryInterface, UserGroupInte $mutator = clone $start; $mutator->startOfDay(); $skipMod = $repetition->repetition_skip + 1; - app('log')->debug(sprintf('Calculating occurrences for rep type "%s"', $repetition->repetition_type)); - app('log')->debug(sprintf('Mutator is now: %s', $mutator->format('Y-m-d'))); + Log::debug(sprintf('Calculating occurrences for rep type "%s"', $repetition->repetition_type)); + Log::debug(sprintf('Mutator is now: %s', $mutator->format('Y-m-d'))); if ('daily' === $repetition->repetition_type) { $occurrences = $this->getDailyInRange($mutator, $end, $skipMod); diff --git a/app/Repositories/Rule/RuleRepository.php b/app/Repositories/Rule/RuleRepository.php index e8435dc6c2..7954bacf39 100644 --- a/app/Repositories/Rule/RuleRepository.php +++ b/app/Repositories/Rule/RuleRepository.php @@ -23,6 +23,7 @@ declare(strict_types=1); namespace FireflyIII\Repositories\Rule; +use Illuminate\Support\Facades\Log; use Exception; use FireflyIII\Exceptions\FireflyException; use FireflyIII\Models\Rule; @@ -261,9 +262,9 @@ class RuleRepository implements RuleRepositoryInterface, UserGroupInterface // reset order: $this->resetRuleOrder($ruleGroup); - app('log')->debug('Done with resetting.'); + Log::debug('Done with resetting.'); if (array_key_exists('order', $data)) { - app('log')->debug(sprintf('User has submitted order %d', $data['order'])); + Log::debug(sprintf('User has submitted order %d', $data['order'])); $this->setOrder($rule, $data['order']); } @@ -318,7 +319,7 @@ class RuleRepository implements RuleRepositoryInterface, UserGroupInterface $groupId = $rule->rule_group_id; $maxOrder = $this->maxOrder($rule->ruleGroup); $newOrder = $newOrder > $maxOrder ? $maxOrder + 1 : $newOrder; - app('log')->debug(sprintf('New order will be %d', $newOrder)); + Log::debug(sprintf('New order will be %d', $newOrder)); if ($newOrder > $oldOrder) { $this->user->rules() @@ -329,7 +330,7 @@ class RuleRepository implements RuleRepositoryInterface, UserGroupInterface ->decrement('rules.order') ; $rule->order = $newOrder; - app('log')->debug(sprintf('Order of rule #%d ("%s") is now %d', $rule->id, $rule->title, $newOrder)); + Log::debug(sprintf('Order of rule #%d ("%s") is now %d', $rule->id, $rule->title, $newOrder)); $rule->save(); return; @@ -343,7 +344,7 @@ class RuleRepository implements RuleRepositoryInterface, UserGroupInterface ->increment('rules.order') ; $rule->order = $newOrder; - app('log')->debug(sprintf('Order of rule #%d ("%s") is now %d', $rule->id, $rule->title, $newOrder)); + Log::debug(sprintf('Order of rule #%d ("%s") is now %d', $rule->id, $rule->title, $newOrder)); $rule->save(); } diff --git a/app/Repositories/RuleGroup/RuleGroupRepository.php b/app/Repositories/RuleGroup/RuleGroupRepository.php index 37b6066a64..ead89a1b91 100644 --- a/app/Repositories/RuleGroup/RuleGroupRepository.php +++ b/app/Repositories/RuleGroup/RuleGroupRepository.php @@ -280,11 +280,11 @@ class RuleGroupRepository implements RuleGroupRepositoryInterface, UserGroupInte Log::debug(sprintf('Will filter getRuleGroupsWithRules on "%s".', $filter)); return $groups->map( - static function (RuleGroup $group) use ($filter) { // @phpstan-ignore-line + static function (RuleGroup $group) use ($filter): RuleGroup { // @phpstan-ignore-line Log::debug(sprintf('Now filtering group #%d', $group->id)); // filter the rules in the rule group: $group->rules = $group->rules->filter( - static function (Rule $rule) use ($filter, $group) { + static function (Rule $rule) use ($filter, $group): bool { Log::debug(sprintf('Now filtering rule #%d', $rule->id)); foreach ($rule->ruleTriggers as $trigger) { if ('user_action' === $trigger->trigger_type && $filter === $trigger->trigger_value) { @@ -337,11 +337,11 @@ class RuleGroupRepository implements RuleGroupRepositoryInterface, UserGroupInte Log::debug(sprintf('Will filter getRuleGroupsWithRules on "%s".', $filter)); return $groups->map( - static function (RuleGroup $group) use ($filter) { // @phpstan-ignore-line + static function (RuleGroup $group) use ($filter): RuleGroup { // @phpstan-ignore-line Log::debug(sprintf('Now filtering group #%d', $group->id)); // filter the rules in the rule group: $group->rules = $group->rules->filter( - static function (Rule $rule) use ($filter, $group) { + static function (Rule $rule) use ($filter, $group): bool { Log::debug(sprintf('Now filtering rule #%d', $rule->id)); foreach ($rule->ruleTriggers as $trigger) { if ('user_action' === $trigger->trigger_type && $filter === $trigger->trigger_value) { diff --git a/app/Repositories/Tag/TagRepository.php b/app/Repositories/Tag/TagRepository.php index b900e9143a..c7a51f7ef7 100644 --- a/app/Repositories/Tag/TagRepository.php +++ b/app/Repositories/Tag/TagRepository.php @@ -110,7 +110,6 @@ class TagRepository implements TagRepositoryInterface, UserGroupInterface public function firstUseDate(Tag $tag): ?Carbon { - /** @var null|Carbon */ return $tag->transactionJournals()->orderBy('date', 'ASC')->first()?->date; } @@ -137,13 +136,13 @@ class TagRepository implements TagRepositoryInterface, UserGroupInterface // add date range (or not): if (null === $year) { - app('log')->debug('Get tags without a date.'); + Log::debug('Get tags without a date.'); $tagQuery->whereNull('tags.date'); } if (null !== $year) { $year = min(2038, max(1970, $year)); - app('log')->debug(sprintf('Get tags with year %s.', $year)); + Log::debug(sprintf('Get tags with year %s.', $year)); $tagQuery->where('tags.date', '>=', sprintf('%d-01-01 00:00:00', $year))->where('tags.date', '<=', sprintf('%d-12-31 23:59:59', $year)); } $collection = $tagQuery->get(); @@ -177,7 +176,6 @@ class TagRepository implements TagRepositoryInterface, UserGroupInterface public function lastUseDate(Tag $tag): ?Carbon { - /** @var null|Carbon */ return $tag->transactionJournals()->orderBy('date', 'DESC')->first()?->date; } diff --git a/app/Repositories/TransactionGroup/TransactionGroupRepository.php b/app/Repositories/TransactionGroup/TransactionGroupRepository.php index fbf45efb73..e2f3842a54 100644 --- a/app/Repositories/TransactionGroup/TransactionGroupRepository.php +++ b/app/Repositories/TransactionGroup/TransactionGroupRepository.php @@ -24,6 +24,7 @@ declare(strict_types=1); namespace FireflyIII\Repositories\TransactionGroup; +use Illuminate\Support\Facades\Log; use Carbon\Carbon; use Exception; use FireflyIII\Enums\TransactionTypeEnum; @@ -78,7 +79,7 @@ class TransactionGroupRepository implements TransactionGroupRepositoryInterface, public function destroy(TransactionGroup $group): void { - app('log')->debug(sprintf('Now in %s', __METHOD__)); + Log::debug(sprintf('Now in %s', __METHOD__)); $service = new TransactionGroupDestroyService(); $service->destroy($group); } @@ -406,13 +407,13 @@ class TransactionGroupRepository implements TransactionGroupRepositoryInterface, try { return $factory->create($data); } catch (DuplicateTransactionException $e) { - app('log')->warning('Group repository caught group factory with a duplicate exception!'); + Log::warning('Group repository caught group factory with a duplicate exception!'); throw new DuplicateTransactionException($e->getMessage(), 0, $e); } catch (FireflyException $e) { - app('log')->warning('Group repository caught group factory with an exception!'); - app('log')->error($e->getMessage()); - app('log')->error($e->getTraceAsString()); + Log::warning('Group repository caught group factory with an exception!'); + Log::error($e->getMessage()); + Log::error($e->getTraceAsString()); throw new FireflyException($e->getMessage(), 0, $e); } diff --git a/app/Repositories/TransactionType/TransactionTypeRepository.php b/app/Repositories/TransactionType/TransactionTypeRepository.php index 55c0e2abe5..ffd2860e1e 100644 --- a/app/Repositories/TransactionType/TransactionTypeRepository.php +++ b/app/Repositories/TransactionType/TransactionTypeRepository.php @@ -24,6 +24,7 @@ declare(strict_types=1); namespace FireflyIII\Repositories\TransactionType; +use Illuminate\Support\Facades\Log; use FireflyIII\Enums\TransactionTypeEnum; use FireflyIII\Models\TransactionType; use Illuminate\Support\Collection; @@ -35,9 +36,9 @@ class TransactionTypeRepository implements TransactionTypeRepositoryInterface { public function findTransactionType(?TransactionType $type, ?string $typeString): TransactionType { - app('log')->debug('Now looking for a transaction type.'); + Log::debug('Now looking for a transaction type.'); if ($type instanceof TransactionType) { - app('log')->debug(sprintf('Found $type in parameters, its %s. Will return it.', $type->type)); + Log::debug(sprintf('Found $type in parameters, its %s. Will return it.', $type->type)); return $type; } @@ -46,7 +47,7 @@ class TransactionTypeRepository implements TransactionTypeRepositoryInterface if (!$search instanceof TransactionType) { $search = $this->findByType(TransactionTypeEnum::WITHDRAWAL->value); } - app('log')->debug(sprintf('Tried to search for "%s", came up with "%s". Will return it.', $typeString, $search->type)); + Log::debug(sprintf('Tried to search for "%s", came up with "%s". Will return it.', $typeString, $search->type)); return $search; } diff --git a/app/Repositories/User/UserRepository.php b/app/Repositories/User/UserRepository.php index da82fe44ad..be9abaf4df 100644 --- a/app/Repositories/User/UserRepository.php +++ b/app/Repositories/User/UserRepository.php @@ -23,6 +23,7 @@ declare(strict_types=1); namespace FireflyIII\Repositories\User; +use Illuminate\Support\Facades\Log; use Carbon\Carbon; use Exception; use FireflyIII\Exceptions\FireflyException; @@ -97,7 +98,7 @@ class UserRepository implements UserRepositoryInterface public function deleteInvite(InvitedUser $invite): void { - app('log')->debug(sprintf('Deleting invite #%d', $invite->id)); + Log::debug(sprintf('Deleting invite #%d', $invite->id)); $invite->delete(); } @@ -106,7 +107,7 @@ class UserRepository implements UserRepositoryInterface */ public function destroy(User $user): bool { - app('log')->debug(sprintf('Calling delete() on user %d', $user->id)); + Log::debug(sprintf('Calling delete() on user %d', $user->id)); $user->groupMemberships()->delete(); $user->delete(); @@ -123,7 +124,7 @@ class UserRepository implements UserRepositoryInterface foreach ($groups as $group) { $count = $group->groupMemberships()->count(); if (0 === $count) { - app('log')->info(sprintf('Deleted empty group #%d ("%s")', $group->id, $group->title)); + Log::info(sprintf('Deleted empty group #%d ("%s")', $group->id, $group->title)); $group->delete(); } } @@ -198,33 +199,12 @@ class UserRepository implements UserRepositoryInterface */ public function getUserData(User $user): array { - $return = []; - - // two factor: - $return['has_2fa'] = null !== $user->mfa_secret; - $return['is_admin'] = $this->hasRole($user, 'owner'); - $return['blocked'] = 1 === (int) $user->blocked; - $return['blocked_code'] = $user->blocked_code; - $return['accounts'] = $user->accounts()->count(); - $return['journals'] = $user->transactionJournals()->count(); - $return['transactions'] = $user->transactions()->count(); - $return['attachments'] = $user->attachments()->count(); - $return['attachments_size'] = $user->attachments()->sum('size'); - $return['bills'] = $user->bills()->count(); - $return['categories'] = $user->categories()->count(); - $return['budgets'] = $user->budgets()->count(); - $return['budgets_with_limits'] = BudgetLimit::distinct() + return ['has_2fa' => null !== $user->mfa_secret, 'is_admin' => $this->hasRole($user, 'owner'), 'blocked' => 1 === (int) $user->blocked, 'blocked_code' => $user->blocked_code, 'accounts' => $user->accounts()->count(), 'journals' => $user->transactionJournals()->count(), 'transactions' => $user->transactions()->count(), 'attachments' => $user->attachments()->count(), 'attachments_size' => $user->attachments()->sum('size'), 'bills' => $user->bills()->count(), 'categories' => $user->categories()->count(), 'budgets' => $user->budgets()->count(), 'budgets_with_limits' => BudgetLimit::distinct() ->leftJoin('budgets', 'budgets.id', '=', 'budget_limits.budget_id') ->where('amount', '>', 0) ->whereNull('budgets.deleted_at') ->where('budgets.user_id', $user->id) - ->count('budget_limits.budget_id') - ; - $return['rule_groups'] = $user->ruleGroups()->count(); - $return['rules'] = $user->rules()->count(); - $return['tags'] = $user->tags()->count(); - - return $return; + ->count('budget_limits.budget_id'), 'rule_groups' => $user->ruleGroups()->count(), 'rules' => $user->rules()->count(), 'tags' => $user->tags()->count()]; } public function hasRole(Authenticatable|User|null $user, string $role): bool @@ -327,7 +307,7 @@ class UserRepository implements UserRepositoryInterface { $roleObject = Role::where('name', $role)->first(); if (null === $roleObject) { - app('log')->error(sprintf('Could not find role "%s" in attachRole()', $role)); + Log::error(sprintf('Could not find role "%s" in attachRole()', $role)); return false; } @@ -336,7 +316,7 @@ class UserRepository implements UserRepositoryInterface $user->roles()->attach($roleObject); } catch (QueryException $e) { // don't care - app('log')->error(sprintf('Query exception when giving user a role: %s', $e->getMessage())); + Log::error(sprintf('Query exception when giving user a role: %s', $e->getMessage())); } return true; diff --git a/app/Repositories/UserGroup/UserGroupRepository.php b/app/Repositories/UserGroup/UserGroupRepository.php index 80b3fc459c..273b74eccf 100644 --- a/app/Repositories/UserGroup/UserGroupRepository.php +++ b/app/Repositories/UserGroup/UserGroupRepository.php @@ -24,6 +24,7 @@ declare(strict_types=1); namespace FireflyIII\Repositories\UserGroup; +use Illuminate\Support\Facades\Log; use FireflyIII\Enums\UserRoleEnum; use FireflyIII\Exceptions\FireflyException; use FireflyIII\Factory\UserGroupFactory; @@ -47,7 +48,7 @@ class UserGroupRepository implements UserGroupRepositoryInterface, UserGroupInte public function destroy(UserGroup $userGroup): void { - app('log')->debug(sprintf('Going to destroy user group #%d ("%s").', $userGroup->id, $userGroup->title)); + Log::debug(sprintf('Going to destroy user group #%d ("%s").', $userGroup->id, $userGroup->title)); $memberships = $userGroup->groupMemberships()->get(); /** @var GroupMembership $membership */ @@ -57,19 +58,19 @@ class UserGroupRepository implements UserGroupRepositoryInterface, UserGroupInte if (null === $user) { continue; } - app('log')->debug(sprintf('Processing membership #%d (user #%d "%s")', $membership->id, $user->id, $user->email)); + Log::debug(sprintf('Processing membership #%d (user #%d "%s")', $membership->id, $user->id, $user->email)); // user has memberships of other groups? $count = $user->groupMemberships()->where('user_group_id', '!=', $userGroup->id)->count(); if (0 === $count) { - app('log')->debug('User has no other memberships and needs a new user group.'); + Log::debug('User has no other memberships and needs a new user group.'); $newUserGroup = $this->createNewUserGroup($user); $user->user_group_id = $newUserGroup->id; $user->save(); - app('log')->debug(sprintf('Make new group #%d ("%s")', $newUserGroup->id, $newUserGroup->title)); + Log::debug(sprintf('Make new group #%d ("%s")', $newUserGroup->id, $newUserGroup->title)); } // user has other memberships, select one at random and assign it to the user. if ($count > 0) { - app('log')->debug('User has other memberships and will be assigned a new administration.'); + Log::debug('User has other memberships and will be assigned a new administration.'); /** @var GroupMembership $first */ $first = $user->groupMemberships()->where('user_group_id', '!=', $userGroup->id)->inRandomOrder()->first(); @@ -91,7 +92,7 @@ class UserGroupRepository implements UserGroupRepositoryInterface, UserGroupInte } } $userGroup->delete(); - app('log')->debug('Done!'); + Log::debug('Done!'); } /** @@ -216,23 +217,23 @@ class UserGroupRepository implements UserGroupRepositoryInterface, UserGroupInte public function updateMembership(UserGroup $userGroup, array $data): UserGroup { $owner = UserRole::whereTitle(UserRoleEnum::OWNER)->first(); - app('log')->debug('in update membership'); + Log::debug('in update membership'); /** @var null|User $user */ $user = null; if (array_key_exists('id', $data)) { /** @var null|User $user */ $user = User::find($data['id']); - app('log')->debug('Found user by ID'); + Log::debug('Found user by ID'); } if (array_key_exists('email', $data) && '' !== (string)$data['email']) { /** @var null|User $user */ $user = User::whereEmail($data['email'])->first(); - app('log')->debug('Found user by email'); + Log::debug('Found user by email'); } if (null === $user) { // should throw error, but validator already catches this. - app('log')->debug('No user found'); + Log::debug('No user found'); return $userGroup; } @@ -244,13 +245,13 @@ class UserGroupRepository implements UserGroupRepositoryInterface, UserGroupInte $lastUserId = $userGroup->groupMemberships()->distinct()->first(['group_memberships.user_id'])->user_id; // if this is also the user we're editing right now, and we remove all of their roles: if ($lastUserId === (int)$user->id && 0 === count($data['roles'])) { - app('log')->debug('User is last in this group, refuse to act'); + Log::debug('User is last in this group, refuse to act'); throw new FireflyException('You cannot remove the last member from this user group. Delete the user group instead.'); } // if this is also the user we're editing right now, and do not grant them the owner role: if ($lastUserId === (int)$user->id && count($data['roles']) > 0 && !in_array(UserRoleEnum::OWNER->value, $data['roles'], true)) { - app('log')->debug('User needs to have owner role in this group, refuse to act'); + Log::debug('User needs to have owner role in this group, refuse to act'); throw new FireflyException('The last member in this user group must get or keep the "owner" role.'); } @@ -267,7 +268,7 @@ class UserGroupRepository implements UserGroupRepositoryInterface, UserGroupInte && (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'); + 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.'); } @@ -294,12 +295,12 @@ class UserGroupRepository implements UserGroupRepositoryInterface, UserGroupInte private function simplifyListByName(array $roles): array { if (in_array(UserRoleEnum::OWNER->value, $roles, true)) { - app('log')->debug(sprintf('List of roles is [%1$s] but this includes "%2$s", so return [%2$s]', implode(',', $roles), UserRoleEnum::OWNER->value)); + Log::debug(sprintf('List of roles is [%1$s] but this includes "%2$s", so return [%2$s]', implode(',', $roles), UserRoleEnum::OWNER->value)); return [UserRoleEnum::OWNER->value]; } if (in_array(UserRoleEnum::FULL->value, $roles, true)) { - app('log')->debug(sprintf('List of roles is [%1$s] but this includes "%2$s", so return [%2$s]', implode(',', $roles), UserRoleEnum::FULL->value)); + Log::debug(sprintf('List of roles is [%1$s] but this includes "%2$s", so return [%2$s]', implode(',', $roles), UserRoleEnum::FULL->value)); return [UserRoleEnum::FULL->value]; } diff --git a/app/Repositories/Webhook/WebhookRepository.php b/app/Repositories/Webhook/WebhookRepository.php index fb8da51d2c..0e787a3a75 100644 --- a/app/Repositories/Webhook/WebhookRepository.php +++ b/app/Repositories/Webhook/WebhookRepository.php @@ -92,7 +92,7 @@ class WebhookRepository implements WebhookRepositoryInterface, UserGroupInterfac ->where('webhook_messages.errored', 0) ->get(['webhook_messages.*']) ->filter( - static fn (WebhookMessage $message) // @phpstan-ignore-line + static fn (WebhookMessage $message): bool // @phpstan-ignore-line => $message->webhookAttempts()->count() <= 2 )->splice(0, 3) ; diff --git a/app/Rules/Account/IsValidAccountTypeList.php b/app/Rules/Account/IsValidAccountTypeList.php index 8f5b7422f2..9cb71bf44c 100644 --- a/app/Rules/Account/IsValidAccountTypeList.php +++ b/app/Rules/Account/IsValidAccountTypeList.php @@ -47,7 +47,6 @@ class IsValidAccountTypeList implements ValidationRule } $keys = array_keys($this->types); foreach ($values as $entry) { - $entry = (string) $entry; if (!in_array($entry, $keys, true)) { $fail('validation.invalid_account_list')->translate(); } diff --git a/app/Rules/BelongsUser.php b/app/Rules/BelongsUser.php index 48e44ddcbc..811ada0f2c 100644 --- a/app/Rules/BelongsUser.php +++ b/app/Rules/BelongsUser.php @@ -24,6 +24,7 @@ declare(strict_types=1); namespace FireflyIII\Rules; +use Illuminate\Support\Facades\Log; use Closure; use FireflyIII\Exceptions\FireflyException; use FireflyIII\Models\Account; @@ -47,7 +48,7 @@ class BelongsUser implements ValidationRule return; } - app('log')->debug(sprintf('Going to validate %s', $attribute)); + Log::debug(sprintf('Going to validate %s', $attribute)); $result = match ($attribute) { 'piggy_bank_id' => $this->validatePiggyBankId((int) $value), @@ -126,7 +127,7 @@ class BelongsUser implements ValidationRule private function validateBillName(string $value): bool { $count = $this->countField(Bill::class, 'name', $value); - app('log')->debug(sprintf('Result of countField for bill name "%s" is %d', $value, $count)); + Log::debug(sprintf('Result of countField for bill name "%s" is %d', $value, $count)); return 1 === $count; } @@ -147,10 +148,10 @@ class BelongsUser implements ValidationRule $count = 0; foreach ($objects as $object) { $objectValue = trim((string) $object->{$field}); // @phpstan-ignore-line - app('log')->debug(sprintf('Comparing object "%s" with value "%s"', $objectValue, $value)); + Log::debug(sprintf('Comparing object "%s" with value "%s"', $objectValue, $value)); if ($objectValue === $value) { ++$count; - app('log')->debug(sprintf('Hit! Count is now %d', $count)); + Log::debug(sprintf('Hit! Count is now %d', $count)); } } diff --git a/app/Rules/BelongsUserGroup.php b/app/Rules/BelongsUserGroup.php index 488080a176..58d4fea871 100644 --- a/app/Rules/BelongsUserGroup.php +++ b/app/Rules/BelongsUserGroup.php @@ -24,6 +24,7 @@ declare(strict_types=1); namespace FireflyIII\Rules; +use Illuminate\Support\Facades\Log; use Closure; use FireflyIII\Exceptions\FireflyException; use FireflyIII\Models\Account; @@ -56,7 +57,7 @@ class BelongsUserGroup implements ValidationRule return; } - app('log')->debug(sprintf('Group: Going to validate "%s"', $attribute)); + Log::debug(sprintf('Group: Going to validate "%s"', $attribute)); $result = match ($attribute) { 'piggy_bank_id' => $this->validatePiggyBankId((int) $value), @@ -121,10 +122,10 @@ class BelongsUserGroup implements ValidationRule $count = 0; foreach ($objects as $object) { $objectValue = trim((string) $object->{$field}); // @phpstan-ignore-line - app('log')->debug(sprintf('Comparing object "%s" with value "%s"', $objectValue, $value)); + Log::debug(sprintf('Comparing object "%s" with value "%s"', $objectValue, $value)); if ($objectValue === $value) { ++$count; - app('log')->debug(sprintf('Hit! Count is now %d', $count)); + Log::debug(sprintf('Hit! Count is now %d', $count)); } } @@ -154,7 +155,7 @@ class BelongsUserGroup implements ValidationRule private function validateBillName(string $value): bool { $count = $this->countField(Bill::class, 'name', $value); - app('log')->debug(sprintf('Result of countField for bill name "%s" is %d', $value, $count)); + Log::debug(sprintf('Result of countField for bill name "%s" is %d', $value, $count)); return 1 === $count; } diff --git a/app/Rules/IsAllowedGroupAction.php b/app/Rules/IsAllowedGroupAction.php index 8f63f5012c..d590f21bfd 100644 --- a/app/Rules/IsAllowedGroupAction.php +++ b/app/Rules/IsAllowedGroupAction.php @@ -28,8 +28,6 @@ use Closure; use FireflyIII\Enums\UserRoleEnum; use FireflyIII\Exceptions\FireflyException; use FireflyIII\Models\Account; -use FireflyIII\Repositories\UserGroup\UserGroupRepositoryInterface; -use FireflyIII\User; use Illuminate\Auth\Access\AuthorizationException; use Illuminate\Contracts\Validation\ValidationRule; use Illuminate\Support\Facades\Log; @@ -37,14 +35,11 @@ use Override; class IsAllowedGroupAction implements ValidationRule { - private array $acceptedRoles; - private readonly UserGroupRepositoryInterface $repository; + // you need these roles to do anything with any endpoint. + private array $acceptedRoles = [UserRoleEnum::OWNER, UserRoleEnum::FULL]; public function __construct(private readonly string $className, private readonly string $methodName) { - // you need these roles to do anything with any endpoint. - $this->acceptedRoles = [UserRoleEnum::OWNER, UserRoleEnum::FULL]; - $this->repository = app(UserGroupRepositoryInterface::class); } /** @@ -69,68 +64,16 @@ class IsAllowedGroupAction implements ValidationRule break; } } - $this->validateUserGroup((int)$value, $fail); + $this->validateUserGroup(); } - private function validateUserGroup(int $userGroupId, Closure $fail): void + private function validateUserGroup(): void { try { throw new FireflyException('Here we are'); } catch (FireflyException $e) { Log::error($e->getTraceAsString()); } - exit('here we are'); - Log::debug(sprintf('validateUserGroup: %s', static::class)); - if (!auth()->check()) { - Log::debug('validateUserGroup: user is not logged in, return NULL.'); - $fail('validation.no_auth_user_group')->translate(); - - return; - } - - /** @var User $user */ - $user = auth()->user(); - if (0 !== $userGroupId) { - Log::debug(sprintf('validateUserGroup: user group submitted, search for memberships in group #%d.', $userGroupId)); - } - if (0 === $userGroupId) { - $userGroupId = $user->user_group_id; - Log::debug(sprintf('validateUserGroup: no user group submitted, use default group #%d.', $userGroupId)); - } - - $this->repository->setUser($user); - $memberships = $this->repository->getMembershipsFromGroupId($userGroupId); - - if (0 === $memberships->count()) { - Log::debug(sprintf('validateUserGroup: user has no access to group #%d.', $userGroupId)); - $fail('validation.no_access_user_group')->translate(); - - return; - } - - // need to get the group from the membership: - $userGroup = $this->repository->getById($userGroupId); - if (null === $userGroup) { - Log::debug(sprintf('validateUserGroup: group #%d does not exist.', $userGroupId)); - $fail('validation.belongs_user_or_user_group')->translate(); - - return; - } - Log::debug(sprintf('validateUserGroup: validate access of user to group #%d ("%s").', $userGroupId, $userGroup->title)); - Log::debug(sprintf('validateUserGroup: have %d roles to check.', count($this->acceptedRoles)), $this->acceptedRoles); - - /** @var UserRoleEnum $role */ - foreach ($this->acceptedRoles as $role) { - if ($user->hasRoleInGroupOrOwner($userGroup, $role)) { - Log::debug(sprintf('validateUserGroup: User has role "%s" in group #%d, return.', $role->value, $userGroupId)); - - return; - } - Log::debug(sprintf('validateUserGroup: User does NOT have role "%s" in group #%d, continue searching.', $role->value, $userGroupId)); - } - - Log::debug('validateUserGroup: User does NOT have enough rights to access endpoint.'); - $fail('validation.belongs_user_or_user_group')->translate(); } } diff --git a/app/Rules/IsDateOrTime.php b/app/Rules/IsDateOrTime.php index ae732d0ab3..309c894c32 100644 --- a/app/Rules/IsDateOrTime.php +++ b/app/Rules/IsDateOrTime.php @@ -24,6 +24,7 @@ declare(strict_types=1); namespace FireflyIII\Rules; +use Illuminate\Support\Facades\Log; use Carbon\Carbon; use Carbon\Exceptions\InvalidDateException; use Carbon\Exceptions\InvalidFormatException; @@ -51,13 +52,13 @@ class IsDateOrTime implements ValidationRule try { Carbon::createFromFormat('Y-m-d', $value); } catch (InvalidDateException $e) { // @phpstan-ignore-line - app('log')->error(sprintf('"%s" is not a valid date: %s', $value, $e->getMessage())); + Log::error(sprintf('"%s" is not a valid date: %s', $value, $e->getMessage())); $fail('validation.date_or_time')->translate(); return; } catch (InvalidFormatException $e) { - app('log')->error(sprintf('"%s" is of an invalid format: %s', $value, $e->getMessage())); + Log::error(sprintf('"%s" is of an invalid format: %s', $value, $e->getMessage())); $fail('validation.date_or_time')->translate(); @@ -71,13 +72,13 @@ class IsDateOrTime implements ValidationRule try { Carbon::parse($value); } catch (InvalidDateException $e) { // @phpstan-ignore-line - app('log')->error(sprintf('"%s" is not a valid date or time: %s', $value, $e->getMessage())); + Log::error(sprintf('"%s" is not a valid date or time: %s', $value, $e->getMessage())); $fail('validation.date_or_time')->translate(); return; } catch (InvalidFormatException $e) { - app('log')->error(sprintf('"%s" is of an invalid format: %s', $value, $e->getMessage())); + Log::error(sprintf('"%s" is of an invalid format: %s', $value, $e->getMessage())); $fail('validation.date_or_time')->translate(); diff --git a/app/Rules/IsDefaultUserGroupName.php b/app/Rules/IsDefaultUserGroupName.php index f59ff49327..5ad43e323f 100644 --- a/app/Rules/IsDefaultUserGroupName.php +++ b/app/Rules/IsDefaultUserGroupName.php @@ -24,6 +24,7 @@ declare(strict_types=1); namespace FireflyIII\Rules; +use Illuminate\Support\Facades\Log; use Closure; use FireflyIII\Models\UserGroup; use FireflyIII\Repositories\User\UserRepositoryInterface; @@ -42,7 +43,7 @@ class IsDefaultUserGroupName implements ValidationRule */ public function validate(string $attribute, mixed $value, Closure $fail): void { - app('log')->debug(sprintf('Now in %s(%s)', __METHOD__, $value)); + Log::debug(sprintf('Now in %s(%s)', __METHOD__, $value)); // are you owner of this group and the name is the same? fail. /** @var User $user */ diff --git a/app/Rules/IsTransferAccount.php b/app/Rules/IsTransferAccount.php index d64f30fa38..069f92715c 100644 --- a/app/Rules/IsTransferAccount.php +++ b/app/Rules/IsTransferAccount.php @@ -24,6 +24,7 @@ declare(strict_types=1); namespace FireflyIII\Rules; +use Illuminate\Support\Facades\Log; use Closure; use FireflyIII\Enums\TransactionTypeEnum; use FireflyIII\Validation\AccountValidator; @@ -39,7 +40,7 @@ class IsTransferAccount implements ValidationRule */ public function validate(string $attribute, mixed $value, Closure $fail): void { - app('log')->debug(sprintf('Now in %s(%s)', __METHOD__, $value)); + Log::debug(sprintf('Now in %s(%s)', __METHOD__, $value)); /** @var AccountValidator $validator */ $validator = app(AccountValidator::class); @@ -48,13 +49,13 @@ class IsTransferAccount implements ValidationRule $validAccount = $validator->validateSource(['name' => (string) $value]); if (true === $validAccount) { - app('log')->debug('Found account based on name. Return true.'); + Log::debug('Found account based on name. Return true.'); // found by name, use repos to return. return; } $validAccount = $validator->validateSource(['id' => (int) $value]); - app('log')->debug(sprintf('Search by id (%d), result is %s.', (int) $value, var_export($validAccount, true))); + Log::debug(sprintf('Search by id (%d), result is %s.', (int) $value, var_export($validAccount, true))); if (false === $validAccount) { $fail('validation.not_transfer_account')->translate(); diff --git a/app/Rules/IsValidDateRange.php b/app/Rules/IsValidDateRange.php index 75a6846fab..d396076dc4 100644 --- a/app/Rules/IsValidDateRange.php +++ b/app/Rules/IsValidDateRange.php @@ -24,6 +24,7 @@ declare(strict_types=1); namespace FireflyIII\Rules; +use Illuminate\Support\Facades\Log; use Carbon\Carbon; use Carbon\Exceptions\InvalidDateException; use Carbon\Exceptions\InvalidFormatException; @@ -54,13 +55,13 @@ class IsValidDateRange implements ValidationRule $left = Carbon::parse($value); $right = Carbon::parse($otherValue); } catch (InvalidDateException $e) { // @phpstan-ignore-line - app('log')->error(sprintf('"%s" or "%s" is not a valid date or time: %s', $value, $otherValue, $e->getMessage())); + Log::error(sprintf('"%s" or "%s" is not a valid date or time: %s', $value, $otherValue, $e->getMessage())); $fail('validation.date_or_time')->translate(); return; } catch (InvalidFormatException $e) { - app('log')->error(sprintf('"%s" or "%s" is of an invalid format: %s', $value, $otherValue, $e->getMessage())); + Log::error(sprintf('"%s" or "%s" is of an invalid format: %s', $value, $otherValue, $e->getMessage())); $fail('validation.date_or_time')->translate(); diff --git a/app/Rules/IsValidZeroOrMoreAmount.php b/app/Rules/IsValidZeroOrMoreAmount.php index f5880fa78a..eb10a43147 100644 --- a/app/Rules/IsValidZeroOrMoreAmount.php +++ b/app/Rules/IsValidZeroOrMoreAmount.php @@ -41,7 +41,7 @@ class IsValidZeroOrMoreAmount implements ValidationRule */ public function validate(string $attribute, mixed $value, Closure $fail): void { - if (true === $this->nullable && null === $value) { + if ($this->nullable && null === $value) { return; } $value = (string) $value; diff --git a/app/Rules/TransactionType/IsValidTransactionTypeList.php b/app/Rules/TransactionType/IsValidTransactionTypeList.php index f0c68e2af5..313f0090c1 100644 --- a/app/Rules/TransactionType/IsValidTransactionTypeList.php +++ b/app/Rules/TransactionType/IsValidTransactionTypeList.php @@ -47,7 +47,6 @@ class IsValidTransactionTypeList implements ValidationRule } $keys = array_keys($this->transactionTypes); foreach ($values as $entry) { - $entry = (string)$entry; if (!in_array($entry, $keys, true)) { $fail('validation.invalid_transaction_type_list')->translate(); } diff --git a/app/Rules/UniqueAccountNumber.php b/app/Rules/UniqueAccountNumber.php index 467c5e6c83..48d7310697 100644 --- a/app/Rules/UniqueAccountNumber.php +++ b/app/Rules/UniqueAccountNumber.php @@ -24,6 +24,7 @@ declare(strict_types=1); namespace FireflyIII\Rules; +use Illuminate\Support\Facades\Log; use Closure; use FireflyIII\Enums\AccountTypeEnum; use FireflyIII\Models\Account; @@ -55,7 +56,7 @@ class UniqueAccountNumber implements ValidationRule if ('asset' === $this->expectedType) { $this->expectedType = AccountTypeEnum::ASSET->value; } - app('log')->debug(sprintf('Expected type is "%s"', $this->expectedType)); + Log::debug(sprintf('Expected type is "%s"', $this->expectedType)); } /** @@ -87,9 +88,9 @@ class UniqueAccountNumber implements ValidationRule foreach ($maxCounts as $type => $max) { $count = $this->countHits($type, $value); - app('log')->debug(sprintf('Count for "%s" and account number "%s" is %d', $type, $value, $count)); + Log::debug(sprintf('Count for "%s" and account number "%s" is %d', $type, $value, $count)); if ($count > $max) { - app('log')->debug( + Log::debug( sprintf( 'account number "%s" is in use with %d account(s) of type "%s", which is too much for expected type "%s"', $value, @@ -104,7 +105,7 @@ class UniqueAccountNumber implements ValidationRule return; } } - app('log')->debug('Account number is valid.'); + Log::debug('Account number is valid.'); } private function getMaxOccurrences(): array diff --git a/app/Rules/UniqueIban.php b/app/Rules/UniqueIban.php index 3f83ab76bf..761d8eb641 100644 --- a/app/Rules/UniqueIban.php +++ b/app/Rules/UniqueIban.php @@ -24,6 +24,7 @@ declare(strict_types=1); namespace FireflyIII\Rules; +use Illuminate\Support\Facades\Log; use Closure; use FireflyIII\Enums\AccountTypeEnum; use FireflyIII\Models\Account; @@ -35,14 +36,13 @@ use Illuminate\Contracts\Validation\ValidationRule; */ class UniqueIban implements ValidationRule { - private array $expectedTypes; + private array $expectedTypes = []; /** * Create a new rule instance. */ public function __construct(private readonly ?Account $account, ?string $expectedType) { - $this->expectedTypes = []; if (null === $expectedType) { return; } @@ -104,9 +104,9 @@ class UniqueIban implements ValidationRule $value = Steam::filterSpaces($value); $count = $this->countHits($type, $value); - app('log')->debug(sprintf('Count for "%s" and IBAN "%s" is %d', $type, $value, $count)); + Log::debug(sprintf('Count for "%s" and IBAN "%s" is %d', $type, $value, $count)); if ($count > $max) { - app('log')->debug( + Log::debug( sprintf( 'IBAN "%s" is in use with %d account(s) of type "%s", which is too much for expected types "%s"', $value, diff --git a/app/Rules/ValidJournals.php b/app/Rules/ValidJournals.php index 221bef831d..463a3fe7f6 100644 --- a/app/Rules/ValidJournals.php +++ b/app/Rules/ValidJournals.php @@ -24,6 +24,7 @@ declare(strict_types=1); namespace FireflyIII\Rules; +use Illuminate\Support\Facades\Log; use Closure; use FireflyIII\Models\TransactionJournal; use Illuminate\Contracts\Validation\ValidationRule; @@ -38,7 +39,7 @@ class ValidJournals implements ValidationRule */ public function validate(string $attribute, mixed $value, Closure $fail): void { - app('log')->debug('In ValidJournals::passes'); + Log::debug('In ValidJournals::passes'); if (!is_array($value)) { return; } @@ -46,13 +47,13 @@ class ValidJournals implements ValidationRule foreach ($value as $journalId) { $count = TransactionJournal::where('id', $journalId)->where('user_id', $userId)->count(); if (0 === $count) { - app('log')->debug(sprintf('Count for transaction #%d and user #%d is zero! Return FALSE', $journalId, $userId)); + Log::debug(sprintf('Count for transaction #%d and user #%d is zero! Return FALSE', $journalId, $userId)); $fail('validation.invalid_selection')->translate(); return; } } - app('log')->debug('Return true!'); + Log::debug('Return true!'); } } diff --git a/app/Rules/ValidRecurrenceRepetitionValue.php b/app/Rules/ValidRecurrenceRepetitionValue.php index 9cd29b261b..ec770c6b9d 100644 --- a/app/Rules/ValidRecurrenceRepetitionValue.php +++ b/app/Rules/ValidRecurrenceRepetitionValue.php @@ -24,6 +24,7 @@ declare(strict_types=1); namespace FireflyIII\Rules; +use Illuminate\Support\Facades\Log; use Carbon\Carbon; use Closure; use Illuminate\Contracts\Validation\ValidationRule; @@ -105,7 +106,7 @@ class ValidRecurrenceRepetitionValue implements ValidationRule try { Carbon::createFromFormat('Y-m-d', $dateString); } catch (InvalidArgumentException $e) { - app('log')->debug(sprintf('Could not parse date %s: %s', $dateString, $e->getMessage())); + Log::debug(sprintf('Could not parse date %s: %s', $dateString, $e->getMessage())); return false; } diff --git a/app/Services/FireflyIIIOrg/Update/UpdateRequest.php b/app/Services/FireflyIIIOrg/Update/UpdateRequest.php index ad55aee903..a3433dc02c 100644 --- a/app/Services/FireflyIIIOrg/Update/UpdateRequest.php +++ b/app/Services/FireflyIIIOrg/Update/UpdateRequest.php @@ -149,7 +149,7 @@ class UpdateRequest implements UpdateRequestInterface $latest = substr($latest, 1); } if (str_starts_with($current, 'develop')) { - return $this->parseResultDevelop($current, $latest, $information); + return $this->parseResultDevelop($current, $latest); } $compare = version_compare($latest, $current); @@ -183,7 +183,7 @@ class UpdateRequest implements UpdateRequestInterface return $this->releasedNewVersion($current, $latest, $released); } - private function parseResultDevelop(string $current, string $latest, array $information): array + private function parseResultDevelop(string $current, string $latest): array { Log::debug(sprintf('User is running develop version "%s"', $current)); $compare = $this->compareDevelopVersions($current, $latest); diff --git a/app/Services/Internal/Destroy/AccountDestroyService.php b/app/Services/Internal/Destroy/AccountDestroyService.php index 2bd2f62c4e..5e6ec04144 100644 --- a/app/Services/Internal/Destroy/AccountDestroyService.php +++ b/app/Services/Internal/Destroy/AccountDestroyService.php @@ -24,6 +24,7 @@ declare(strict_types=1); namespace FireflyIII\Services\Internal\Destroy; +use Illuminate\Support\Facades\Log; use FireflyIII\Enums\TransactionTypeEnum; use FireflyIII\Models\Account; use FireflyIII\Models\PiggyBank; @@ -65,7 +66,7 @@ class AccountDestroyService private function destroyOpeningBalance(Account $account): void { - app('log')->debug(sprintf('Searching for opening balance for account #%d "%s"', $account->id, $account->name)); + Log::debug(sprintf('Searching for opening balance for account #%d "%s"', $account->id, $account->name)); $set = $account->transactions() ->leftJoin('transaction_journals', 'transaction_journals.id', '=', 'transactions.transaction_journal_id') ->leftJoin('transaction_types', 'transaction_types.id', '=', 'transaction_journals.transaction_type_id') @@ -74,7 +75,7 @@ class AccountDestroyService ; if ($set->count() > 0) { $journalId = $set->first()->transaction_journal_id; - app('log')->debug(sprintf('Found opening balance journal with ID #%d', $journalId)); + Log::debug(sprintf('Found opening balance journal with ID #%d', $journalId)); // get transactions with this journal (should be just one): $transactions = Transaction::where('transaction_journal_id', $journalId) @@ -84,9 +85,9 @@ class AccountDestroyService /** @var Transaction $transaction */ foreach ($transactions as $transaction) { - app('log')->debug(sprintf('Found transaction with ID #%d', $transaction->id)); + Log::debug(sprintf('Found transaction with ID #%d', $transaction->id)); $ibAccount = $transaction->account; - app('log')->debug(sprintf('Connected to account #%d "%s"', $ibAccount->id, $ibAccount->name)); + Log::debug(sprintf('Connected to account #%d "%s"', $ibAccount->id, $ibAccount->name)); $ibAccount->accountMeta()->delete(); $transaction->delete(); @@ -105,7 +106,7 @@ class AccountDestroyService public function moveTransactions(Account $account, Account $moveTo): void { - app('log')->debug(sprintf('Move from account #%d to #%d', $account->id, $moveTo->id)); + Log::debug(sprintf('Move from account #%d to #%d', $account->id, $moveTo->id)); DB::table('transactions')->where('account_id', $account->id)->update(['account_id' => $moveTo->id]); $collection = Transaction::groupBy('transaction_journal_id', 'account_id')->where('account_id', $moveTo->id)->get(['transaction_journal_id', 'account_id', DB::raw('count(*) as the_count')]); @@ -123,7 +124,7 @@ class AccountDestroyService $journalId = $row->transaction_journal_id; $journal = $user->transactionJournals()->find($journalId); if (null !== $journal) { - app('log')->debug(sprintf('Deleted journal #%d because it has the same source as destination.', $journal->id)); + Log::debug(sprintf('Deleted journal #%d because it has the same source as destination.', $journal->id)); $service->destroy($journal); } } diff --git a/app/Services/Internal/Destroy/JournalDestroyService.php b/app/Services/Internal/Destroy/JournalDestroyService.php index 77f63fa3ff..e75cf2a92b 100644 --- a/app/Services/Internal/Destroy/JournalDestroyService.php +++ b/app/Services/Internal/Destroy/JournalDestroyService.php @@ -24,6 +24,7 @@ declare(strict_types=1); namespace FireflyIII\Services\Internal\Destroy; +use Illuminate\Support\Facades\Log; use FireflyIII\Models\Attachment; use FireflyIII\Models\Transaction; use FireflyIII\Models\TransactionJournal; @@ -38,18 +39,18 @@ class JournalDestroyService { public function destroy(TransactionJournal $journal): void { - app('log')->debug(sprintf('Now in %s', __METHOD__)); + Log::debug(sprintf('Now in %s', __METHOD__)); /** @var Transaction $transaction */ foreach ($journal->transactions()->get() as $transaction) { - app('log')->debug(sprintf('Will now delete transaction #%d', $transaction->id)); + Log::debug(sprintf('Will now delete transaction #%d', $transaction->id)); $transaction->delete(); } // also delete journal_meta entries. /** @var TransactionJournalMeta $meta */ foreach ($journal->transactionJournalMeta()->get() as $meta) { - app('log')->debug(sprintf('Will now delete meta-entry #%d', $meta->id)); + Log::debug(sprintf('Will now delete meta-entry #%d', $meta->id)); $meta->delete(); } diff --git a/app/Services/Internal/Destroy/TransactionGroupDestroyService.php b/app/Services/Internal/Destroy/TransactionGroupDestroyService.php index 281a49e0c8..159fca52e1 100644 --- a/app/Services/Internal/Destroy/TransactionGroupDestroyService.php +++ b/app/Services/Internal/Destroy/TransactionGroupDestroyService.php @@ -24,6 +24,7 @@ declare(strict_types=1); namespace FireflyIII\Services\Internal\Destroy; +use Illuminate\Support\Facades\Log; use FireflyIII\Events\DestroyedTransactionGroup; use FireflyIII\Models\TransactionGroup; @@ -34,7 +35,7 @@ class TransactionGroupDestroyService { public function destroy(TransactionGroup $transactionGroup): void { - app('log')->debug(sprintf('Now in %s', __METHOD__)); + Log::debug(sprintf('Now in %s', __METHOD__)); /** @var JournalDestroyService $service */ $service = app(JournalDestroyService::class); diff --git a/app/Services/Internal/Support/AccountServiceTrait.php b/app/Services/Internal/Support/AccountServiceTrait.php index 15cb35f760..bce254bd60 100644 --- a/app/Services/Internal/Support/AccountServiceTrait.php +++ b/app/Services/Internal/Support/AccountServiceTrait.php @@ -24,6 +24,7 @@ declare(strict_types=1); namespace FireflyIII\Services\Internal\Support; +use Illuminate\Support\Facades\Log; use Carbon\Carbon; use Deprecated; use FireflyIII\Enums\AccountTypeEnum; @@ -58,7 +59,7 @@ trait AccountServiceTrait $rules = ['iban' => 'required|iban']; $validator = Validator::make($data, $rules); if ($validator->fails()) { - app('log')->info(sprintf('Detected invalid IBAN ("%s"). Return NULL instead.', $iban)); + Log::info(sprintf('Detected invalid IBAN ("%s"). Return NULL instead.', $iban)); return null; } @@ -78,14 +79,8 @@ trait AccountServiceTrait return false; } // if is set, but is empty: - if ( - (array_key_exists('opening_balance', $data) && '' === $data['opening_balance']) - || (array_key_exists('opening_balance_date', $data) && '' === $data['opening_balance_date']) - ) { - return true; - } - - return false; + return (array_key_exists('opening_balance', $data) && '' === $data['opening_balance']) + || (array_key_exists('opening_balance_date', $data) && '' === $data['opening_balance_date']); } /** @@ -180,11 +175,11 @@ trait AccountServiceTrait } if ('' !== $data['opening_balance'] && array_key_exists('opening_balance_date', $data) && '' !== $data['opening_balance_date'] && $data['opening_balance_date'] instanceof Carbon) { - app('log')->debug('Array has valid opening balance data.'); + Log::debug('Array has valid opening balance data.'); return true; } - app('log')->debug('Array does not have valid opening balance data.'); + Log::debug('Array does not have valid opening balance data.'); return false; } @@ -196,7 +191,7 @@ trait AccountServiceTrait #[Deprecated] protected function createOBGroup(Account $account, array $data): TransactionGroup { - app('log')->debug('Now going to create an OB group.'); + Log::debug('Now going to create an OB group.'); $language = app('preferences')->getForUser($account->user, 'language', 'en_US')->data; if (is_array($language)) { $language = 'en_US'; @@ -210,19 +205,19 @@ trait AccountServiceTrait // amount is positive. if (1 === bccomp((string) $amount, '0')) { - app('log')->debug(sprintf('Amount is %s, which is positive. Source is a new IB account, destination is #%d', $amount, $account->id)); + Log::debug(sprintf('Amount is %s, which is positive. Source is a new IB account, destination is #%d', $amount, $account->id)); $sourceName = trans('firefly.initial_balance_description', ['account' => $account->name], $language); $destId = $account->id; } // amount is not positive if (-1 === bccomp((string) $amount, '0')) { - app('log')->debug(sprintf('Amount is %s, which is negative. Destination is a new IB account, source is #%d', $amount, $account->id)); + Log::debug(sprintf('Amount is %s, which is negative. Destination is a new IB account, source is #%d', $amount, $account->id)); $destName = trans('firefly.initial_balance_account', ['account' => $account->name], $language); $sourceId = $account->id; } // amount is 0 if (0 === bccomp((string) $amount, '0')) { - app('log')->debug('Amount is zero, so will not make an OB group.'); + Log::debug('Amount is zero, so will not make an OB group.'); throw new FireflyException('Amount for new opening balance was unexpectedly 0.'); } @@ -268,7 +263,7 @@ trait AccountServiceTrait ], ], ]; - app('log')->debug('Going for submission in createOBGroup', $submission); + Log::debug('Going for submission in createOBGroup', $submission); /** @var TransactionGroupFactory $factory */ $factory = app(TransactionGroupFactory::class); @@ -277,8 +272,8 @@ trait AccountServiceTrait try { $group = $factory->create($submission); } catch (DuplicateTransactionException $e) { - app('log')->error($e->getMessage()); - app('log')->error($e->getTraceAsString()); + Log::error($e->getMessage()); + Log::error($e->getTraceAsString()); throw new FireflyException($e->getMessage(), 0, $e); } @@ -291,11 +286,11 @@ trait AccountServiceTrait */ protected function deleteCreditTransaction(Account $account): void { - app('log')->debug(sprintf('deleteCreditTransaction() for account #%d', $account->id)); + Log::debug(sprintf('deleteCreditTransaction() for account #%d', $account->id)); $creditGroup = $this->getCreditTransaction($account); if (null !== $creditGroup) { - app('log')->debug('Credit journal found, delete journal.'); + Log::debug('Credit journal found, delete journal.'); /** @var TransactionGroupDestroyService $service */ $service = app(TransactionGroupDestroyService::class); @@ -308,7 +303,7 @@ trait AccountServiceTrait */ protected function getCreditTransaction(Account $account): ?TransactionGroup { - app('log')->debug(sprintf('Now at %s', __METHOD__)); + Log::debug(sprintf('Now at %s', __METHOD__)); return $this->accountRepository->getCreditTransactionGroup($account); } @@ -318,12 +313,12 @@ trait AccountServiceTrait */ protected function deleteOBGroup(Account $account): void { - app('log')->debug(sprintf('deleteOB() for account #%d', $account->id)); + Log::debug(sprintf('deleteOB() for account #%d', $account->id)); $openingBalanceGroup = $this->getOBGroup($account); // opening balance data? update it! if (null !== $openingBalanceGroup) { - app('log')->debug('Opening balance journal found, delete journal.'); + Log::debug('Opening balance journal found, delete journal.'); /** @var TransactionGroupDestroyService $service */ $service = app(TransactionGroupDestroyService::class); @@ -365,10 +360,10 @@ trait AccountServiceTrait */ protected function updateCreditTransaction(Account $account, string $direction, string $openingBalance, Carbon $openingBalanceDate): TransactionGroup { - app('log')->debug(sprintf('Now in %s', __METHOD__)); + Log::debug(sprintf('Now in %s', __METHOD__)); if (0 === bccomp($openingBalance, '0')) { - app('log')->debug('Amount is zero, so will not update liability credit/debit group.'); + Log::debug('Amount is zero, so will not update liability credit/debit group.'); throw new FireflyException('Amount for update liability credit/debit was unexpectedly 0.'); } @@ -421,10 +416,10 @@ trait AccountServiceTrait */ protected function createCreditTransaction(Account $account, string $openingBalance, Carbon $openingBalanceDate): TransactionGroup { - app('log')->debug('Now going to create an createCreditTransaction.'); + Log::debug('Now going to create an createCreditTransaction.'); if (0 === bccomp($openingBalance, '0')) { - app('log')->debug('Amount is zero, so will not make an liability credit group.'); + Log::debug('Amount is zero, so will not make an liability credit group.'); throw new FireflyException('Amount for new liability credit was unexpectedly 0.'); } @@ -490,7 +485,7 @@ trait AccountServiceTrait ], ], ]; - app('log')->debug('Going for submission in createCreditTransaction', $submission); + Log::debug('Going for submission in createCreditTransaction', $submission); /** @var TransactionGroupFactory $factory */ $factory = app(TransactionGroupFactory::class); @@ -499,8 +494,8 @@ trait AccountServiceTrait try { $group = $factory->create($submission); } catch (DuplicateTransactionException $e) { - app('log')->error($e->getMessage()); - app('log')->error($e->getTraceAsString()); + Log::error($e->getMessage()); + Log::error($e->getTraceAsString()); throw new FireflyException($e->getMessage(), 0, $e); } @@ -562,13 +557,13 @@ trait AccountServiceTrait */ protected function updateOBGroupV2(Account $account, string $openingBalance, Carbon $openingBalanceDate): TransactionGroup { - app('log')->debug(sprintf('Now in %s', __METHOD__)); + Log::debug(sprintf('Now in %s', __METHOD__)); // create if not exists: $obGroup = $this->getOBGroup($account); if (null === $obGroup) { return $this->createOBGroupV2($account, $openingBalance, $openingBalanceDate); } - app('log')->debug('Update OB group'); + Log::debug('Update OB group'); // if exists, update: $currency = $this->accountRepository->getAccountCurrency($account); @@ -585,7 +580,7 @@ trait AccountServiceTrait // if amount is negative: if (1 === bccomp('0', $openingBalance)) { - app('log')->debug('Amount is negative.'); + Log::debug('Amount is negative.'); // account transaction loses money: $accountTransaction->amount = app('steam')->negative($openingBalance); $accountTransaction->transaction_currency_id = $currency->id; @@ -595,7 +590,7 @@ trait AccountServiceTrait $obTransaction->transaction_currency_id = $currency->id; } if (-1 === bccomp('0', $openingBalance)) { - app('log')->debug('Amount is positive.'); + Log::debug('Amount is positive.'); // account gains money: $accountTransaction->amount = app('steam')->positive($openingBalance); $accountTransaction->transaction_currency_id = $currency->id; @@ -618,7 +613,7 @@ trait AccountServiceTrait */ protected function createOBGroupV2(Account $account, string $openingBalance, Carbon $openingBalanceDate): TransactionGroup { - app('log')->debug('Now going to create an OB group.'); + Log::debug('Now going to create an OB group.'); $language = app('preferences')->getForUser($account->user, 'language', 'en_US')->data; if (is_array($language)) { $language = 'en_US'; @@ -631,19 +626,19 @@ trait AccountServiceTrait // amount is positive. if (1 === bccomp($openingBalance, '0')) { - app('log')->debug(sprintf('Amount is %s, which is positive. Source is a new IB account, destination is #%d', $openingBalance, $account->id)); + Log::debug(sprintf('Amount is %s, which is positive. Source is a new IB account, destination is #%d', $openingBalance, $account->id)); $sourceName = trans('firefly.initial_balance_description', ['account' => $account->name], $language); $destId = $account->id; } // amount is not positive if (-1 === bccomp($openingBalance, '0')) { - app('log')->debug(sprintf('Amount is %s, which is negative. Destination is a new IB account, source is #%d', $openingBalance, $account->id)); + Log::debug(sprintf('Amount is %s, which is negative. Destination is a new IB account, source is #%d', $openingBalance, $account->id)); $destName = trans('firefly.initial_balance_account', ['account' => $account->name], $language); $sourceId = $account->id; } // amount is 0 if (0 === bccomp($openingBalance, '0')) { - app('log')->debug('Amount is zero, so will not make an OB group.'); + Log::debug('Amount is zero, so will not make an OB group.'); throw new FireflyException('Amount for new opening balance was unexpectedly 0.'); } @@ -689,7 +684,7 @@ trait AccountServiceTrait ], ], ]; - app('log')->debug('Going for submission in createOBGroupV2', $submission); + Log::debug('Going for submission in createOBGroupV2', $submission); /** @var TransactionGroupFactory $factory */ $factory = app(TransactionGroupFactory::class); @@ -698,8 +693,8 @@ trait AccountServiceTrait try { $group = $factory->create($submission); } catch (DuplicateTransactionException $e) { - app('log')->error($e->getMessage()); - app('log')->error($e->getTraceAsString()); + Log::error($e->getMessage()); + Log::error($e->getTraceAsString()); throw new FireflyException($e->getMessage(), 0, $e); } diff --git a/app/Services/Internal/Support/BillServiceTrait.php b/app/Services/Internal/Support/BillServiceTrait.php index a9217f347d..79fa463b86 100644 --- a/app/Services/Internal/Support/BillServiceTrait.php +++ b/app/Services/Internal/Support/BillServiceTrait.php @@ -24,6 +24,7 @@ declare(strict_types=1); namespace FireflyIII\Services\Internal\Support; +use Illuminate\Support\Facades\Log; use FireflyIII\Models\Bill; use FireflyIII\Models\Note; use FireflyIII\Models\RuleAction; @@ -46,7 +47,7 @@ trait BillServiceTrait /** @var RuleAction $ruleAction */ foreach ($set as $ruleAction) { - app('log')->debug(sprintf('Updated rule action #%d to search for new bill name "%s"', $ruleAction->id, $newName)); + Log::debug(sprintf('Updated rule action #%d to search for new bill name "%s"', $ruleAction->id, $newName)); $ruleAction->action_value = $newName; $ruleAction->save(); } diff --git a/app/Services/Internal/Support/CreditRecalculateService.php b/app/Services/Internal/Support/CreditRecalculateService.php index 66b5fc359c..b1dc2406aa 100644 --- a/app/Services/Internal/Support/CreditRecalculateService.php +++ b/app/Services/Internal/Support/CreditRecalculateService.php @@ -40,20 +40,10 @@ use Illuminate\Support\Facades\Log; */ class CreditRecalculateService { - private ?Account $account; - private ?TransactionGroup $group; + private ?Account $account = null; + private ?TransactionGroup $group = null; private AccountRepositoryInterface $repository; - private array $work; - - /** - * CreditRecalculateService constructor. - */ - public function __construct() - { - $this->group = null; - $this->account = null; - $this->work = []; - } + private array $work = []; public function recalculate(): void { @@ -163,12 +153,10 @@ class CreditRecalculateService $this->repository->setUser($account->user); $direction = (string) $this->repository->getMetaValue($account, 'liability_direction'); $openingBalance = $this->repository->getOpeningBalance($account); - if ($openingBalance instanceof TransactionJournal) { - // Log::debug(sprintf('Found opening balance transaction journal #%d', $openingBalance->id)); - // if account direction is "debit" ("I owe this amount") the opening balance must always be AWAY from the account: - if ('debit' === $direction) { - $this->validateOpeningBalance($account, $openingBalance); - } + // Log::debug(sprintf('Found opening balance transaction journal #%d', $openingBalance->id)); + // if account direction is "debit" ("I owe this amount") the opening balance must always be AWAY from the account: + if ($openingBalance instanceof TransactionJournal && 'debit' === $direction) { + $this->validateOpeningBalance($account, $openingBalance); } $startOfDebt = $this->repository->getOpeningBalanceAmount($account, false) ?? '0'; $leftOfDebt = app('steam')->positive($startOfDebt); @@ -188,7 +176,7 @@ class CreditRecalculateService ->orderBy('transaction_journals.date', 'ASC') ->get(['transactions.*']) ; - $total = $transactions->count(); + $transactions->count(); // Log::debug(sprintf('Found %d transaction(s) to process.', $total)); /** @var Transaction $transaction */ diff --git a/app/Services/Internal/Support/JournalServiceTrait.php b/app/Services/Internal/Support/JournalServiceTrait.php index ec9a7dec3e..94f6c46e33 100644 --- a/app/Services/Internal/Support/JournalServiceTrait.php +++ b/app/Services/Internal/Support/JournalServiceTrait.php @@ -258,7 +258,7 @@ trait JournalServiceTrait /** @var string $type */ foreach ($types as $type) { - if (true === in_array($type, $list, true)) { + if (in_array($type, $list, true)) { $result = $type; break; diff --git a/app/Services/Internal/Support/RecurringTransactionTrait.php b/app/Services/Internal/Support/RecurringTransactionTrait.php index ebb7aad99f..25f0fb75db 100644 --- a/app/Services/Internal/Support/RecurringTransactionTrait.php +++ b/app/Services/Internal/Support/RecurringTransactionTrait.php @@ -94,9 +94,9 @@ trait RecurringTransactionTrait */ protected function createTransactions(Recurrence $recurrence, array $transactions): void { - app('log')->debug('Now in createTransactions()'); + Log::debug('Now in createTransactions()'); foreach ($transactions as $index => $array) { - app('log')->debug(sprintf('Now at transaction #%d', $index)); + Log::debug(sprintf('Now at transaction #%d', $index)); $sourceTypes = config(sprintf('firefly.expected_source_types.source.%s', $recurrence->transactionType->type)); $destTypes = config(sprintf('firefly.expected_source_types.destination.%s', $recurrence->transactionType->type)); $source = $this->findAccount($sourceTypes, $array['source_id'], null); @@ -110,7 +110,7 @@ trait RecurringTransactionTrait $currency = app('amount')->getPrimaryCurrencyByUserGroup($recurrence->user->userGroup); } - app('log')->debug( + Log::debug( sprintf('Will set the validator type to %s based on the type of the recurrence (#%d).', $recurrence->transactionType->type, $recurrence->id) ); @@ -204,7 +204,7 @@ trait RecurringTransactionTrait try { $result = $factory->findOrCreate($accountName, $expectedType); } catch (FireflyException $e) { - app('log')->error($e->getMessage()); + Log::error($e->getMessage()); } } } @@ -325,7 +325,7 @@ trait RecurringTransactionTrait protected function deleteTransactions(Recurrence $recurrence): void { - app('log')->debug('deleteTransactions()'); + Log::debug('deleteTransactions()'); /** @var RecurrenceTransaction $transaction */ foreach ($recurrence->recurrenceTransactions as $transaction) { diff --git a/app/Services/Internal/Support/TransactionTypeTrait.php b/app/Services/Internal/Support/TransactionTypeTrait.php index a9fe1308c8..e16bfd87f7 100644 --- a/app/Services/Internal/Support/TransactionTypeTrait.php +++ b/app/Services/Internal/Support/TransactionTypeTrait.php @@ -24,6 +24,7 @@ declare(strict_types=1); namespace FireflyIII\Services\Internal\Support; +use Illuminate\Support\Facades\Log; use FireflyIII\Exceptions\FireflyException; use FireflyIII\Factory\TransactionTypeFactory; use FireflyIII\Models\TransactionType; @@ -44,7 +45,7 @@ trait TransactionTypeTrait $factory = app(TransactionTypeFactory::class); $transactionType = $factory->find($type); if (null === $transactionType) { - app('log')->error(sprintf('Could not find transaction type for "%s"', $type)); + Log::error(sprintf('Could not find transaction type for "%s"', $type)); throw new FireflyException(sprintf('Could not find transaction type for "%s"', $type)); } diff --git a/app/Services/Internal/Update/AccountUpdateService.php b/app/Services/Internal/Update/AccountUpdateService.php index 9f38297e42..ea1b758124 100644 --- a/app/Services/Internal/Update/AccountUpdateService.php +++ b/app/Services/Internal/Update/AccountUpdateService.php @@ -24,6 +24,7 @@ declare(strict_types=1); namespace FireflyIII\Services\Internal\Update; +use Illuminate\Support\Facades\Log; use FireflyIII\Enums\AccountTypeEnum; use FireflyIII\Events\UpdatedAccount; use FireflyIII\Exceptions\FireflyException; @@ -68,7 +69,7 @@ class AccountUpdateService */ public function update(Account $account, array $data): Account { - app('log')->debug(sprintf('Now in %s', __METHOD__)); + Log::debug(sprintf('Now in %s', __METHOD__)); $this->accountRepository->setUser($account->user); $this->user = $account->user; $account = $this->updateAccount($account, $data); @@ -166,21 +167,21 @@ class AccountUpdateService { // skip if no order info if (!array_key_exists('order', $data) || $data['order'] === $account->order) { - app('log')->debug(sprintf('Account order will not be touched because its not set or already at %d.', $account->order)); + Log::debug(sprintf('Account order will not be touched because its not set or already at %d.', $account->order)); return $account; } // skip if not of orderable type. $type = $account->accountType->type; if (!in_array($type, [AccountTypeEnum::ASSET->value, AccountTypeEnum::MORTGAGE->value, AccountTypeEnum::LOAN->value, AccountTypeEnum::DEBT->value], true)) { - app('log')->debug('Will not change order of this account.'); + Log::debug('Will not change order of this account.'); return $account; } // get account type ID's because a join and an update is hard: $oldOrder = $account->order; $newOrder = $data['order']; - app('log')->debug(sprintf('Order is set to be updated from %s to %s', $oldOrder, $newOrder)); + Log::debug(sprintf('Order is set to be updated from %s to %s', $oldOrder, $newOrder)); $list = $this->getTypeIds([AccountTypeEnum::MORTGAGE->value, AccountTypeEnum::LOAN->value, AccountTypeEnum::DEBT->value]); if (AccountTypeEnum::ASSET->value === $type) { $list = $this->getTypeIds([AccountTypeEnum::ASSET->value]); @@ -193,7 +194,7 @@ class AccountUpdateService ->decrement('order') ; $account->order = $newOrder; - app('log')->debug(sprintf('Order of account #%d ("%s") is now %d', $account->id, $account->name, $newOrder)); + Log::debug(sprintf('Order of account #%d ("%s") is now %d', $account->id, $account->name, $newOrder)); $account->save(); return $account; @@ -205,7 +206,7 @@ class AccountUpdateService ->increment('order') ; $account->order = $newOrder; - app('log')->debug(sprintf('Order of account #%d ("%s") is now %d', $account->id, $account->name, $newOrder)); + Log::debug(sprintf('Order of account #%d ("%s") is now %d', $account->id, $account->name, $newOrder)); $account->save(); return $account; @@ -298,17 +299,17 @@ class AccountUpdateService if (!is_array($array)) { $array = [$array]; } - app('log')->debug('Old array is: ', $array); - app('log')->debug(sprintf('Must remove : %d', $account->id)); + Log::debug('Old array is: ', $array); + Log::debug(sprintf('Must remove : %d', $account->id)); $removeAccountId = $account->id; $new = []; foreach ($array as $value) { if ((int) $value !== $removeAccountId) { - app('log')->debug(sprintf('Will include: %d', $value)); + Log::debug(sprintf('Will include: %d', $value)); $new[] = (int) $value; } } - app('log')->debug('Final new array is', $new); + Log::debug('Final new array is', $new); app('preferences')->setForUser($account->user, 'frontpageAccounts', $new); } } diff --git a/app/Services/Internal/Update/BillUpdateService.php b/app/Services/Internal/Update/BillUpdateService.php index 20825af2f2..cdf2118cc8 100644 --- a/app/Services/Internal/Update/BillUpdateService.php +++ b/app/Services/Internal/Update/BillUpdateService.php @@ -24,6 +24,7 @@ declare(strict_types=1); namespace FireflyIII\Services\Internal\Update; +use Illuminate\Support\Facades\Log; use FireflyIII\Factory\TransactionCurrencyFactory; use FireflyIII\Models\Bill; use FireflyIII\Models\ObjectGroup; @@ -193,18 +194,18 @@ class BillUpdateService private function updateBillTriggers(Bill $bill, array $oldData, array $newData): void { - app('log')->debug(sprintf('Now in updateBillTriggers(%d, "%s")', $bill->id, $bill->name)); + Log::debug(sprintf('Now in updateBillTriggers(%d, "%s")', $bill->id, $bill->name)); /** @var BillRepositoryInterface $repository */ $repository = app(BillRepositoryInterface::class); $repository->setUser($bill->user); $rules = $repository->getRulesForBill($bill); if (0 === $rules->count()) { - app('log')->debug('Found no rules.'); + Log::debug('Found no rules.'); return; } - app('log')->debug(sprintf('Found %d rules', $rules->count())); + Log::debug(sprintf('Found %d rules', $rules->count())); $fields = [ 'name' => 'description_contains', 'amount_min' => 'amount_more', @@ -216,7 +217,7 @@ class BillUpdateService continue; } if ($oldData[$field] === $newData[$field]) { - app('log')->debug(sprintf('Field %s is unchanged ("%s"), continue.', $field, $oldData[$field])); + Log::debug(sprintf('Field %s is unchanged ("%s"), continue.', $field, $oldData[$field])); continue; } @@ -230,7 +231,7 @@ class BillUpdateService foreach ($rules as $rule) { $trigger = $this->getRuleTrigger($rule, $key); if ($trigger instanceof RuleTrigger && $trigger->trigger_value === $oldValue) { - app('log')->debug(sprintf('Updated rule trigger #%d from value "%s" to value "%s"', $trigger->id, $oldValue, $newValue)); + Log::debug(sprintf('Updated rule trigger #%d from value "%s" to value "%s"', $trigger->id, $oldValue, $newValue)); $trigger->trigger_value = $newValue; $trigger->save(); @@ -238,7 +239,7 @@ class BillUpdateService } if ($trigger instanceof RuleTrigger && $trigger->trigger_value !== $oldValue && in_array($key, ['amount_more', 'amount_less'], true) && 0 === bccomp($trigger->trigger_value, $oldValue)) { - app('log')->debug(sprintf('Updated rule trigger #%d from value "%s" to value "%s"', $trigger->id, $oldValue, $newValue)); + Log::debug(sprintf('Updated rule trigger #%d from value "%s" to value "%s"', $trigger->id, $oldValue, $newValue)); $trigger->trigger_value = $newValue; $trigger->save(); } diff --git a/app/Services/Internal/Update/CategoryUpdateService.php b/app/Services/Internal/Update/CategoryUpdateService.php index b04c06686e..1561dcd6ce 100644 --- a/app/Services/Internal/Update/CategoryUpdateService.php +++ b/app/Services/Internal/Update/CategoryUpdateService.php @@ -24,6 +24,7 @@ declare(strict_types=1); namespace FireflyIII\Services\Internal\Update; +use Illuminate\Support\Facades\Log; use Exception; use FireflyIII\Models\Category; use FireflyIII\Models\Note; @@ -54,7 +55,7 @@ class CategoryUpdateService /** * @param mixed $user */ - public function setUser($user): void + public function setUser(User $user): void { $this->user = $user; } @@ -88,13 +89,13 @@ class CategoryUpdateService ->where('rule_triggers.trigger_value', $oldName) ->get(['rule_triggers.*']) ; - app('log')->debug(sprintf('Found %d triggers to update.', $triggers->count())); + Log::debug(sprintf('Found %d triggers to update.', $triggers->count())); /** @var RuleTrigger $trigger */ foreach ($triggers as $trigger) { $trigger->trigger_value = $newName; $trigger->save(); - app('log')->debug(sprintf('Updated trigger %d: %s', $trigger->id, $trigger->trigger_value)); + Log::debug(sprintf('Updated trigger %d: %s', $trigger->id, $trigger->trigger_value)); } } @@ -107,13 +108,13 @@ class CategoryUpdateService ->where('rule_actions.action_value', $oldName) ->get(['rule_actions.*']) ; - app('log')->debug(sprintf('Found %d actions to update.', $actions->count())); + Log::debug(sprintf('Found %d actions to update.', $actions->count())); /** @var RuleAction $action */ foreach ($actions as $action) { $action->action_value = $newName; $action->save(); - app('log')->debug(sprintf('Updated action %d: %s', $action->id, $action->action_value)); + Log::debug(sprintf('Updated action %d: %s', $action->id, $action->action_value)); } } @@ -133,7 +134,7 @@ class CategoryUpdateService */ private function updateNotes(Category $category, array $data): void { - $note = array_key_exists('notes', $data) ? $data['notes'] : null; + $note = $data['notes'] ?? null; if (null === $note) { return; } diff --git a/app/Services/Internal/Update/GroupUpdateService.php b/app/Services/Internal/Update/GroupUpdateService.php index 384f304938..fcf280a403 100644 --- a/app/Services/Internal/Update/GroupUpdateService.php +++ b/app/Services/Internal/Update/GroupUpdateService.php @@ -105,16 +105,14 @@ class GroupUpdateService $result = array_diff($existing, $updated); Log::debug('Result of DIFF: ', $result); - if (count($result) > 0) { - /** @var string $deletedId */ - foreach ($result as $deletedId) { - /** @var TransactionJournal $journal */ - $journal = $transactionGroup->transactionJournals()->find((int) $deletedId); + /** @var string $deletedId */ + foreach ($result as $deletedId) { + /** @var TransactionJournal $journal */ + $journal = $transactionGroup->transactionJournals()->find((int) $deletedId); - /** @var JournalDestroyService $service */ - $service = app(JournalDestroyService::class); - $service->destroy($journal); - } + /** @var JournalDestroyService $service */ + $service = app(JournalDestroyService::class); + $service->destroy($journal); } app('preferences')->mark(); diff --git a/app/Services/Internal/Update/JournalUpdateService.php b/app/Services/Internal/Update/JournalUpdateService.php index f960b8e3e0..0831b22d29 100644 --- a/app/Services/Internal/Update/JournalUpdateService.php +++ b/app/Services/Internal/Update/JournalUpdateService.php @@ -63,14 +63,29 @@ class JournalUpdateService private CurrencyRepositoryInterface $currencyRepository; private TransactionGroupRepositoryInterface $transactionGroupRepository; private array $data; - private ?Account $destinationAccount; - private ?Transaction $destinationTransaction; - private array $metaDate; - private array $metaString; - private ?Account $sourceAccount; - private ?Transaction $sourceTransaction; - private ?TransactionGroup $transactionGroup; - private ?TransactionJournal $transactionJournal; + private ?Account $destinationAccount = null; + private ?Transaction $destinationTransaction = null; + private array $metaDate = ['interest_date', 'book_date', 'process_date', 'due_date', 'payment_date', + 'invoice_date', ]; + private array $metaString = [ + 'sepa_cc', + 'sepa_ct_op', + 'sepa_ct_id', + 'sepa_db', + 'sepa_country', + 'sepa_ep', + 'sepa_ci', + 'sepa_batch_id', + 'recurrence_id', + 'internal_reference', + 'bunq_payment_id', + 'external_id', + 'external_url', + ]; + private ?Account $sourceAccount = null; + private ?Transaction $sourceTransaction = null; + private ?TransactionGroup $transactionGroup = null; + private ?TransactionJournal $transactionJournal = null; private string $startCompareHash = ''; /** @@ -78,12 +93,6 @@ class JournalUpdateService */ public function __construct() { - $this->destinationAccount = null; - $this->destinationTransaction = null; - $this->sourceAccount = null; - $this->sourceTransaction = null; - $this->transactionGroup = null; - $this->transactionJournal = null; $this->billRepository = app(BillRepositoryInterface::class); $this->categoryRepository = app(CategoryRepositoryInterface::class); $this->budgetRepository = app(BudgetRepositoryInterface::class); @@ -91,23 +100,6 @@ class JournalUpdateService $this->accountRepository = app(AccountRepositoryInterface::class); $this->currencyRepository = app(CurrencyRepositoryInterface::class); $this->transactionGroupRepository = app(TransactionGroupRepositoryInterface::class); - $this->metaString = [ - 'sepa_cc', - 'sepa_ct_op', - 'sepa_ct_id', - 'sepa_db', - 'sepa_country', - 'sepa_ep', - 'sepa_ci', - 'sepa_batch_id', - 'recurrence_id', - 'internal_reference', - 'bunq_payment_id', - 'external_id', - 'external_url', - ]; - $this->metaDate = ['interest_date', 'book_date', 'process_date', 'due_date', 'payment_date', - 'invoice_date', ]; } public function setData(array $data): void @@ -141,7 +133,7 @@ class JournalUpdateService Log::debug(sprintf('Now in %s', __METHOD__)); Log::debug(sprintf('Now in JournalUpdateService for journal #%d.', $this->transactionJournal->id)); - $this->data['reconciled'] = array_key_exists('reconciled', $this->data) ? $this->data['reconciled'] : null; + $this->data['reconciled'] ??= null; // can we update account data using the new type? if ($this->hasValidAccounts()) { @@ -221,7 +213,7 @@ class JournalUpdateService private function hasFields(array $fields): bool { - return array_any($fields, fn ($field) => array_key_exists($field, $this->data)); + return array_any($fields, fn ($field): bool => array_key_exists($field, $this->data)); } private function getOriginalSourceAccount(): Account diff --git a/app/Services/Internal/Update/RecurrenceUpdateService.php b/app/Services/Internal/Update/RecurrenceUpdateService.php index 7cad86a146..83c3856e29 100644 --- a/app/Services/Internal/Update/RecurrenceUpdateService.php +++ b/app/Services/Internal/Update/RecurrenceUpdateService.php @@ -24,6 +24,7 @@ declare(strict_types=1); namespace FireflyIII\Services\Internal\Update; +use Illuminate\Support\Facades\Log; use FireflyIII\Exceptions\FireflyException; use FireflyIII\Factory\TransactionCurrencyFactory; use FireflyIII\Models\Note; @@ -94,7 +95,7 @@ class RecurrenceUpdateService // update all repetitions if (array_key_exists('repetitions', $data)) { - app('log')->debug('Will update repetitions array'); + Log::debug('Will update repetitions array'); // update each repetition or throw error yay $this->updateRepetitions($recurrence, $data['repetitions'] ?? []); } @@ -135,14 +136,14 @@ class RecurrenceUpdateService } // user added or removed repetitions, delete all and recreate: if ($originalCount !== count($repetitions)) { - app('log')->debug('Delete existing repetitions and create new ones.'); + Log::debug('Delete existing repetitions and create new ones.'); $this->deleteRepetitions($recurrence); $this->createRepetitions($recurrence, $repetitions); return; } // loop all and try to match them: - app('log')->debug('Loop and find'); + Log::debug('Loop and find'); foreach ($repetitions as $current) { $match = $this->matchRepetition($recurrence, $current); if (!$match instanceof RecurrenceRepetition) { @@ -167,7 +168,7 @@ class RecurrenceUpdateService { $originalCount = $recurrence->recurrenceRepetitions()->count(); if (1 === $originalCount) { - app('log')->debug('Return the first one'); + Log::debug('Return the first one'); /** @var null|RecurrenceRepetition */ return $recurrence->recurrenceRepetitions()->first(); @@ -198,12 +199,12 @@ class RecurrenceUpdateService */ private function updateTransactions(Recurrence $recurrence, array $transactions): void { - app('log')->debug('Now in updateTransactions()'); + Log::debug('Now in updateTransactions()'); $originalCount = $recurrence->recurrenceTransactions()->count(); - app('log')->debug(sprintf('Original count is %d', $originalCount)); + Log::debug(sprintf('Original count is %d', $originalCount)); if (0 === count($transactions)) { // won't drop transactions, rather avoid. - app('log')->warning('No transactions to update, too scared to continue!'); + Log::warning('No transactions to update, too scared to continue!'); return; } @@ -213,7 +214,7 @@ class RecurrenceUpdateService foreach ($originalTransactions as $i => $originalTransaction) { foreach ($transactions as $ii => $submittedTransaction) { if (array_key_exists('id', $submittedTransaction) && (int) $originalTransaction['id'] === (int) $submittedTransaction['id']) { - app('log')->debug(sprintf('Match original transaction #%d with an entry in the submitted array.', $originalTransaction['id'])); + Log::debug(sprintf('Match original transaction #%d with an entry in the submitted array.', $originalTransaction['id'])); $combinations[] = [ 'original' => $originalTransaction, 'submitted' => $submittedTransaction, @@ -225,7 +226,7 @@ class RecurrenceUpdateService // If one left of both we can match those as well and presto. if (1 === count($originalTransactions) && 1 === count($transactions)) { $first = array_shift($originalTransactions); - app('log')->debug(sprintf('One left of each, link them (ID is #%d)', $first['id'])); + Log::debug(sprintf('One left of each, link them (ID is #%d)', $first['id'])); $combinations[] = [ 'original' => $first, 'submitted' => array_shift($transactions), @@ -240,7 +241,7 @@ class RecurrenceUpdateService } // anything left in the original transactions array can be deleted. foreach ($originalTransactions as $original) { - app('log')->debug(sprintf('Original transaction #%d is unmatched, delete it!', $original['id'])); + Log::debug(sprintf('Original transaction #%d is unmatched, delete it!', $original['id'])); $this->deleteTransaction($recurrence, (int) $original['id']); } // anything left is new. @@ -261,7 +262,7 @@ class RecurrenceUpdateService /** @var RecurrenceTransaction $transaction */ $transaction = $recurrence->recurrenceTransactions()->find($original['id']); - app('log')->debug(sprintf('Now in updateCombination(#%d)', $original['id'])); + Log::debug(sprintf('Now in updateCombination(#%d)', $original['id'])); // loop all and try to match them: $currency = null; @@ -269,7 +270,7 @@ class RecurrenceUpdateService if (array_key_exists('currency_id', $submitted) || array_key_exists('currency_code', $submitted)) { $currency = $currencyFactory->find( array_key_exists('currency_id', $submitted) ? (int) $submitted['currency_id'] : null, - array_key_exists('currency_code', $submitted) ? $submitted['currency_code'] : null + $submitted['currency_code'] ?? null ); } if (null === $currency) { @@ -281,7 +282,7 @@ class RecurrenceUpdateService if (array_key_exists('foreign_currency_id', $submitted) || array_key_exists('foreign_currency_code', $submitted)) { $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 + $submitted['foreign_currency_code'] ?? null ); } if (null === $foreignCurrency) { @@ -317,13 +318,13 @@ class RecurrenceUpdateService // reset category if name is set but empty: // can be removed when v1 is retired. if (array_key_exists('category_name', $submitted) && '' === (string) $submitted['category_name']) { - app('log')->debug('Category name is submitted but is empty. Set category to be empty.'); + Log::debug('Category name is submitted but is empty. Set category to be empty.'); $submitted['category_name'] = null; $submitted['category_id'] = 0; } if (array_key_exists('category_id', $submitted)) { - app('log')->debug(sprintf('Category ID is submitted, set category to be %d.', (int) $submitted['category_id'])); + Log::debug(sprintf('Category ID is submitted, set category to be %d.', (int) $submitted['category_id'])); $this->setCategory($transaction, (int) $submitted['category_id']); } @@ -337,7 +338,7 @@ class RecurrenceUpdateService private function deleteTransaction(Recurrence $recurrence, int $transactionId): void { - app('log')->debug(sprintf('Will delete transaction #%d in recurrence #%d.', $transactionId, $recurrence->id)); + Log::debug(sprintf('Will delete transaction #%d in recurrence #%d.', $transactionId, $recurrence->id)); $recurrence->recurrenceTransactions()->where('id', $transactionId)->delete(); } } diff --git a/app/Services/Password/PwndVerifierV2.php b/app/Services/Password/PwndVerifierV2.php index 79067b27f3..874e5e80a5 100644 --- a/app/Services/Password/PwndVerifierV2.php +++ b/app/Services/Password/PwndVerifierV2.php @@ -23,6 +23,7 @@ declare(strict_types=1); namespace FireflyIII\Services\Password; +use Illuminate\Support\Facades\Log; use GuzzleHttp\Client; use GuzzleHttp\Exception\GuzzleException; use GuzzleHttp\Exception\RequestException; @@ -50,28 +51,28 @@ class PwndVerifierV2 implements Verifier 'timeout' => 3.1415, ]; - app('log')->debug(sprintf('hash prefix is %s', $prefix)); - app('log')->debug(sprintf('rest is %s', $rest)); + Log::debug(sprintf('hash prefix is %s', $prefix)); + Log::debug(sprintf('rest is %s', $rest)); try { $client = new Client(); $res = $client->request('GET', $url, $opt); } catch (GuzzleException|RequestException $e) { - app('log')->error(sprintf('Could not verify password security: %s', $e->getMessage())); + Log::error(sprintf('Could not verify password security: %s', $e->getMessage())); return true; } - app('log')->debug(sprintf('Status code returned is %d', $res->getStatusCode())); + Log::debug(sprintf('Status code returned is %d', $res->getStatusCode())); if (404 === $res->getStatusCode()) { return true; } $strpos = stripos($res->getBody()->getContents(), $rest); if (false === $strpos) { - app('log')->debug(sprintf('%s was not found in result body. Return true.', $rest)); + Log::debug(sprintf('%s was not found in result body. Return true.', $rest)); return true; } - app('log')->debug(sprintf('Found %s, return FALSE.', $rest)); + Log::debug(sprintf('Found %s, return FALSE.', $rest)); return false; } diff --git a/app/Support/Amount.php b/app/Support/Amount.php index f4bf1de35c..ad117d2a39 100644 --- a/app/Support/Amount.php +++ b/app/Support/Amount.php @@ -174,7 +174,7 @@ class Amount $fmt->setAttribute(NumberFormatter::MAX_FRACTION_DIGITS, $decimalPlaces); $result = (string)$fmt->format((float)$rounded); // intentional float - if (true === $coloured) { + if ($coloured) { if (1 === bccomp($rounded, '0')) { return sprintf('%s', $result); } @@ -355,7 +355,7 @@ class Amount private function getLocaleField(array $info, string $field): bool { - return (is_bool($info[$field]) && true === $info[$field]) + return (is_bool($info[$field]) && $info[$field]) || (is_int($info[$field]) && 1 === $info[$field]); } diff --git a/app/Support/Authentication/RemoteUserGuard.php b/app/Support/Authentication/RemoteUserGuard.php index f53ecaa4fc..a1a19ddb56 100644 --- a/app/Support/Authentication/RemoteUserGuard.php +++ b/app/Support/Authentication/RemoteUserGuard.php @@ -40,18 +40,16 @@ use Illuminate\Support\Facades\Log; class RemoteUserGuard implements Guard { protected Application $application; - protected ?User $user; + protected ?User $user = null; /** * Create a new authentication guard. */ public function __construct(protected UserProvider $provider, Application $app) { - /** @var null|Request $request */ - $request = $app->get('request'); + $app->get('request'); // Log::debug(sprintf('Created RemoteUserGuard for %s "%s"', $request?->getMethod(), $request?->getRequestUri())); $this->application = $app; - $this->user = null; } public function authenticate(): void diff --git a/app/Support/Authentication/RemoteUserProvider.php b/app/Support/Authentication/RemoteUserProvider.php index 629ea7d5be..1b42607fef 100644 --- a/app/Support/Authentication/RemoteUserProvider.php +++ b/app/Support/Authentication/RemoteUserProvider.php @@ -24,6 +24,7 @@ declare(strict_types=1); namespace FireflyIII\Support\Authentication; +use Illuminate\Support\Facades\Log; use FireflyIII\Console\Commands\Correction\CreatesGroupMemberships; use FireflyIII\Exceptions\FireflyException; use FireflyIII\Models\Role; @@ -41,7 +42,7 @@ class RemoteUserProvider implements UserProvider #[Override] public function rehashPasswordIfRequired(Authenticatable $user, array $credentials, bool $force = false): void { - app('log')->debug(sprintf('Now at %s', __METHOD__)); + Log::debug(sprintf('Now at %s', __METHOD__)); throw new FireflyException(sprintf('Did not implement %s', __METHOD__)); } @@ -53,7 +54,7 @@ class RemoteUserProvider implements UserProvider */ public function retrieveByCredentials(array $credentials): ?Authenticatable { - app('log')->debug(sprintf('Now at %s', __METHOD__)); + Log::debug(sprintf('Now at %s', __METHOD__)); throw new FireflyException(sprintf('Did not implement %s', __METHOD__)); } @@ -65,10 +66,10 @@ class RemoteUserProvider implements UserProvider */ public function retrieveById($identifier): User { - app('log')->debug(sprintf('Now at %s(%s)', __METHOD__, $identifier)); + Log::debug(sprintf('Now at %s(%s)', __METHOD__, $identifier)); $user = User::where('email', $identifier)->first(); if (null === $user) { - app('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( [ 'blocked' => false, @@ -86,7 +87,7 @@ class RemoteUserProvider implements UserProvider // make sure the user gets an administration as well. CreatesGroupMemberships::createGroupMembership($user); - app('log')->debug(sprintf('Going to return user #%d (%s)', $user->id, $user->email)); + Log::debug(sprintf('Going to return user #%d (%s)', $user->id, $user->email)); return $user; } @@ -101,7 +102,7 @@ class RemoteUserProvider implements UserProvider */ public function retrieveByToken($identifier, $token): ?Authenticatable { - app('log')->debug(sprintf('Now at %s', __METHOD__)); + Log::debug(sprintf('Now at %s', __METHOD__)); throw new FireflyException(sprintf('A) Did not implement %s', __METHOD__)); } @@ -115,7 +116,7 @@ class RemoteUserProvider implements UserProvider */ public function updateRememberToken(Authenticatable $user, $token): void { - app('log')->debug(sprintf('Now at %s', __METHOD__)); + Log::debug(sprintf('Now at %s', __METHOD__)); throw new FireflyException(sprintf('B) Did not implement %s', __METHOD__)); } @@ -127,7 +128,7 @@ class RemoteUserProvider implements UserProvider */ public function validateCredentials(Authenticatable $user, array $credentials): bool { - app('log')->debug(sprintf('Now at %s', __METHOD__)); + Log::debug(sprintf('Now at %s', __METHOD__)); throw new FireflyException(sprintf('C) Did not implement %s', __METHOD__)); } diff --git a/app/Support/Binder/AccountList.php b/app/Support/Binder/AccountList.php index 314a0c025f..e2d77aa9c3 100644 --- a/app/Support/Binder/AccountList.php +++ b/app/Support/Binder/AccountList.php @@ -23,6 +23,7 @@ declare(strict_types=1); namespace FireflyIII\Support\Binder; +use Illuminate\Support\Facades\Log; use FireflyIII\Enums\AccountTypeEnum; use Illuminate\Routing\Route; use Illuminate\Support\Collection; @@ -50,7 +51,7 @@ class AccountList implements BinderInterface ; } if ('allAssetAccounts' !== $value) { - $incoming = array_map('\intval', explode(',', $value)); + $incoming = array_map(\intval(...), explode(',', $value)); $list = array_merge(array_unique($incoming), [0]); /** @var Collection $collection */ @@ -66,7 +67,7 @@ class AccountList implements BinderInterface return $collection; } } - app('log')->error(sprintf('Trying to show account list (%s), but user is not logged in or list is empty.', $route->uri)); + Log::error(sprintf('Trying to show account list (%s), but user is not logged in or list is empty.', $route->uri)); throw new NotFoundHttpException(); } diff --git a/app/Support/Binder/BudgetList.php b/app/Support/Binder/BudgetList.php index 6526ebd38a..adaef6db1f 100644 --- a/app/Support/Binder/BudgetList.php +++ b/app/Support/Binder/BudgetList.php @@ -23,6 +23,7 @@ declare(strict_types=1); namespace FireflyIII\Support\Binder; +use Illuminate\Support\Facades\Log; use FireflyIII\Models\Budget; use Illuminate\Routing\Route; use Illuminate\Support\Collection; @@ -47,10 +48,10 @@ class BudgetList implements BinderInterface ; } - $list = array_unique(array_map('\intval', explode(',', $value))); + $list = array_unique(array_map(\intval(...), explode(',', $value))); if (0 === count($list)) { // @phpstan-ignore-line - app('log')->warning('Budget list count is zero, return 404.'); + Log::warning('Budget list count is zero, return 404.'); throw new NotFoundHttpException(); } @@ -71,7 +72,7 @@ class BudgetList implements BinderInterface return $collection; } } - app('log')->warning('BudgetList fallback to 404.'); + Log::warning('BudgetList fallback to 404.'); throw new NotFoundHttpException(); } diff --git a/app/Support/Binder/CLIToken.php b/app/Support/Binder/CLIToken.php index 09c54de3f0..d09da8c0b1 100644 --- a/app/Support/Binder/CLIToken.php +++ b/app/Support/Binder/CLIToken.php @@ -24,6 +24,7 @@ declare(strict_types=1); namespace FireflyIII\Support\Binder; +use Illuminate\Support\Facades\Log; use FireflyIII\Repositories\User\UserRepositoryInterface; use Illuminate\Routing\Route; use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; @@ -33,10 +34,7 @@ use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; */ class CLIToken implements BinderInterface { - /** - * @return mixed - */ - public static function routeBinder(string $value, Route $route) + public static function routeBinder(string $value, Route $route): string { /** @var UserRepositoryInterface $repository */ $repository = app(UserRepositoryInterface::class); @@ -50,12 +48,12 @@ class CLIToken implements BinderInterface foreach ($users as $user) { $accessToken = app('preferences')->getForUser($user, 'access_token'); if (null !== $accessToken && $accessToken->data === $value) { - app('log')->info(sprintf('Recognized user #%d (%s) from his access token.', $user->id, $user->email)); + Log::info(sprintf('Recognized user #%d (%s) from his access token.', $user->id, $user->email)); return $value; } } - app('log')->error(sprintf('Recognized no users by access token "%s"', $value)); + Log::error(sprintf('Recognized no users by access token "%s"', $value)); throw new NotFoundHttpException(); } diff --git a/app/Support/Binder/CategoryList.php b/app/Support/Binder/CategoryList.php index 1275481fa3..1cd4eb0e3a 100644 --- a/app/Support/Binder/CategoryList.php +++ b/app/Support/Binder/CategoryList.php @@ -46,7 +46,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)) { // @phpstan-ignore-line throw new NotFoundHttpException(); } diff --git a/app/Support/Binder/Date.php b/app/Support/Binder/Date.php index 99c0ce4c17..26b955716c 100644 --- a/app/Support/Binder/Date.php +++ b/app/Support/Binder/Date.php @@ -23,6 +23,7 @@ declare(strict_types=1); namespace FireflyIII\Support\Binder; +use Illuminate\Support\Facades\Log; use Carbon\Carbon; use Carbon\Exceptions\InvalidDateException; use Carbon\Exceptions\InvalidFormatException; @@ -61,7 +62,7 @@ class Date implements BinderInterface ]; if (array_key_exists($value, $magicWords)) { $return = $magicWords[$value]; - app('log')->debug(sprintf('User requests "%s", so will return "%s"', $value, $return)); + Log::debug(sprintf('User requests "%s", so will return "%s"', $value, $return)); return $return; } @@ -70,7 +71,7 @@ class Date implements BinderInterface $result = new Carbon($value); } catch (InvalidDateException|InvalidFormatException $e) { // @phpstan-ignore-line $message = sprintf('Could not parse date "%s" for user #%d: %s', $value, auth()->user()->id, $e->getMessage()); - app('log')->error($message); + Log::error($message); throw new NotFoundHttpException('Could not parse value', $e); } diff --git a/app/Support/Binder/JournalList.php b/app/Support/Binder/JournalList.php index 5eadcc587a..0ecdad1fff 100644 --- a/app/Support/Binder/JournalList.php +++ b/app/Support/Binder/JournalList.php @@ -60,7 +60,7 @@ class JournalList implements BinderInterface 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)) { // @phpstan-ignore-line throw new NotFoundHttpException(); } diff --git a/app/Support/Binder/TagList.php b/app/Support/Binder/TagList.php index d87c8c69b9..6894fa7c30 100644 --- a/app/Support/Binder/TagList.php +++ b/app/Support/Binder/TagList.php @@ -47,11 +47,11 @@ class TagList implements BinderInterface ->get() ; } - $list = array_unique(array_map('\strtolower', explode(',', $value))); - app('log')->debug('List of tags is', $list); + $list = array_unique(array_map(\strtolower(...), explode(',', $value))); + Log::debug('List of tags is', $list); if (0 === count($list)) { // @phpstan-ignore-line - app('log')->error('Tag list is empty.'); + Log::error('Tag list is empty.'); throw new NotFoundHttpException(); } @@ -62,7 +62,7 @@ class TagList implements BinderInterface $allTags = $repository->get(); $collection = $allTags->filter( - static function (Tag $tag) use ($list) { + static function (Tag $tag) use ($list): bool { if (in_array(strtolower($tag->tag), $list, true)) { Log::debug(sprintf('TagList: (string) found tag #%d ("%s") in list.', $tag->id, $tag->tag)); @@ -82,7 +82,7 @@ class TagList implements BinderInterface return $collection; } } - app('log')->error('TagList: user is not logged in.'); + Log::error('TagList: user is not logged in.'); throw new NotFoundHttpException(); } diff --git a/app/Support/Binder/TagOrId.php b/app/Support/Binder/TagOrId.php index e742fb674d..685119eff3 100644 --- a/app/Support/Binder/TagOrId.php +++ b/app/Support/Binder/TagOrId.php @@ -23,6 +23,7 @@ declare(strict_types=1); namespace FireflyIII\Support\Binder; +use Illuminate\Support\Facades\Log; use FireflyIII\Models\Tag; use FireflyIII\Repositories\Tag\TagRepositoryInterface; use Illuminate\Routing\Route; @@ -47,11 +48,11 @@ class TagOrId implements BinderInterface if (null !== $result) { return $result; } - app('log')->error('TagOrId: tag not found.'); + Log::error('TagOrId: tag not found.'); throw new NotFoundHttpException(); } - app('log')->error('TagOrId: user is not logged in.'); + Log::error('TagOrId: user is not logged in.'); throw new NotFoundHttpException(); } diff --git a/app/Support/Calendar/Calculator.php b/app/Support/Calendar/Calculator.php index ae5c1d7f72..5e08fd614d 100644 --- a/app/Support/Calendar/Calculator.php +++ b/app/Support/Calendar/Calculator.php @@ -37,12 +37,12 @@ class Calculator private static ?SplObjectStorage $intervalMap = null; // @phpstan-ignore-line private static array $intervals = []; - private static function containsInterval(Periodicity $periodicity): bool + private function containsInterval(Periodicity $periodicity): bool { - return self::loadIntervalMap()->contains($periodicity); + return $this->loadIntervalMap()->contains($periodicity); } - private static function loadIntervalMap(): SplObjectStorage + private function loadIntervalMap(): SplObjectStorage { if (self::$intervalMap instanceof SplObjectStorage) { return self::$intervalMap; @@ -59,7 +59,7 @@ class Calculator public function isAvailablePeriodicity(Periodicity $periodicity): bool { - return self::containsInterval($periodicity); + return $this->containsInterval($periodicity); } /** diff --git a/app/Support/Chart/Budget/FrontpageChartGenerator.php b/app/Support/Chart/Budget/FrontpageChartGenerator.php index b5af64fedd..1addb48b8b 100644 --- a/app/Support/Chart/Budget/FrontpageChartGenerator.php +++ b/app/Support/Chart/Budget/FrontpageChartGenerator.php @@ -45,7 +45,7 @@ class FrontpageChartGenerator private readonly BudgetLimitRepositoryInterface $blRepository; private readonly BudgetRepositoryInterface $budgetRepository; private Carbon $end; - private string $monthAndDayFormat; + private string $monthAndDayFormat = ''; private Carbon $start; /** @@ -56,7 +56,6 @@ class FrontpageChartGenerator $this->budgetRepository = app(BudgetRepositoryInterface::class); $this->blRepository = app(BudgetLimitRepositoryInterface::class); $this->opsRepository = app(OperationsRepositoryInterface::class); - $this->monthAndDayFormat = ''; } /** @@ -192,7 +191,7 @@ class FrontpageChartGenerator Log::debug(sprintf('Process spent row (%s)', $entry['currency_code'])); $data = $this->processRow($data, $budget, $limit, $entry); } - if (!($entry['currency_id'] === $limit->transaction_currency_id || $usePrimary)) { + if ($entry['currency_id'] !== $limit->transaction_currency_id && !$usePrimary) { Log::debug(sprintf('Skipping spent row (%s).', $entry['currency_code'])); } } diff --git a/app/Support/Chart/Category/FrontpageChartGenerator.php b/app/Support/Chart/Category/FrontpageChartGenerator.php index cc9b249235..45884c710f 100644 --- a/app/Support/Chart/Category/FrontpageChartGenerator.php +++ b/app/Support/Chart/Category/FrontpageChartGenerator.php @@ -45,7 +45,7 @@ class FrontpageChartGenerator public bool $convertToPrimary = false; public TransactionCurrency $primaryCurrency; private AccountRepositoryInterface $accountRepos; - private array $currencies; + private array $currencies = []; private NoCategoryRepositoryInterface $noCatRepos; private OperationsRepositoryInterface $opsRepos; private CategoryRepositoryInterface $repository; @@ -55,7 +55,6 @@ class FrontpageChartGenerator */ public function __construct(private Carbon $start, private Carbon $end) { - $this->currencies = []; $this->repository = app(CategoryRepositoryInterface::class); $this->accountRepos = app(AccountRepositoryInterface::class); $this->opsRepos = app(OperationsRepositoryInterface::class); diff --git a/app/Support/Chart/ChartData.php b/app/Support/Chart/ChartData.php index d35242c4d6..e3b086295b 100644 --- a/app/Support/Chart/ChartData.php +++ b/app/Support/Chart/ChartData.php @@ -31,12 +31,7 @@ use FireflyIII\Exceptions\FireflyException; */ class ChartData { - private array $series; - - public function __construct() - { - $this->series = []; - } + private array $series = []; /** * @throws FireflyException diff --git a/app/Support/Cronjobs/AbstractCronjob.php b/app/Support/Cronjobs/AbstractCronjob.php index fd287710ac..6211149b05 100644 --- a/app/Support/Cronjobs/AbstractCronjob.php +++ b/app/Support/Cronjobs/AbstractCronjob.php @@ -31,25 +31,20 @@ use Carbon\Carbon; */ abstract class AbstractCronjob { - public bool $jobErrored; - public bool $jobFired; - public bool $jobSucceeded; - public ?string $message; + public bool $jobErrored = false; + public bool $jobFired = false; + public bool $jobSucceeded = false; + public ?string $message = null; public int $timeBetweenRuns = 43200; protected Carbon $date; - protected bool $force; + protected bool $force = false; /** * AbstractCronjob constructor. */ public function __construct() { - $this->force = false; $this->date = today(config('app.timezone')); - $this->jobErrored = false; - $this->jobSucceeded = false; - $this->jobFired = false; - $this->message = null; } abstract public function fire(): void; diff --git a/app/Support/ExpandedForm.php b/app/Support/ExpandedForm.php index fc464fae22..26ca12798f 100644 --- a/app/Support/ExpandedForm.php +++ b/app/Support/ExpandedForm.php @@ -23,6 +23,7 @@ declare(strict_types=1); namespace FireflyIII\Support; +use Illuminate\Support\Facades\Log; use FireflyIII\Exceptions\FireflyException; use FireflyIII\Support\Form\FormSupport; use Illuminate\Database\Eloquent\Model; @@ -56,9 +57,9 @@ class ExpandedForm // $value = round((float)$value, 8); // } try { - $html = view('form.amount-no-currency', compact('classes', 'name', 'label', 'value', 'options'))->render(); + $html = view('form.amount-no-currency', ['classes' => $classes, 'name' => $name, 'label' => $label, 'value' => $value, 'options' => $options])->render(); } catch (Throwable $e) { - app('log')->error(sprintf('Could not render amountNoCurrency(): %s', $e->getMessage())); + Log::error(sprintf('Could not render amountNoCurrency(): %s', $e->getMessage())); $html = 'Could not render amountNoCurrency.'; throw new FireflyException($html, 0, $e); @@ -91,9 +92,9 @@ class ExpandedForm unset($options['placeholder'], $options['autocomplete'], $options['class']); try { - $html = view('form.checkbox', compact('classes', 'name', 'label', 'value', 'options'))->render(); + $html = view('form.checkbox', ['classes' => $classes, 'name' => $name, 'label' => $label, 'value' => $value, 'options' => $options])->render(); } catch (Throwable $e) { - app('log')->debug(sprintf('Could not render checkbox(): %s', $e->getMessage())); + Log::debug(sprintf('Could not render checkbox(): %s', $e->getMessage())); $html = 'Could not render checkbox.'; throw new FireflyException($html, 0, $e); @@ -116,9 +117,9 @@ class ExpandedForm unset($options['placeholder']); try { - $html = view('form.date', compact('classes', 'name', 'label', 'value', 'options'))->render(); + $html = view('form.date', ['classes' => $classes, 'name' => $name, 'label' => $label, 'value' => $value, 'options' => $options])->render(); } catch (Throwable $e) { - app('log')->debug(sprintf('Could not render date(): %s', $e->getMessage())); + Log::debug(sprintf('Could not render date(): %s', $e->getMessage())); $html = 'Could not render date.'; throw new FireflyException($html, 0, $e); @@ -138,9 +139,9 @@ class ExpandedForm $classes = $this->getHolderClasses($name); try { - $html = view('form.file', compact('classes', 'name', 'label', 'options'))->render(); + $html = view('form.file', ['classes' => $classes, 'name' => $name, 'label' => $label, 'options' => $options])->render(); } catch (Throwable $e) { - app('log')->debug(sprintf('Could not render file(): %s', $e->getMessage())); + Log::debug(sprintf('Could not render file(): %s', $e->getMessage())); $html = 'Could not render file.'; throw new FireflyException($html, 0, $e); @@ -164,9 +165,9 @@ class ExpandedForm $options['step'] ??= '1'; try { - $html = view('form.integer', compact('classes', 'name', 'label', 'value', 'options'))->render(); + $html = view('form.integer', ['classes' => $classes, 'name' => $name, 'label' => $label, 'value' => $value, 'options' => $options])->render(); } catch (Throwable $e) { - app('log')->debug(sprintf('Could not render integer(): %s', $e->getMessage())); + Log::debug(sprintf('Could not render integer(): %s', $e->getMessage())); $html = 'Could not render integer.'; throw new FireflyException($html, 0, $e); @@ -189,9 +190,9 @@ class ExpandedForm $value = $this->fillFieldValue($name, $value); try { - $html = view('form.location', compact('classes', 'name', 'label', 'value', 'options'))->render(); + $html = view('form.location', ['classes' => $classes, 'name' => $name, 'label' => $label, 'value' => $value, 'options' => $options])->render(); } catch (Throwable $e) { - app('log')->debug(sprintf('Could not render location(): %s', $e->getMessage())); + Log::debug(sprintf('Could not render location(): %s', $e->getMessage())); $html = 'Could not render location.'; throw new FireflyException($html, 0, $e); @@ -224,8 +225,6 @@ class ExpandedForm } /** - * @param null $value - * * @throws FireflyException */ public function objectGroup($value = null, ?array $options = null): string @@ -242,9 +241,9 @@ class ExpandedForm } try { - $html = view('form.object_group', compact('classes', 'name', 'label', 'value', 'options'))->render(); + $html = view('form.object_group', ['classes' => $classes, 'name' => $name, 'label' => $label, 'value' => $value, 'options' => $options])->render(); } catch (Throwable $e) { - app('log')->debug(sprintf('Could not render objectGroup(): %s', $e->getMessage())); + Log::debug(sprintf('Could not render objectGroup(): %s', $e->getMessage())); $html = 'Could not render objectGroup.'; throw new FireflyException($html, 0, $e); @@ -259,9 +258,9 @@ class ExpandedForm public function optionsList(string $type, string $name): string { try { - $html = view('form.options', compact('type', 'name'))->render(); + $html = view('form.options', ['type' => $type, 'name' => $name])->render(); } catch (Throwable $e) { - app('log')->debug(sprintf('Could not render select(): %s', $e->getMessage())); + Log::debug(sprintf('Could not render select(): %s', $e->getMessage())); $html = 'Could not render optionsList.'; throw new FireflyException($html, 0, $e); @@ -280,9 +279,9 @@ class ExpandedForm $classes = $this->getHolderClasses($name); try { - $html = view('form.password', compact('classes', 'name', 'label', 'options'))->render(); + $html = view('form.password', ['classes' => $classes, 'name' => $name, 'label' => $label, 'options' => $options])->render(); } catch (Throwable $e) { - app('log')->debug(sprintf('Could not render password(): %s', $e->getMessage())); + Log::debug(sprintf('Could not render password(): %s', $e->getMessage())); $html = 'Could not render password.'; throw new FireflyException($html, 0, $e); @@ -301,9 +300,9 @@ class ExpandedForm $classes = $this->getHolderClasses($name); try { - $html = view('form.password', compact('classes', 'value', 'name', 'label', 'options'))->render(); + $html = view('form.password', ['classes' => $classes, 'value' => $value, 'name' => $name, 'label' => $label, 'options' => $options])->render(); } catch (Throwable $e) { - app('log')->debug(sprintf('Could not render passwordWithValue(): %s', $e->getMessage())); + Log::debug(sprintf('Could not render passwordWithValue(): %s', $e->getMessage())); $html = 'Could not render passwordWithValue.'; throw new FireflyException($html, 0, $e); @@ -329,9 +328,9 @@ class ExpandedForm unset($options['placeholder']); try { - $html = view('form.percentage', compact('classes', 'name', 'label', 'value', 'options'))->render(); + $html = view('form.percentage', ['classes' => $classes, 'name' => $name, 'label' => $label, 'value' => $value, 'options' => $options])->render(); } catch (Throwable $e) { - app('log')->debug(sprintf('Could not render percentage(): %s', $e->getMessage())); + Log::debug(sprintf('Could not render percentage(): %s', $e->getMessage())); $html = 'Could not render percentage.'; throw new FireflyException($html, 0, $e); @@ -352,9 +351,9 @@ class ExpandedForm $classes = $this->getHolderClasses($name); try { - $html = view('form.static', compact('classes', 'name', 'label', 'value', 'options'))->render(); + $html = view('form.static', ['classes' => $classes, 'name' => $name, 'label' => $label, 'value' => $value, 'options' => $options])->render(); } catch (Throwable $e) { - app('log')->debug(sprintf('Could not render staticText(): %s', $e->getMessage())); + Log::debug(sprintf('Could not render staticText(): %s', $e->getMessage())); $html = 'Could not render staticText.'; throw new FireflyException($html, 0, $e); @@ -376,9 +375,9 @@ class ExpandedForm $value = $this->fillFieldValue($name, $value); try { - $html = view('form.text', compact('classes', 'name', 'label', 'value', 'options'))->render(); + $html = view('form.text', ['classes' => $classes, 'name' => $name, 'label' => $label, 'value' => $value, 'options' => $options])->render(); } catch (Throwable $e) { - app('log')->debug(sprintf('Could not render text(): %s', $e->getMessage())); + Log::debug(sprintf('Could not render text(): %s', $e->getMessage())); $html = 'Could not render text.'; throw new FireflyException($html, 0, $e); @@ -405,9 +404,9 @@ class ExpandedForm } try { - $html = view('form.textarea', compact('classes', 'name', 'label', 'value', 'options'))->render(); + $html = view('form.textarea', ['classes' => $classes, 'name' => $name, 'label' => $label, 'value' => $value, 'options' => $options])->render(); } catch (Throwable $e) { - app('log')->debug(sprintf('Could not render textarea(): %s', $e->getMessage())); + Log::debug(sprintf('Could not render textarea(): %s', $e->getMessage())); $html = 'Could not render textarea.'; throw new FireflyException($html, 0, $e); diff --git a/app/Support/Export/ExportDataGenerator.php b/app/Support/Export/ExportDataGenerator.php index c9f25e12a5..df551fa84b 100644 --- a/app/Support/Export/ExportDataGenerator.php +++ b/app/Support/Export/ExportDataGenerator.php @@ -76,15 +76,15 @@ class ExportDataGenerator private const string EXPORT_ERR = 'Could not export to string: %s'; private Collection $accounts; private Carbon $end; - private bool $exportAccounts; - private bool $exportBills; - private bool $exportBudgets; - private bool $exportCategories; - private bool $exportPiggies; - private bool $exportRecurring; - private bool $exportRules; - private bool $exportTags; - private bool $exportTransactions; + private bool $exportAccounts = false; + private bool $exportBills = false; + private bool $exportBudgets = false; + private bool $exportCategories = false; + private bool $exportPiggies = false; + private bool $exportRecurring = false; + private bool $exportRules = false; + private bool $exportTags = false; + private bool $exportTransactions = false; private Carbon $start; private User $user; private UserGroup $userGroup; // @phpstan-ignore-line @@ -95,15 +95,6 @@ class ExportDataGenerator $this->start = today(config('app.timezone')); $this->start->subYear(); $this->end = today(config('app.timezone')); - $this->exportTransactions = false; - $this->exportAccounts = false; - $this->exportBudgets = false; - $this->exportCategories = false; - $this->exportTags = false; - $this->exportRecurring = false; - $this->exportRules = false; - $this->exportBills = false; - $this->exportPiggies = false; } /** @@ -306,7 +297,7 @@ class ExportDataGenerator try { $string = $csv->toString(); } catch (Exception $e) { // intentional generic exception - app('log')->error($e->getMessage()); + Log::error($e->getMessage()); throw new FireflyException(sprintf(self::EXPORT_ERR, $e->getMessage()), 0, $e); } @@ -375,7 +366,7 @@ class ExportDataGenerator try { $string = $csv->toString(); } catch (Exception $e) { // intentional generic exception - app('log')->error($e->getMessage()); + Log::error($e->getMessage()); throw new FireflyException(sprintf(self::EXPORT_ERR, $e->getMessage()), 0, $e); } @@ -444,7 +435,7 @@ class ExportDataGenerator try { $string = $csv->toString(); } catch (Exception $e) { // intentional generic exception - app('log')->error($e->getMessage()); + Log::error($e->getMessage()); throw new FireflyException(sprintf(self::EXPORT_ERR, $e->getMessage()), 0, $e); } @@ -495,7 +486,7 @@ class ExportDataGenerator try { $string = $csv->toString(); } catch (Exception $e) { // intentional generic exception - app('log')->error($e->getMessage()); + Log::error($e->getMessage()); throw new FireflyException(sprintf(self::EXPORT_ERR, $e->getMessage()), 0, $e); } @@ -575,7 +566,7 @@ class ExportDataGenerator try { $string = $csv->toString(); } catch (Exception $e) { // intentional generic exception - app('log')->error($e->getMessage()); + Log::error($e->getMessage()); throw new FireflyException(sprintf(self::EXPORT_ERR, $e->getMessage()), 0, $e); } @@ -667,7 +658,7 @@ class ExportDataGenerator try { $string = $csv->toString(); } catch (Exception $e) { // intentional generic exception - app('log')->error($e->getMessage()); + Log::error($e->getMessage()); throw new FireflyException(sprintf(self::EXPORT_ERR, $e->getMessage()), 0, $e); } @@ -744,7 +735,7 @@ class ExportDataGenerator try { $string = $csv->toString(); } catch (Exception $e) { // intentional generic exception - app('log')->error($e->getMessage()); + Log::error($e->getMessage()); throw new FireflyException(sprintf(self::EXPORT_ERR, $e->getMessage()), 0, $e); } @@ -800,7 +791,7 @@ class ExportDataGenerator try { $string = $csv->toString(); } catch (Exception $e) { // intentional generic exception - app('log')->error($e->getMessage()); + Log::error($e->getMessage()); throw new FireflyException(sprintf(self::EXPORT_ERR, $e->getMessage()), 0, $e); } @@ -901,7 +892,7 @@ class ExportDataGenerator try { $string = $csv->toString(); } catch (Exception $e) { // intentional generic exception - app('log')->error($e->getMessage()); + Log::error($e->getMessage()); throw new FireflyException(sprintf(self::EXPORT_ERR, $e->getMessage()), 0, $e); } diff --git a/app/Support/Facades/Preferences.php b/app/Support/Facades/Preferences.php index 694e94ec96..998763b705 100644 --- a/app/Support/Facades/Preferences.php +++ b/app/Support/Facades/Preferences.php @@ -23,13 +23,14 @@ declare(strict_types=1); namespace FireflyIII\Support\Facades; +use Illuminate\Support\Facades\Log; use Illuminate\Support\Facades\Facade; class Preferences extends Facade { public function __construct() { - app('log')->warning('Hi there'); + Log::warning('Hi there'); } /** diff --git a/app/Support/FireflyConfig.php b/app/Support/FireflyConfig.php index 70d4650c6c..94f004ab5c 100644 --- a/app/Support/FireflyConfig.php +++ b/app/Support/FireflyConfig.php @@ -133,7 +133,7 @@ class FireflyConfig try { $config = Configuration::whereName($name)->whereNull('deleted_at')->first(); } catch (QueryException $e) { - app('log')->error($e->getMessage()); + Log::error($e->getMessage()); $item = new Configuration(); $item->name = $name; $item->data = $value; diff --git a/app/Support/Form/AccountForm.php b/app/Support/Form/AccountForm.php index 9b72eb285a..f512c1aa0c 100644 --- a/app/Support/Form/AccountForm.php +++ b/app/Support/Form/AccountForm.php @@ -24,6 +24,7 @@ declare(strict_types=1); namespace FireflyIII\Support\Form; +use Illuminate\Support\Facades\Log; use FireflyIII\Enums\AccountTypeEnum; use FireflyIII\Exceptions\FireflyException; use FireflyIII\Models\Account; @@ -93,9 +94,9 @@ class AccountForm unset($options['class']); try { - $html = view('form.assetAccountCheckList', compact('classes', 'selected', 'name', 'label', 'options', 'grouped'))->render(); + $html = view('form.assetAccountCheckList', ['classes' => $classes, 'selected' => $selected, 'name' => $name, 'label' => $label, 'options' => $options, 'grouped' => $grouped])->render(); } catch (Throwable $e) { - app('log')->debug(sprintf('Could not render assetAccountCheckList(): %s', $e->getMessage())); + Log::debug(sprintf('Could not render assetAccountCheckList(): %s', $e->getMessage())); $html = 'Could not render assetAccountCheckList.'; throw new FireflyException($html, 0, $e); diff --git a/app/Support/Form/CurrencyForm.php b/app/Support/Form/CurrencyForm.php index 5bf2e0ba77..c8005211cf 100644 --- a/app/Support/Form/CurrencyForm.php +++ b/app/Support/Form/CurrencyForm.php @@ -24,6 +24,7 @@ declare(strict_types=1); namespace FireflyIII\Support\Form; +use Illuminate\Support\Facades\Log; use FireflyIII\Exceptions\FireflyException; use FireflyIII\Models\TransactionCurrency; use FireflyIII\Repositories\Currency\CurrencyRepositoryInterface; @@ -135,13 +136,13 @@ class CurrencyForm $key = 'amount_currency_id_'.$name; $sentCurrencyId = array_key_exists($key, $preFilled) ? (int)$preFilled[$key] : $primaryCurrency->id; - app('log')->debug(sprintf('Sent currency ID is %d', $sentCurrencyId)); + Log::debug(sprintf('Sent currency ID is %d', $sentCurrencyId)); // find this currency in set of currencies: foreach ($currencies as $currency) { if ($currency->id === $sentCurrencyId) { $primaryCurrency = $currency; - app('log')->debug(sprintf('default currency is now %s', $primaryCurrency->code)); + Log::debug(sprintf('default currency is now %s', $primaryCurrency->code)); break; } @@ -153,9 +154,9 @@ class CurrencyForm } try { - $html = view('form.'.$view, compact('primaryCurrency', 'currencies', 'classes', 'name', 'label', 'value', 'options'))->render(); + $html = view('form.'.$view, ['primaryCurrency' => $primaryCurrency, 'currencies' => $currencies, 'classes' => $classes, 'name' => $name, 'label' => $label, 'value' => $value, 'options' => $options])->render(); } catch (Throwable $e) { - app('log')->debug(sprintf('Could not render currencyField(): %s', $e->getMessage())); + Log::debug(sprintf('Could not render currencyField(): %s', $e->getMessage())); $html = 'Could not render currencyField.'; throw new FireflyException($html, 0, $e); @@ -187,13 +188,13 @@ class CurrencyForm $key = 'amount_currency_id_'.$name; $sentCurrencyId = array_key_exists($key, $preFilled) ? (int)$preFilled[$key] : $primaryCurrency->id; - app('log')->debug(sprintf('Sent currency ID is %d', $sentCurrencyId)); + Log::debug(sprintf('Sent currency ID is %d', $sentCurrencyId)); // find this currency in set of currencies: foreach ($currencies as $currency) { if ($currency->id === $sentCurrencyId) { $primaryCurrency = $currency; - app('log')->debug(sprintf('default currency is now %s', $primaryCurrency->code)); + Log::debug(sprintf('default currency is now %s', $primaryCurrency->code)); break; } @@ -205,9 +206,9 @@ class CurrencyForm } try { - $html = view('form.'.$view, compact('primaryCurrency', 'currencies', 'classes', 'name', 'label', 'value', 'options'))->render(); + $html = view('form.'.$view, ['primaryCurrency' => $primaryCurrency, 'currencies' => $currencies, 'classes' => $classes, 'name' => $name, 'label' => $label, 'value' => $value, 'options' => $options])->render(); } catch (Throwable $e) { - app('log')->debug(sprintf('Could not render currencyField(): %s', $e->getMessage())); + Log::debug(sprintf('Could not render currencyField(): %s', $e->getMessage())); $html = 'Could not render currencyField.'; throw new FireflyException($html, 0, $e); diff --git a/app/Support/Form/FormSupport.php b/app/Support/Form/FormSupport.php index 22a580c295..ff1a1f0a7b 100644 --- a/app/Support/Form/FormSupport.php +++ b/app/Support/Form/FormSupport.php @@ -24,6 +24,7 @@ declare(strict_types=1); namespace FireflyIII\Support\Form; +use Illuminate\Support\Facades\Log; use Carbon\Carbon; use FireflyIII\Repositories\Account\AccountRepositoryInterface; use Illuminate\Support\MessageBag; @@ -45,9 +46,9 @@ trait FormSupport unset($options['autocomplete'], $options['placeholder']); try { - $html = view('form.multi-select', compact('classes', 'name', 'label', 'selected', 'options', 'list'))->render(); + $html = view('form.multi-select', ['classes' => $classes, 'name' => $name, 'label' => $label, 'selected' => $selected, 'options' => $options, 'list' => $list])->render(); } catch (Throwable $e) { - app('log')->debug(sprintf('Could not render multi-select(): %s', $e->getMessage())); + Log::debug(sprintf('Could not render multi-select(): %s', $e->getMessage())); $html = 'Could not render multi-select.'; } @@ -67,9 +68,9 @@ trait FormSupport unset($options['autocomplete'], $options['placeholder']); try { - $html = view('form.select', compact('classes', 'name', 'label', 'selected', 'options', 'list'))->render(); + $html = view('form.select', ['classes' => $classes, 'name' => $name, 'label' => $label, 'selected' => $selected, 'options' => $options, 'list' => $list])->render(); } catch (Throwable $e) { - app('log')->debug(sprintf('Could not render select(): %s', $e->getMessage())); + Log::debug(sprintf('Could not render select(): %s', $e->getMessage())); $html = 'Could not render select.'; } diff --git a/app/Support/Form/RuleForm.php b/app/Support/Form/RuleForm.php index 9566f0301f..066fdbb5f8 100644 --- a/app/Support/Form/RuleForm.php +++ b/app/Support/Form/RuleForm.php @@ -52,9 +52,6 @@ class RuleForm return $this->select($name, $array, $value, $options); } - /** - * @param null $value - */ public function ruleGroupListWithEmpty(string $name, $value = null, ?array $options = null): string { $options ??= []; diff --git a/app/Support/Http/Api/AccountBalanceGrouped.php b/app/Support/Http/Api/AccountBalanceGrouped.php index e335da23eb..0475d7753f 100644 --- a/app/Support/Http/Api/AccountBalanceGrouped.php +++ b/app/Support/Http/Api/AccountBalanceGrouped.php @@ -39,7 +39,7 @@ use Illuminate\Support\Facades\Log; */ class AccountBalanceGrouped { - private array $accountIds; + private array $accountIds = []; private string $carbonFormat; private readonly ExchangeRateConverter $converter; private array $currencies = []; @@ -52,7 +52,6 @@ class AccountBalanceGrouped public function __construct() { - $this->accountIds = []; $this->converter = app(ExchangeRateConverter::class); } @@ -258,7 +257,7 @@ class AccountBalanceGrouped try { $rate = $this->converter->getCurrencyRate($currency, $this->primary, $date); } catch (FireflyException $e) { - app('log')->error($e->getMessage()); + Log::error($e->getMessage()); $rate = '1'; } diff --git a/app/Support/Http/Api/ExchangeRateConverter.php b/app/Support/Http/Api/ExchangeRateConverter.php index 6f6728e825..deb9457f58 100644 --- a/app/Support/Http/Api/ExchangeRateConverter.php +++ b/app/Support/Http/Api/ExchangeRateConverter.php @@ -71,7 +71,7 @@ class ExchangeRateConverter public function enabled(): bool { - return false !== config('cer.enabled') || true === $this->ignoreSettings; + return false !== config('cer.enabled') || $this->ignoreSettings; } /** @@ -147,24 +147,24 @@ class ExchangeRateConverter $rate = $this->getFromDB($currency->id, $euroId, $date->format('Y-m-d')); if (null !== $rate) { - // app('log')->debug(sprintf('Rate for %s to EUR is %s.', $currency->code, $rate)); + // \Illuminate\Support\Facades\Log::debug(sprintf('Rate for %s to EUR is %s.', $currency->code, $rate)); return $rate; } $rate = $this->getFromDB($euroId, $currency->id, $date->format('Y-m-d')); if (null !== $rate) { return bcdiv('1', $rate); - // app('log')->debug(sprintf('Inverted rate for %s to EUR is %s.', $currency->code, $rate)); + // \Illuminate\Support\Facades\Log::debug(sprintf('Inverted rate for %s to EUR is %s.', $currency->code, $rate)); // return $rate; } // grab backup values from config file: $backup = config(sprintf('cer.rates.%s', $currency->code)); if (null !== $backup) { return bcdiv('1', (string)$backup); - // app('log')->debug(sprintf('Backup rate for %s to EUR is %s.', $currency->code, $backup)); + // \Illuminate\Support\Facades\Log::debug(sprintf('Backup rate for %s to EUR is %s.', $currency->code, $backup)); // return $backup; } - // app('log')->debug(sprintf('No rate for %s to EUR.', $currency->code)); + // \Illuminate\Support\Facades\Log::debug(sprintf('No rate for %s to EUR.', $currency->code)); return '0'; } @@ -209,16 +209,16 @@ class ExchangeRateConverter $rate = (string)$result?->rate; if ('' === $rate) { - app('log')->debug(sprintf('ExchangeRateConverter: Found no rate for #%d->#%d (%s) in the DB.', $from, $to, $date)); + Log::debug(sprintf('ExchangeRateConverter: Found no rate for #%d->#%d (%s) in the DB.', $from, $to, $date)); return null; } if (0 === bccomp('0', $rate)) { - app('log')->debug(sprintf('ExchangeRateConverter: Found rate for #%d->#%d (%s) in the DB, but it\'s zero.', $from, $to, $date)); + Log::debug(sprintf('ExchangeRateConverter: Found rate for #%d->#%d (%s) in the DB, but it\'s zero.', $from, $to, $date)); return null; } - app('log')->debug(sprintf('ExchangeRateConverter: Found rate for #%d->#%d (%s) in the DB: %s.', $from, $to, $date, $rate)); + Log::debug(sprintf('ExchangeRateConverter: Found rate for #%d->#%d (%s) in the DB: %s.', $from, $to, $date, $rate)); $cache->store($rate); // if the rate has not been cached during this particular run, save it diff --git a/app/Support/Http/Api/SummaryBalanceGrouped.php b/app/Support/Http/Api/SummaryBalanceGrouped.php index e4fdb41b68..f830ed83e5 100644 --- a/app/Support/Http/Api/SummaryBalanceGrouped.php +++ b/app/Support/Http/Api/SummaryBalanceGrouped.php @@ -33,15 +33,13 @@ class SummaryBalanceGrouped { private const string SUM = 'sum'; private array $amounts = []; - private array $currencies; + private array $currencies = []; private readonly CurrencyRepositoryInterface $currencyRepository; private TransactionCurrency $default; - private array $keys; + private array $keys = [self::SUM]; public function __construct() { - $this->keys = [self::SUM]; - $this->currencies = []; $this->currencyRepository = app(CurrencyRepositoryInterface::class); } diff --git a/app/Support/Http/Controllers/GetConfigurationData.php b/app/Support/Http/Controllers/GetConfigurationData.php index 097204bd83..d1f28200e0 100644 --- a/app/Support/Http/Controllers/GetConfigurationData.php +++ b/app/Support/Http/Controllers/GetConfigurationData.php @@ -70,7 +70,7 @@ trait GetConfigurationData $steps[] = $currentStep; } } - app('log')->debug(sprintf('Total basic steps for %s is %d', $routeKey, count($steps))); + Log::debug(sprintf('Total basic steps for %s is %d', $routeKey, count($steps))); return $steps; } @@ -199,7 +199,7 @@ trait GetConfigurationData } } } - app('log')->debug(sprintf('Total specific steps for route "%s" and page "%s" (routeKey is "%s") is %d', $route, $specificPage, $routeKey, count($steps))); + Log::debug(sprintf('Total specific steps for route "%s" and page "%s" (routeKey is "%s") is %d', $route, $specificPage, $routeKey, count($steps))); return $steps; } @@ -209,7 +209,7 @@ trait GetConfigurationData $config = FireflyConfig::get('last_rt_job', 0); $lastTime = (int)$config?->data; $now = Carbon::now()->getTimestamp(); - app('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) { request()->session()->flash('info', trans('firefly.recurring_never_cron')); diff --git a/app/Support/Http/Controllers/ModelInformation.php b/app/Support/Http/Controllers/ModelInformation.php index 093120cf7a..523c225d26 100644 --- a/app/Support/Http/Controllers/ModelInformation.php +++ b/app/Support/Http/Controllers/ModelInformation.php @@ -24,6 +24,7 @@ declare(strict_types=1); namespace FireflyIII\Support\Http\Controllers; +use Illuminate\Support\Facades\Log; use FireflyIII\Enums\AccountTypeEnum; use FireflyIII\Exceptions\FireflyException; use FireflyIII\Models\AccountType; @@ -57,8 +58,8 @@ trait ModelInformation ] )->render(); } catch (Throwable $e) { - app('log')->error(sprintf('Throwable was thrown in getActionsForBill(): %s', $e->getMessage())); - app('log')->error($e->getTraceAsString()); + Log::error(sprintf('Throwable was thrown in getActionsForBill(): %s', $e->getMessage())); + Log::error($e->getTraceAsString()); $result = 'Could not render view. See log files.'; throw new FireflyException($result, 0, $e); @@ -144,8 +145,8 @@ trait ModelInformation ] )->render(); } catch (Throwable $e) { - app('log')->debug(sprintf('Throwable was thrown in getTriggersForBill(): %s', $e->getMessage())); - app('log')->debug($e->getTraceAsString()); + Log::debug(sprintf('Throwable was thrown in getTriggersForBill(): %s', $e->getMessage())); + Log::debug($e->getTraceAsString()); throw new FireflyException(sprintf('Could not render trigger: %s', $e->getMessage()), 0, $e); } @@ -260,8 +261,8 @@ trait ModelInformation ]; $string = view('rules.partials.trigger', $renderInfo)->render(); } catch (Throwable $e) { - app('log')->debug(sprintf('Throwable was thrown in getTriggersForJournal(): %s', $e->getMessage())); - app('log')->debug($e->getTraceAsString()); + Log::debug(sprintf('Throwable was thrown in getTriggersForJournal(): %s', $e->getMessage())); + Log::debug($e->getTraceAsString()); throw new FireflyException(sprintf('Could not render trigger: %s', $e->getMessage()), 0, $e); } diff --git a/app/Support/Http/Controllers/PeriodOverview.php b/app/Support/Http/Controllers/PeriodOverview.php index 6fec7eadda..897f8da732 100644 --- a/app/Support/Http/Controllers/PeriodOverview.php +++ b/app/Support/Http/Controllers/PeriodOverview.php @@ -331,7 +331,7 @@ trait PeriodOverview } return $this->statistics->filter( - fn (PeriodStatistic $statistic) => $statistic->start->eq($start) && $statistic->end->eq($end) && $statistic->type === $type + fn (PeriodStatistic $statistic): bool => $statistic->start->eq($start) && $statistic->end->eq($end) && $statistic->type === $type ); } @@ -344,7 +344,7 @@ trait PeriodOverview } return $this->statistics->filter( - fn (PeriodStatistic $statistic) => $statistic->start->eq($start) && $statistic->end->eq($end) && str_starts_with($statistic->type, $prefix) + fn (PeriodStatistic $statistic): bool => $statistic->start->eq($start) && $statistic->end->eq($end) && str_starts_with($statistic->type, $prefix) ); } @@ -571,10 +571,6 @@ trait PeriodOverview { $result = []; - /** - * @var int $index - * @var array $item - */ foreach ($this->transactions as $item) { $date = Carbon::parse($item['date']); $fits = $item['type'] === $type->value && $date >= $start && $date <= $end; @@ -595,10 +591,6 @@ trait PeriodOverview { $result = []; - /** - * @var int $index - * @var array $item - */ foreach ($this->transactions as $item) { $date = Carbon::parse($item['date']); if ($date >= $start && $date <= $end) { diff --git a/app/Support/Http/Controllers/RenderPartialViews.php b/app/Support/Http/Controllers/RenderPartialViews.php index f7d5df7cb8..962e9d5155 100644 --- a/app/Support/Http/Controllers/RenderPartialViews.php +++ b/app/Support/Http/Controllers/RenderPartialViews.php @@ -24,6 +24,7 @@ declare(strict_types=1); namespace FireflyIII\Support\Http\Controllers; +use Illuminate\Support\Facades\Log; use FireflyIII\Enums\AccountTypeEnum; use FireflyIII\Exceptions\FireflyException; use FireflyIII\Helpers\Report\PopupReportInterface; @@ -68,9 +69,9 @@ trait RenderPartialViews $journals = $popupHelper->balanceForBudget($budget, $account, $attributes); try { - $view = view('popup.report.balance-amount', compact('journals', 'budget', 'account'))->render(); + $view = view('popup.report.balance-amount', ['journals' => $journals, 'budget' => $budget, 'account' => $account])->render(); } catch (Throwable $e) { - app('log')->error(sprintf('Could not render: %s', $e->getMessage())); + Log::error(sprintf('Could not render: %s', $e->getMessage())); $view = 'Firefly III could not render the view. Please see the log files.'; throw new FireflyException($view, 0, $e); @@ -91,9 +92,9 @@ trait RenderPartialViews $budgets = $repository->getActiveBudgets(); try { - $result = view('reports.options.budget', compact('budgets'))->render(); + $result = view('reports.options.budget', ['budgets' => $budgets])->render(); } catch (Throwable $e) { - app('log')->error(sprintf('Cannot render reports.options.tag: %s', $e->getMessage())); + Log::error(sprintf('Cannot render reports.options.tag: %s', $e->getMessage())); $result = 'Could not render view.'; throw new FireflyException($result, 0, $e); @@ -123,9 +124,9 @@ trait RenderPartialViews $journals = $popupHelper->byBudget($budget, $attributes); try { - $view = view('popup.report.budget-spent-amount', compact('journals', 'budget'))->render(); + $view = view('popup.report.budget-spent-amount', ['journals' => $journals, 'budget' => $budget])->render(); } catch (Throwable $e) { - app('log')->error(sprintf('Could not render: %s', $e->getMessage())); + Log::error(sprintf('Could not render: %s', $e->getMessage())); $view = 'Firefly III could not render the view. Please see the log files.'; throw new FireflyException($view, 0, $e); @@ -150,9 +151,9 @@ trait RenderPartialViews $journals = $popupHelper->byCategory($category, $attributes); try { - $view = view('popup.report.category-entry', compact('journals', 'category'))->render(); + $view = view('popup.report.category-entry', ['journals' => $journals, 'category' => $category])->render(); } catch (Throwable $e) { - app('log')->error(sprintf('Could not render: %s', $e->getMessage())); + Log::error(sprintf('Could not render: %s', $e->getMessage())); $view = 'Firefly III could not render the view. Please see the log files.'; throw new FireflyException($view, 0, $e); @@ -173,9 +174,9 @@ trait RenderPartialViews $categories = $repository->getCategories(); try { - $result = view('reports.options.category', compact('categories'))->render(); + $result = view('reports.options.category', ['categories' => $categories])->render(); } catch (Throwable $e) { - app('log')->error(sprintf('Cannot render reports.options.category: %s', $e->getMessage())); + Log::error(sprintf('Cannot render reports.options.category: %s', $e->getMessage())); $result = 'Could not render view.'; throw new FireflyException($result, 0, $e); @@ -215,9 +216,9 @@ trait RenderPartialViews } try { - $result = view('reports.options.double', compact('set'))->render(); + $result = view('reports.options.double', ['set' => $set])->render(); } catch (Throwable $e) { - app('log')->error(sprintf('Cannot render reports.options.tag: %s', $e->getMessage())); + Log::error(sprintf('Cannot render reports.options.tag: %s', $e->getMessage())); $result = 'Could not render view.'; throw new FireflyException($result, 0, $e); @@ -248,9 +249,9 @@ trait RenderPartialViews $journals = $popupHelper->byExpenses($account, $attributes); try { - $view = view('popup.report.expense-entry', compact('journals', 'account'))->render(); + $view = view('popup.report.expense-entry', ['journals' => $journals, 'account' => $account])->render(); } catch (Throwable $e) { - app('log')->error(sprintf('Could not render: %s', $e->getMessage())); + Log::error(sprintf('Could not render: %s', $e->getMessage())); $view = 'Firefly III could not render the view. Please see the log files.'; throw new FireflyException($view, 0, $e); @@ -286,8 +287,8 @@ trait RenderPartialViews ] )->render(); } catch (Throwable $e) { - app('log')->debug(sprintf('Throwable was thrown in getCurrentActions(): %s', $e->getMessage())); - app('log')->error($e->getTraceAsString()); + Log::debug(sprintf('Throwable was thrown in getCurrentActions(): %s', $e->getMessage())); + Log::error($e->getTraceAsString()); throw new FireflyException(sprintf('Could not render: %s', $e->getMessage()), 0, $e); } @@ -341,8 +342,8 @@ trait RenderPartialViews ] )->render(); } catch (Throwable $e) { - app('log')->debug(sprintf('Throwable was thrown in getCurrentTriggers(): %s', $e->getMessage())); - app('log')->error($e->getTraceAsString()); + Log::debug(sprintf('Throwable was thrown in getCurrentTriggers(): %s', $e->getMessage())); + Log::error($e->getTraceAsString()); throw new FireflyException(sprintf('Could not render: %s', $e->getMessage()), 0, $e); } @@ -375,9 +376,9 @@ trait RenderPartialViews $journals = $popupHelper->byIncome($account, $attributes); try { - $view = view('popup.report.income-entry', compact('journals', 'account'))->render(); + $view = view('popup.report.income-entry', ['journals' => $journals, 'account' => $account])->render(); } catch (Throwable $e) { - app('log')->error(sprintf('Could not render: %s', $e->getMessage())); + Log::error(sprintf('Could not render: %s', $e->getMessage())); $view = 'Firefly III could not render the view. Please see the log files.'; throw new FireflyException($view, 0, $e); @@ -396,7 +397,7 @@ trait RenderPartialViews try { $result = view('reports.options.no-options')->render(); } catch (Throwable $e) { - app('log')->error(sprintf('Cannot render reports.options.no-options: %s', $e->getMessage())); + Log::error(sprintf('Cannot render reports.options.no-options: %s', $e->getMessage())); $result = 'Could not render view.'; throw new FireflyException($result, 0, $e); @@ -417,9 +418,9 @@ trait RenderPartialViews $tags = $repository->get(); try { - $result = view('reports.options.tag', compact('tags'))->render(); + $result = view('reports.options.tag', ['tags' => $tags])->render(); } catch (Throwable $e) { - app('log')->error(sprintf('Cannot render reports.options.tag: %s', $e->getMessage())); + Log::error(sprintf('Cannot render reports.options.tag: %s', $e->getMessage())); $result = 'Could not render view.'; throw new FireflyException($result, 0, $e); diff --git a/app/Support/Http/Controllers/RequestInformation.php b/app/Support/Http/Controllers/RequestInformation.php index 39a6df3aff..2bd5dad925 100644 --- a/app/Support/Http/Controllers/RequestInformation.php +++ b/app/Support/Http/Controllers/RequestInformation.php @@ -133,11 +133,7 @@ trait RequestInformation return true; } // start and end in the past? use $end - if ($start->lessThanOrEqualTo($date) && $end->lessThanOrEqualTo($date)) { - return true; - } - - return false; + return $start->lessThanOrEqualTo($date) && $end->lessThanOrEqualTo($date); } /** diff --git a/app/Support/Http/Controllers/RuleManagement.php b/app/Support/Http/Controllers/RuleManagement.php index 081d1c44d0..e26d27498c 100644 --- a/app/Support/Http/Controllers/RuleManagement.php +++ b/app/Support/Http/Controllers/RuleManagement.php @@ -24,6 +24,7 @@ declare(strict_types=1); namespace FireflyIII\Support\Http\Controllers; +use Illuminate\Support\Facades\Log; use FireflyIII\Exceptions\FireflyException; use FireflyIII\Repositories\RuleGroup\RuleGroupRepositoryInterface; use FireflyIII\Support\Search\OperatorQuerySearch; @@ -56,8 +57,8 @@ trait RuleManagement ] )->render(); } catch (Throwable $e) { - app('log')->error(sprintf('Throwable was thrown in getPreviousActions(): %s', $e->getMessage())); - app('log')->error($e->getTraceAsString()); + Log::error(sprintf('Throwable was thrown in getPreviousActions(): %s', $e->getMessage())); + Log::error($e->getTraceAsString()); throw new FireflyException(sprintf('Could not render: %s', $e->getMessage()), 0, $e); } @@ -101,8 +102,8 @@ trait RuleManagement ] )->render(); } catch (Throwable $e) { - app('log')->debug(sprintf('Throwable was thrown in getPreviousTriggers(): %s', $e->getMessage())); - app('log')->error($e->getTraceAsString()); + Log::debug(sprintf('Throwable was thrown in getPreviousTriggers(): %s', $e->getMessage())); + Log::error($e->getTraceAsString()); throw new FireflyException(sprintf('Could not render: %s', $e->getMessage()), 0, $e); } @@ -147,8 +148,8 @@ trait RuleManagement ] )->render(); } catch (Throwable $e) { - app('log')->debug(sprintf('Throwable was thrown in getPreviousTriggers(): %s', $e->getMessage())); - app('log')->error($e->getTraceAsString()); + Log::debug(sprintf('Throwable was thrown in getPreviousTriggers(): %s', $e->getMessage())); + Log::error($e->getTraceAsString()); throw new FireflyException(sprintf('Could not render: %s', $e->getMessage()), 0, $e); } diff --git a/app/Support/Http/Controllers/UserNavigation.php b/app/Support/Http/Controllers/UserNavigation.php index bee31f429e..86804c7dbb 100644 --- a/app/Support/Http/Controllers/UserNavigation.php +++ b/app/Support/Http/Controllers/UserNavigation.php @@ -24,6 +24,7 @@ declare(strict_types=1); namespace FireflyIII\Support\Http\Controllers; +use Illuminate\Support\Facades\Log; use FireflyIII\Enums\AccountTypeEnum; use FireflyIII\Enums\TransactionTypeEnum; use FireflyIII\Models\Account; @@ -48,9 +49,9 @@ trait UserNavigation */ final protected function getPreviousUrl(string $identifier): string { - app('log')->debug(sprintf('Trying to retrieve URL stored under "%s"', $identifier)); + Log::debug(sprintf('Trying to retrieve URL stored under "%s"', $identifier)); $url = (string)session($identifier); - app('log')->debug(sprintf('The URL is %s', $url)); + Log::debug(sprintf('The URL is %s', $url)); return app('steam')->getSafeUrl($url, route('index')); } @@ -79,10 +80,7 @@ trait UserNavigation return in_array($type, $editable, true); } - /** - * @return Redirector|RedirectResponse - */ - final protected function redirectAccountToAccount(Account $account) + final protected function redirectAccountToAccount(Account $account): Redirector|RedirectResponse { $type = $account->accountType->type; if (AccountTypeEnum::RECONCILIATION->value === $type || AccountTypeEnum::INITIAL_BALANCE->value === $type || AccountTypeEnum::LIABILITY_CREDIT->value === $type) { @@ -91,7 +89,7 @@ trait UserNavigation /** @var null|Transaction $transaction */ $transaction = $account->transactions()->first(); if (null === $transaction) { - app('log')->error(sprintf('Account #%d has no transactions. Dont know where it belongs.', $account->id)); + Log::error(sprintf('Account #%d has no transactions. Dont know where it belongs.', $account->id)); session()->flash('error', trans('firefly.cant_find_redirect_account')); return redirect(route('index')); @@ -101,7 +99,7 @@ trait UserNavigation /** @var null|Transaction $other */ $other = $journal->transactions()->where('id', '!=', $transaction->id)->first(); if (null === $other) { - app('log')->error(sprintf('Account #%d has no valid journals. Dont know where it belongs.', $account->id)); + Log::error(sprintf('Account #%d has no valid journals. Dont know where it belongs.', $account->id)); session()->flash('error', trans('firefly.cant_find_redirect_account')); return redirect(route('index')); @@ -113,15 +111,12 @@ trait UserNavigation return redirect(route('index')); } - /** - * @return Redirector|RedirectResponse - */ - final protected function redirectGroupToAccount(TransactionGroup $group) + final protected function redirectGroupToAccount(TransactionGroup $group): Redirector|RedirectResponse { /** @var null|TransactionJournal $journal */ $journal = $group->transactionJournals()->first(); if (null === $journal) { - app('log')->error(sprintf('No journals in group #%d', $group->id)); + Log::error(sprintf('No journals in group #%d', $group->id)); return redirect(route('index')); } @@ -145,7 +140,7 @@ trait UserNavigation $return = app('steam')->getSafePreviousUrl(); session()->put($identifier, $return); - app('log')->debug(sprintf('rememberPreviousUrl: %s: "%s"', $identifier, $return)); + Log::debug(sprintf('rememberPreviousUrl: %s: "%s"', $identifier, $return)); return $return; } diff --git a/app/Support/JsonApi/Enrichments/AccountEnrichment.php b/app/Support/JsonApi/Enrichments/AccountEnrichment.php index 43179333d6..7b59442993 100644 --- a/app/Support/JsonApi/Enrichments/AccountEnrichment.php +++ b/app/Support/JsonApi/Enrichments/AccountEnrichment.php @@ -167,7 +167,7 @@ class AccountEnrichment implements EnrichmentInterface private function appendCollectedData(): void { - $this->collection = $this->collection->map(function (Account $item) { + $this->collection = $this->collection->map(function (Account $item): Account { $id = (int)$item->id; $item->full_account_type = $this->accountTypes[(int)$item->account_type_id] ?? null; $meta = [ diff --git a/app/Support/JsonApi/Enrichments/AvailableBudgetEnrichment.php b/app/Support/JsonApi/Enrichments/AvailableBudgetEnrichment.php index b794275706..8e09d2c5da 100644 --- a/app/Support/JsonApi/Enrichments/AvailableBudgetEnrichment.php +++ b/app/Support/JsonApi/Enrichments/AvailableBudgetEnrichment.php @@ -52,8 +52,6 @@ class AvailableBudgetEnrichment implements EnrichmentInterface private readonly BudgetRepositoryInterface $repository; private array $spentInBudgets = []; private array $spentOutsideBudgets = []; - private User $user; - private UserGroup $userGroup; public function __construct() { @@ -91,14 +89,12 @@ class AvailableBudgetEnrichment implements EnrichmentInterface #[Override] public function setUser(User $user): void { - $this->user = $user; $this->setUserGroup($user->userGroup); } #[Override] public function setUserGroup(UserGroup $userGroup): void { - $this->userGroup = $userGroup; $this->noBudgetRepository->setUserGroup($userGroup); $this->opsRepository->setUserGroup($userGroup); $this->repository->setUserGroup($userGroup); @@ -106,7 +102,7 @@ class AvailableBudgetEnrichment implements EnrichmentInterface private function appendCollectedData(): void { - $this->collection = $this->collection->map(function (AvailableBudget $item) { + $this->collection = $this->collection->map(function (AvailableBudget $item): AvailableBudget { $id = (int)$item->id; $currencyId = $this->currencyIds[$id]; $currency = $this->currencies[$currencyId]; @@ -158,7 +154,7 @@ class AvailableBudgetEnrichment implements EnrichmentInterface $this->spentInBudgets[$id] = array_values($filteredSpentInBudgets); $this->spentOutsideBudgets[$id] = array_values($filteredSpentOutsideBudgets); - if (true === $this->convertToPrimary) { + if ($this->convertToPrimary) { $pcFilteredSpentInBudgets = $this->opsRepository->sumCollectedExpenses($spentInBudgets, $availableBudget->start_date, $availableBudget->end_date, $currency, true); $pcFilteredSpentOutsideBudgets = $this->opsRepository->sumCollectedExpenses($spentOutsideBudgets, $availableBudget->start_date, $availableBudget->end_date, $currency, true); $this->pcSpentInBudgets[$id] = array_values($pcFilteredSpentInBudgets); diff --git a/app/Support/JsonApi/Enrichments/BudgetEnrichment.php b/app/Support/JsonApi/Enrichments/BudgetEnrichment.php index 8d548405d2..92e953a7be 100644 --- a/app/Support/JsonApi/Enrichments/BudgetEnrichment.php +++ b/app/Support/JsonApi/Enrichments/BudgetEnrichment.php @@ -54,8 +54,6 @@ class BudgetEnrichment implements EnrichmentInterface private User $user; private UserGroup $userGroup; - public function __construct() {} - public function enrich(Collection $collection): Collection { $this->collection = $collection; @@ -102,7 +100,7 @@ class BudgetEnrichment implements EnrichmentInterface private function appendCollectedData(): void { - $this->collection = $this->collection->map(function (Budget $item) { + $this->collection = $this->collection->map(function (Budget $item): Budget { $id = (int)$item->id; $meta = [ 'object_group_id' => null, diff --git a/app/Support/JsonApi/Enrichments/BudgetLimitEnrichment.php b/app/Support/JsonApi/Enrichments/BudgetLimitEnrichment.php index 8306274b4d..a7c3385645 100644 --- a/app/Support/JsonApi/Enrichments/BudgetLimitEnrichment.php +++ b/app/Support/JsonApi/Enrichments/BudgetLimitEnrichment.php @@ -41,7 +41,7 @@ use Illuminate\Support\Facades\Log; class BudgetLimitEnrichment implements EnrichmentInterface { private Collection $collection; - private bool $convertToPrimary; // @phpstan-ignore-line + private readonly bool $convertToPrimary; // @phpstan-ignore-line private array $currencies = []; private array $currencyIds = []; private Carbon $end; @@ -52,7 +52,6 @@ class BudgetLimitEnrichment implements EnrichmentInterface private readonly TransactionCurrency $primaryCurrency; private Carbon $start; private User $user; - private UserGroup $userGroup; public function __construct() { @@ -85,17 +84,15 @@ class BudgetLimitEnrichment implements EnrichmentInterface public function setUser(User $user): void { $this->user = $user; - $this->userGroup = $user->userGroup; } public function setUserGroup(UserGroup $userGroup): void { - $this->userGroup = $userGroup; } private function appendCollectedData(): void { - $this->collection = $this->collection->map(function (BudgetLimit $item) { + $this->collection = $this->collection->map(function (BudgetLimit $item): BudgetLimit { $id = (int)$item->id; $currencyId = (int)$item->transaction_currency_id; if (0 === $currencyId) { @@ -130,11 +127,11 @@ class BudgetLimitEnrichment implements EnrichmentInterface $filteredExpenses = $repository->sumCollectedExpenses($filteredExpenses, $budgetLimit->start_date, $budgetLimit->end_date, $budgetLimit->transactionCurrency); $this->expenses[$id] = array_values($filteredExpenses); - if (true === $this->convertToPrimary && $budgetLimit->transactionCurrency->id !== $this->primaryCurrency->id) { + if ($this->convertToPrimary && $budgetLimit->transactionCurrency->id !== $this->primaryCurrency->id) { $pcFilteredExpenses = $repository->sumCollectedExpenses($expenses, $budgetLimit->start_date, $budgetLimit->end_date, $budgetLimit->transactionCurrency, true); $this->pcExpenses[$id] = array_values($pcFilteredExpenses); } - if (true === $this->convertToPrimary && $budgetLimit->transactionCurrency->id === $this->primaryCurrency->id) { + if ($this->convertToPrimary && $budgetLimit->transactionCurrency->id === $this->primaryCurrency->id) { $this->pcExpenses[$id] = $this->expenses[$id] ?? []; } } @@ -184,7 +181,7 @@ class BudgetLimitEnrichment implements EnrichmentInterface private function filterToBudget(array $expenses, int $budget): array { - $result = array_filter($expenses, fn (array $item) => (int)$item['budget_id'] === $budget); + $result = array_filter($expenses, fn (array $item): bool => (int)$item['budget_id'] === $budget); Log::debug(sprintf('filterToBudget for budget #%d, from %d to %d items', $budget, count($expenses), count($result))); return $result; @@ -192,14 +189,14 @@ class BudgetLimitEnrichment implements EnrichmentInterface private function stringifyIds(): void { - $this->expenses = array_map(fn ($first) => array_map(function ($second) { + $this->expenses = array_map(fn ($first): array => array_map(function (array $second): array { $second['currency_id'] = (string)($second['currency_id'] ?? 0); return $second; }, $first), $this->expenses); - $this->pcExpenses = array_map(fn ($first) => array_map(function ($second) { - $second['currency_id'] = (string)($second['currency_id'] ?? 0); + $this->pcExpenses = array_map(fn (array $first): array => array_map(function (array $second): array { + $second['currency_id'] ??= 0; return $second; }, $first), $this->expenses); diff --git a/app/Support/JsonApi/Enrichments/CategoryEnrichment.php b/app/Support/JsonApi/Enrichments/CategoryEnrichment.php index f470e1c111..699102912e 100644 --- a/app/Support/JsonApi/Enrichments/CategoryEnrichment.php +++ b/app/Support/JsonApi/Enrichments/CategoryEnrichment.php @@ -94,7 +94,7 @@ class CategoryEnrichment implements EnrichmentInterface private function appendCollectedData(): void { - $this->collection = $this->collection->map(function (Category $item) { + $this->collection = $this->collection->map(function (Category $item): Category { $id = (int)$item->id; $meta = [ 'notes' => $this->notes[$id] ?? null, diff --git a/app/Support/JsonApi/Enrichments/PiggyBankEnrichment.php b/app/Support/JsonApi/Enrichments/PiggyBankEnrichment.php index 23f7b2d2d3..2309e6b228 100644 --- a/app/Support/JsonApi/Enrichments/PiggyBankEnrichment.php +++ b/app/Support/JsonApi/Enrichments/PiggyBankEnrichment.php @@ -55,8 +55,6 @@ class PiggyBankEnrichment implements EnrichmentInterface private array $notes = []; private array $objectGroups = []; private readonly TransactionCurrency $primaryCurrency; - private User $user; - private UserGroup $userGroup; private ?Carbon $date; public function __construct() @@ -89,18 +87,16 @@ class PiggyBankEnrichment implements EnrichmentInterface public function setUser(User $user): void { - $this->user = $user; $this->setUserGroup($user->userGroup); } public function setUserGroup(UserGroup $userGroup): void { - $this->userGroup = $userGroup; } private function appendCollectedData(): void { - $this->collection = $this->collection->map(function (PiggyBank $item) { + $this->collection = $this->collection->map(function (PiggyBank $item): PiggyBank { $id = (int)$item->id; $currencyId = (int)$item->transaction_currency_id; $currency = $this->currencies[$currencyId] ?? $this->primaryCurrency; diff --git a/app/Support/JsonApi/Enrichments/PiggyBankEventEnrichment.php b/app/Support/JsonApi/Enrichments/PiggyBankEventEnrichment.php index 56a0714466..b8c78464da 100644 --- a/app/Support/JsonApi/Enrichments/PiggyBankEventEnrichment.php +++ b/app/Support/JsonApi/Enrichments/PiggyBankEventEnrichment.php @@ -46,8 +46,6 @@ class PiggyBankEventEnrichment implements EnrichmentInterface private array $ids = []; private array $journalIds = []; private array $piggyBankIds = []; - private User $user; - private UserGroup $userGroup; // private bool $convertToPrimary = false; // private TransactionCurrency $primaryCurrency; @@ -77,18 +75,16 @@ class PiggyBankEventEnrichment implements EnrichmentInterface public function setUser(User $user): void { - $this->user = $user; $this->setUserGroup($user->userGroup); } public function setUserGroup(UserGroup $userGroup): void { - $this->userGroup = $userGroup; } private function appendCollectedData(): void { - $this->collection = $this->collection->map(function (PiggyBankEvent $item) { + $this->collection = $this->collection->map(function (PiggyBankEvent $item): PiggyBankEvent { $id = (int)$item->id; $piggyId = (int)$item->piggy_bank_id; $journalId = (int)$item->transaction_journal_id; diff --git a/app/Support/JsonApi/Enrichments/RecurringEnrichment.php b/app/Support/JsonApi/Enrichments/RecurringEnrichment.php index fb5115136a..1f881ddbc5 100644 --- a/app/Support/JsonApi/Enrichments/RecurringEnrichment.php +++ b/app/Support/JsonApi/Enrichments/RecurringEnrichment.php @@ -60,7 +60,7 @@ class RecurringEnrichment implements EnrichmentInterface private Collection $collection; // private array $transactionTypeIds = []; // private array $transactionTypes = []; - private bool $convertToPrimary; + private readonly bool $convertToPrimary; private array $currencies = []; private array $currencyIds = []; private array $destinationAccountIds = []; @@ -171,7 +171,7 @@ class RecurringEnrichment implements EnrichmentInterface private function appendCollectedData(): void { - $this->collection = $this->collection->map(function (Recurrence $item) { + $this->collection = $this->collection->map(function (Recurrence $item): Recurrence { $id = (int)$item->id; $meta = [ 'notes' => $this->notes[$id] ?? null, @@ -341,7 +341,7 @@ class RecurringEnrichment implements EnrichmentInterface /** @var RecurrenceRepetition $repetition */ foreach ($set as $repetition) { - $recurrence = $this->collection->filter(fn (Recurrence $item) => (int)$item->id === (int)$repetition->recurrence_id)->first(); + $recurrence = $this->collection->filter(fn (Recurrence $item): bool => (int)$item->id === (int)$repetition->recurrence_id)->first(); $fromDate = clone ($recurrence->latest_date ?? $recurrence->first_date); $id = (int)$repetition->recurrence_id; $repId = (int)$repetition->id; @@ -549,11 +549,11 @@ class RecurringEnrichment implements EnrichmentInterface $pcAmount = null; $pcForeignAmount = null; // set the same amount in the primary currency, if both are the same anyway. - if (true === $this->convertToPrimary && $currencyId === (int)$this->primaryCurrency->id) { + if ($this->convertToPrimary && $currencyId === (int)$this->primaryCurrency->id) { $pcAmount = $transaction['amount']; } // convert the amount to the primary currency, if it is not the same. - if (true === $this->convertToPrimary && $currencyId !== (int)$this->primaryCurrency->id) { + if ($this->convertToPrimary && $currencyId !== (int)$this->primaryCurrency->id) { $pcAmount = $converter->convert($this->currencies[$currencyId], $this->primaryCurrency, today(), $transaction['amount']); } if (null !== $transaction['foreign_amount'] && null !== $transaction['foreign_currency_id']) { diff --git a/app/Support/JsonApi/Enrichments/SubscriptionEnrichment.php b/app/Support/JsonApi/Enrichments/SubscriptionEnrichment.php index 3068c45d88..8d3c134f65 100644 --- a/app/Support/JsonApi/Enrichments/SubscriptionEnrichment.php +++ b/app/Support/JsonApi/Enrichments/SubscriptionEnrichment.php @@ -59,7 +59,6 @@ class SubscriptionEnrichment implements EnrichmentInterface private ?Carbon $start = null; private array $subscriptionIds = []; private User $user; - private UserGroup $userGroup; public function __construct() { @@ -84,7 +83,7 @@ class SubscriptionEnrichment implements EnrichmentInterface $notes = $this->notes; $paidDates = $this->paidDates; $payDates = $this->payDates; - $this->collection = $this->collection->map(function (Bill $item) use ($notes, $paidDates, $payDates) { + $this->collection = $this->collection->map(function (Bill $item) use ($notes, $paidDates, $payDates): Bill { $id = (int)$item->id; $currency = $item->transactionCurrency; $nem = $this->getNextExpectedMatch($payDates[$id] ?? []); @@ -165,12 +164,10 @@ class SubscriptionEnrichment implements EnrichmentInterface public function setUser(User $user): void { $this->user = $user; - $this->userGroup = $user->userGroup; } public function setUserGroup(UserGroup $userGroup): void { - $this->userGroup = $userGroup; } /** @@ -178,7 +175,7 @@ class SubscriptionEnrichment implements EnrichmentInterface */ protected function lastPaidDate(Bill $subscription, Collection $dates, Carbon $default): Carbon { - $filtered = $dates->filter(fn (TransactionJournal $journal) => (int)$journal->bill_id === (int)$subscription->id); + $filtered = $dates->filter(fn (TransactionJournal $journal): bool => (int)$journal->bill_id === (int)$subscription->id); Log::debug(sprintf('Filtered down from %d to %d entries for bill #%d.', $dates->count(), $filtered->count(), $subscription->id)); if (0 === $filtered->count()) { return $default; @@ -299,7 +296,7 @@ class SubscriptionEnrichment implements EnrichmentInterface // At this point the "next match" is exactly after the last time the bill was paid. $result = []; - $filtered = $set->filter(fn (TransactionJournal $journal) => (int)$journal->bill_id === (int)$subscription->id); + $filtered = $set->filter(fn (TransactionJournal $journal): bool => (int)$journal->bill_id === (int)$subscription->id); foreach ($filtered as $entry) { $array = [ 'transaction_group_id' => (string)$entry->transaction_group_id, @@ -390,7 +387,7 @@ class SubscriptionEnrichment implements EnrichmentInterface private function filterPaidDates(array $entries): array { - return array_map(function (array $entry) { + return array_map(function (array $entry): array { unset($entry['date_object']); return $entry; diff --git a/app/Support/JsonApi/Enrichments/TransactionGroupEnrichment.php b/app/Support/JsonApi/Enrichments/TransactionGroupEnrichment.php index a8dccfe9fc..f4d5fdebda 100644 --- a/app/Support/JsonApi/Enrichments/TransactionGroupEnrichment.php +++ b/app/Support/JsonApi/Enrichments/TransactionGroupEnrichment.php @@ -54,8 +54,6 @@ class TransactionGroupEnrichment implements EnrichmentInterface private array $notes = []; private readonly TransactionCurrency $primaryCurrency; private array $tags = []; // @phpstan-ignore-line - private User $user; - private UserGroup $userGroup; // @phpstan-ignore-line public function __construct() { @@ -98,13 +96,10 @@ class TransactionGroupEnrichment implements EnrichmentInterface public function setUser(User $user): void { - $this->user = $user; - $this->userGroup = $user->userGroup; } public function setUserGroup(UserGroup $userGroup): void { - $this->userGroup = $userGroup; } private function appendCollectedData(): void @@ -116,12 +111,12 @@ class TransactionGroupEnrichment implements EnrichmentInterface $attachmentCount = $this->attachmentCount; $primaryCurrency = $this->primaryCurrency; - $this->collection = $this->collection->map(function (array $item) use ($primaryCurrency, $notes, $tags, $metaData, $locations, $attachmentCount) { + $this->collection = $this->collection->map(function (array $item) use ($primaryCurrency, $notes, $tags, $metaData, $locations, $attachmentCount): array { foreach ($item['transactions'] as $index => $transaction) { $journalId = (int)$transaction['transaction_journal_id']; // attach notes if they exist: - $item['transactions'][$index]['notes'] = array_key_exists($journalId, $notes) ? $notes[$journalId] : null; + $item['transactions'][$index]['notes'] = $notes[$journalId] ?? null; // attach tags if they exist: $item['transactions'][$index]['tags'] = array_key_exists($journalId, $tags) ? $tags[$journalId] : []; diff --git a/app/Support/JsonApi/Enrichments/WebhookEnrichment.php b/app/Support/JsonApi/Enrichments/WebhookEnrichment.php index e847a16b0f..4553b494e8 100644 --- a/app/Support/JsonApi/Enrichments/WebhookEnrichment.php +++ b/app/Support/JsonApi/Enrichments/WebhookEnrichment.php @@ -47,8 +47,6 @@ class WebhookEnrichment implements EnrichmentInterface private array $ids = []; // @phpstan-ignore-line private array $responses = []; private array $triggers = []; - private User $user; - private UserGroup $userGroup; private array $webhookDeliveries = []; private array $webhookResponses = []; private array $webhookTriggers = []; @@ -77,17 +75,15 @@ class WebhookEnrichment implements EnrichmentInterface public function setUser(User $user): void { - $this->user = $user; } public function setUserGroup(UserGroup $userGroup): void { - $this->userGroup = $userGroup; } private function appendCollectedInfo(): void { - $this->collection = $this->collection->map(function (Webhook $item) { + $this->collection = $this->collection->map(function (Webhook $item): Webhook { $meta = [ 'deliveries' => $this->webhookDeliveries[$item->id] ?? [], 'responses' => $this->webhookResponses[$item->id] ?? [], diff --git a/app/Support/Models/ReturnsIntegerIdTrait.php b/app/Support/Models/ReturnsIntegerIdTrait.php index f3fac096ce..eb628bf26e 100644 --- a/app/Support/Models/ReturnsIntegerIdTrait.php +++ b/app/Support/Models/ReturnsIntegerIdTrait.php @@ -39,7 +39,7 @@ trait ReturnsIntegerIdTrait protected function id(): Attribute { return Attribute::make( - get: static fn ($value) => (int)$value, + get: static fn ($value): int => (int)$value, ); } } diff --git a/app/Support/Models/ReturnsIntegerUserIdTrait.php b/app/Support/Models/ReturnsIntegerUserIdTrait.php index 3f1808923d..e9aeed82ba 100644 --- a/app/Support/Models/ReturnsIntegerUserIdTrait.php +++ b/app/Support/Models/ReturnsIntegerUserIdTrait.php @@ -37,14 +37,14 @@ trait ReturnsIntegerUserIdTrait protected function userGroupId(): Attribute { return Attribute::make( - get: static fn ($value) => (int)$value, + get: static fn ($value): int => (int)$value, ); } protected function userId(): Attribute { return Attribute::make( - get: static fn ($value) => (int)$value, + get: static fn ($value): int => (int)$value, ); } } diff --git a/app/Support/ParseDateString.php b/app/Support/ParseDateString.php index 46df80c290..b1e13aad5d 100644 --- a/app/Support/ParseDateString.php +++ b/app/Support/ParseDateString.php @@ -65,11 +65,7 @@ class ParseDateString return false; } // no x'es - if (!str_contains($date, 'xx') && !str_contains($date, 'xxxx')) { - return false; - } - - return true; + return !(!str_contains($date, 'xx') && !str_contains($date, 'xxxx')); } /** diff --git a/app/Support/Report/Budget/BudgetReportGenerator.php b/app/Support/Report/Budget/BudgetReportGenerator.php index 42f58a2728..246f05dd0d 100644 --- a/app/Support/Report/Budget/BudgetReportGenerator.php +++ b/app/Support/Report/Budget/BudgetReportGenerator.php @@ -49,7 +49,7 @@ class BudgetReportGenerator private Carbon $end; private readonly NoBudgetRepositoryInterface $nbRepository; private readonly OperationsRepositoryInterface $opsRepository; - private array $report; + private array $report = []; private readonly BudgetRepositoryInterface $repository; private Carbon $start; @@ -62,7 +62,6 @@ class BudgetReportGenerator $this->blRepository = app(BudgetLimitRepositoryInterface::class); $this->opsRepository = app(OperationsRepositoryInterface::class); $this->nbRepository = app(NoBudgetRepositoryInterface::class); - $this->report = []; } /** diff --git a/app/Support/Report/Summarizer/TransactionSummarizer.php b/app/Support/Report/Summarizer/TransactionSummarizer.php index 83f057c68c..326dd9f644 100644 --- a/app/Support/Report/Summarizer/TransactionSummarizer.php +++ b/app/Support/Report/Summarizer/TransactionSummarizer.php @@ -120,7 +120,7 @@ class TransactionSummarizer } // then process foreign amount, if it exists. - if (0 !== $foreignCurrencyId && true === $includeForeign) { + if (0 !== $foreignCurrencyId && $includeForeign) { $amount = (string)($journal['foreign_amount'] ?? '0'); $array[$foreignCurrencyId] ??= [ 'sum' => '0', diff --git a/app/Support/Repositories/Recurring/CalculateRangeOccurrences.php b/app/Support/Repositories/Recurring/CalculateRangeOccurrences.php index df73a72f60..f9fd9994ee 100644 --- a/app/Support/Repositories/Recurring/CalculateRangeOccurrences.php +++ b/app/Support/Repositories/Recurring/CalculateRangeOccurrences.php @@ -24,6 +24,7 @@ declare(strict_types=1); namespace FireflyIII\Support\Repositories\Recurring; +use Illuminate\Support\Facades\Log; use Carbon\Carbon; /** @@ -110,30 +111,30 @@ trait CalculateRangeOccurrences { $return = []; $attempts = 0; - app('log')->debug('Rep is weekly.'); + Log::debug('Rep is weekly.'); // monday = 1 // sunday = 7 $dayOfWeek = (int)$moment; - app('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) { // day has already passed this week, add one week: $start->addWeek(); - app('log')->debug(sprintf('Jump to next week, so mutator is now: %s', $start->format('Y-m-d'))); + Log::debug(sprintf('Jump to next week, so mutator is now: %s', $start->format('Y-m-d'))); } // today is wednesday (3), expected is friday (5): add two days. // today is friday (5), expected is monday (1), subtract four days. - app('log')->debug(sprintf('Mutator is now: %s', $start->format('Y-m-d'))); + Log::debug(sprintf('Mutator is now: %s', $start->format('Y-m-d'))); $dayDifference = $dayOfWeek - $start->dayOfWeekIso; $start->addDays($dayDifference); - app('log')->debug(sprintf('Mutator is now: %s', $start->format('Y-m-d'))); + Log::debug(sprintf('Mutator is now: %s', $start->format('Y-m-d'))); while ($start <= $end) { if (0 === $attempts % $skipMod && $start->lte($start) && $end->gte($start)) { - app('log')->debug('Date is in range of start+end, add to set.'); + Log::debug('Date is in range of start+end, add to set.'); $return[] = clone $start; } ++$attempts; $start->addWeek(); - app('log')->debug(sprintf('Mutator is now (end of loop): %s', $start->format('Y-m-d'))); + Log::debug(sprintf('Mutator is now (end of loop): %s', $start->format('Y-m-d'))); } return $return; diff --git a/app/Support/Repositories/Recurring/CalculateXOccurrencesSince.php b/app/Support/Repositories/Recurring/CalculateXOccurrencesSince.php index 9587ccc0f7..ccef5770ca 100644 --- a/app/Support/Repositories/Recurring/CalculateXOccurrencesSince.php +++ b/app/Support/Repositories/Recurring/CalculateXOccurrencesSince.php @@ -74,7 +74,7 @@ trait CalculateXOccurrencesSince Log::debug(sprintf('%d is after %d, add a month. Mutator is now...', $mutator->day, $dayOfMonth)); // day has passed already, add a month. $mutator->addMonth(); - Log::debug(sprintf('%s', $mutator->toAtomString())); + Log::debug($mutator->toAtomString()); } while ($total < $count) { diff --git a/app/Support/Request/AppendsLocationData.php b/app/Support/Request/AppendsLocationData.php index b77cd9ee41..26c54ef921 100644 --- a/app/Support/Request/AppendsLocationData.php +++ b/app/Support/Request/AppendsLocationData.php @@ -24,6 +24,8 @@ declare(strict_types=1); namespace FireflyIII\Support\Request; +use Illuminate\Support\Facades\Log; + /** * Trait AppendsLocationData */ @@ -33,8 +35,8 @@ trait AppendsLocationData { $return['store_location'] = false; if (true === $information['store_location']) { - $long = array_key_exists('longitude', $information) ? $information['longitude'] : null; - $lat = array_key_exists('latitude', $information) ? $information['latitude'] : null; + $long = $information['longitude'] ?? null; + $lat = $information['latitude'] ?? null; if (null !== $long && null !== $lat && $this->validLongitude($long) && $this->validLatitude($lat)) { $return['store_location'] = true; $return['longitude'] = $information['longitude']; @@ -49,11 +51,9 @@ trait AppendsLocationData /** * Abstract method stolen from "InteractsWithInput". * - * @param null $key * @param bool $default * * @return mixed - * * @SuppressWarnings("PHPMD.BooleanArgumentFlag") */ abstract public function boolean($key = null, $default = false); @@ -88,7 +88,7 @@ trait AppendsLocationData */ protected function appendLocationData(array $data, ?string $prefix): array { - app('log')->debug(sprintf('Now in appendLocationData("%s")', $prefix), $data); + Log::debug(sprintf('Now in appendLocationData("%s")', $prefix), $data); $data['store_location'] = false; $data['update_location'] = false; $data['remove_location'] = false; @@ -105,7 +105,7 @@ trait AppendsLocationData // for a POST (store), all fields must be present and not NULL. if ($isValidPOST) { - app('log')->debug('Method is POST and all fields present and not NULL.'); + Log::debug('Method is POST and all fields present and not NULL.'); $data['store_location'] = true; $data['longitude'] = $this->convertString($longitudeKey); $data['latitude'] = $this->convertString($latitudeKey); @@ -114,18 +114,18 @@ trait AppendsLocationData // for a PUT (api update) or POST update (UI) if ($isValidPUT) { - app('log')->debug('Method is PUT and all fields present and not NULL.'); + Log::debug('Method is PUT and all fields present and not NULL.'); $data['update_location'] = true; $data['longitude'] = $this->convertString($longitudeKey); $data['latitude'] = $this->convertString($latitudeKey); $data['zoom_level'] = $this->convertString($zoomLevelKey); } if ($isValidEmptyPUT) { - app('log')->debug('Method is PUT and all fields present and NULL.'); + Log::debug('Method is PUT and all fields present and NULL.'); $data['remove_location'] = true; } - app('log')->debug(sprintf('Returning longitude: "%s", latitude: "%s", zoom level: "%s"', $data['longitude'], $data['latitude'], $data['zoom_level'])); - app('log')->debug( + Log::debug(sprintf('Returning longitude: "%s", latitude: "%s", zoom level: "%s"', $data['longitude'], $data['latitude'], $data['zoom_level'])); + Log::debug( sprintf( 'Returning actions: store: %s, update: %s, delete: %s', var_export($data['store_location'], true), @@ -168,74 +168,74 @@ trait AppendsLocationData $latitudeKey = $this->getLocationKey($prefix, 'latitude'); $zoomLevelKey = $this->getLocationKey($prefix, 'zoom_level'); $hasLocationKey = $this->getLocationKey($prefix, 'has_location'); - app('log')->debug('Now in isValidPUT()'); + Log::debug('Now in isValidPUT()'); // all fields must be set: - if (null !== $this->get($longitudeKey) && null !== $this->get($latitudeKey) && null !== $this->get($zoomLevelKey)) { - app('log')->debug('All fields present.'); + if (!in_array(null, [$this->get($longitudeKey), $this->get($latitudeKey), $this->get($zoomLevelKey)], true)) { + Log::debug('All fields present.'); // must be PUT and API route: if ('PUT' === $this->method() && $this->routeIs('api.v1.*')) { - app('log')->debug('Is API location'); + Log::debug('Is API location'); return true; } // if POST and not API route, must also have "has_location" // if is POST and route does not contain API, must also have "has_location" = true if ('POST' === $this->method() && $this->routeIs('*.update') && !$this->routeIs('api.v1.*') && '' !== $hasLocationKey) { - app('log')->debug('Is POST + store route.'); + Log::debug('Is POST + store route.'); $hasLocation = $this->boolean($hasLocationKey); if (true === $hasLocation) { - app('log')->debug('Has form location data + has_location'); + Log::debug('Has form location data + has_location'); return true; } - app('log')->debug('Does not have form location'); + Log::debug('Does not have form location'); return false; } - app('log')->debug('Is not POST API or POST form'); + Log::debug('Is not POST API or POST form'); return false; } - app('log')->debug('Fields not present'); + Log::debug('Fields not present'); return false; } private function isValidPost(?string $prefix): bool { - app('log')->debug('Now in isValidPost()'); + Log::debug('Now in isValidPost()'); $longitudeKey = $this->getLocationKey($prefix, 'longitude'); $latitudeKey = $this->getLocationKey($prefix, 'latitude'); $zoomLevelKey = $this->getLocationKey($prefix, 'zoom_level'); $hasLocationKey = $this->getLocationKey($prefix, 'has_location'); // fields must not be null: - if (null !== $this->get($longitudeKey) && null !== $this->get($latitudeKey) && null !== $this->get($zoomLevelKey)) { - app('log')->debug('All fields present'); + if (!in_array(null, [$this->get($longitudeKey), $this->get($latitudeKey), $this->get($zoomLevelKey)], true)) { + Log::debug('All fields present'); // if is POST and route contains API, this is enough: if ('POST' === $this->method() && $this->routeIs('api.v1.*')) { - app('log')->debug('Is API location'); + Log::debug('Is API location'); return true; } // if is POST and route does not contain API, must also have "has_location" = true if ('POST' === $this->method() && $this->routeIs('*.store') && !$this->routeIs('api.v1.*') && '' !== $hasLocationKey) { - app('log')->debug('Is POST + store route.'); + Log::debug('Is POST + store route.'); $hasLocation = $this->boolean($hasLocationKey); if (true === $hasLocation) { - app('log')->debug('Has form form location'); + Log::debug('Has form form location'); return true; } - app('log')->debug('Does not have form location'); + Log::debug('Does not have form location'); return false; } - app('log')->debug('Is not POST API or POST form'); + Log::debug('Is not POST API or POST form'); return false; } - app('log')->debug('Fields not present'); + Log::debug('Fields not present'); return false; } diff --git a/app/Support/Request/ChecksLogin.php b/app/Support/Request/ChecksLogin.php index 0f9753ee62..2781c131db 100644 --- a/app/Support/Request/ChecksLogin.php +++ b/app/Support/Request/ChecksLogin.php @@ -24,6 +24,7 @@ declare(strict_types=1); namespace FireflyIII\Support\Request; +use Illuminate\Support\Facades\Log; use FireflyIII\Enums\UserRoleEnum; use FireflyIII\Models\UserGroup; use FireflyIII\User; @@ -38,14 +39,14 @@ trait ChecksLogin */ public function authorize(): bool { - app('log')->debug(sprintf('Now in %s', __METHOD__)); + Log::debug(sprintf('Now in %s', __METHOD__)); // Only allow logged-in users $check = auth()->check(); if (!$check) { return false; } if (!property_exists($this, 'acceptedRoles')) { // @phpstan-ignore-line - app('log')->debug('Request class has no acceptedRoles array'); + Log::debug('Request class has no acceptedRoles array'); return true; // check for false already took place. } @@ -54,7 +55,7 @@ trait ChecksLogin $user = auth()->user(); $userGroup = $this->getUserGroup(); if (null === $userGroup) { - app('log')->error('User has no valid user group submitted or otherwise.'); + Log::error('User has no valid user group submitted or otherwise.'); return false; } @@ -80,24 +81,24 @@ trait ChecksLogin { /** @var User $user */ $user = auth()->user(); - app('log')->debug('Now in getUserGroup()'); + Log::debug('Now in getUserGroup()'); /** @var null|UserGroup $userGroup */ $userGroup = $this->route()?->parameter('userGroup'); if (null === $userGroup) { - app('log')->debug('Request class has no userGroup parameter, but perhaps there is a parameter.'); + Log::debug('Request class has no userGroup parameter, but perhaps there is a parameter.'); $userGroupId = (int)$this->get('user_group_id'); if (0 === $userGroupId) { - app('log')->debug(sprintf('Request class has no user_group_id parameter, grab default from user (group #%d).', $user->user_group_id)); + Log::debug(sprintf('Request class has no user_group_id parameter, grab default from user (group #%d).', $user->user_group_id)); $userGroupId = (int)$user->user_group_id; } $userGroup = UserGroup::find($userGroupId); if (null === $userGroup) { - app('log')->error(sprintf('Request class has user_group_id (#%d), but group does not exist.', $userGroupId)); + Log::error(sprintf('Request class has user_group_id (#%d), but group does not exist.', $userGroupId)); return null; } - app('log')->debug('Request class has valid user_group_id.'); + Log::debug('Request class has valid user_group_id.'); } return $userGroup; diff --git a/app/Support/Request/ConvertsDataTypes.php b/app/Support/Request/ConvertsDataTypes.php index f8cb76378f..64804987b9 100644 --- a/app/Support/Request/ConvertsDataTypes.php +++ b/app/Support/Request/ConvertsDataTypes.php @@ -274,11 +274,7 @@ trait ConvertsDataTypes if ('y' === $value) { return true; } - if ('1' === $value) { - return true; - } - - return false; + return '1' === $value; } protected function convertDateTime(?string $string): ?Carbon diff --git a/app/Support/Request/ValidatesWebhooks.php b/app/Support/Request/ValidatesWebhooks.php index 15d41f41ef..331eecc552 100644 --- a/app/Support/Request/ValidatesWebhooks.php +++ b/app/Support/Request/ValidatesWebhooks.php @@ -25,10 +25,10 @@ declare(strict_types=1); namespace FireflyIII\Support\Request; +use Illuminate\Contracts\Validation\Validator; use FireflyIII\Enums\WebhookTrigger; use FireflyIII\Models\Webhook; use Illuminate\Support\Facades\Log; -use Illuminate\Validation\Validator; trait ValidatesWebhooks { diff --git a/app/Support/Search/AccountSearch.php b/app/Support/Search/AccountSearch.php index 44bb34e893..3820caf7bc 100644 --- a/app/Support/Search/AccountSearch.php +++ b/app/Support/Search/AccountSearch.php @@ -36,30 +36,20 @@ use function Safe\json_encode; */ class AccountSearch implements GenericSearchInterface { - /** @var string */ public const string SEARCH_ALL = 'all'; - /** @var string */ public const string SEARCH_IBAN = 'iban'; - /** @var string */ public const string SEARCH_ID = 'id'; - /** @var string */ public const string SEARCH_NAME = 'name'; - /** @var string */ public const string SEARCH_NUMBER = 'number'; private string $field; private string $query; - private array $types; + private array $types = []; private User $user; - public function __construct() - { - $this->types = []; - } - public function search(): Collection { $searchQuery = $this->user->accounts() diff --git a/app/Support/Search/OperatorQuerySearch.php b/app/Support/Search/OperatorQuerySearch.php index 5546fbc8c9..d13ebc8dd1 100644 --- a/app/Support/Search/OperatorQuerySearch.php +++ b/app/Support/Search/OperatorQuerySearch.php @@ -66,19 +66,19 @@ class OperatorQuerySearch implements SearchInterface private readonly CategoryRepositoryInterface $categoryRepository; private GroupCollectorInterface $collector; private readonly CurrencyRepositoryInterface $currencyRepository; - private array $excludeTags; - private array $includeAnyTags; + private array $excludeTags = []; + private array $includeAnyTags = []; // added to fix #8632 - private array $includeTags; - private array $invalidOperators; - private int $limit; + private array $includeTags = []; + private array $invalidOperators = []; + private int $limit = 25; private readonly Collection $operators; - private int $page; - private array $prohibitedWords; + private int $page = 1; + private array $prohibitedWords = []; private readonly float $startTime; private readonly TagRepositoryInterface $tagRepository; private readonly array $validOperators; - private array $words; + private array $words = []; /** * OperatorQuerySearch constructor. @@ -87,14 +87,6 @@ class OperatorQuerySearch implements SearchInterface { Log::debug('Constructed OperatorQuerySearch'); $this->operators = new Collection(); - $this->page = 1; - $this->words = []; - $this->excludeTags = []; - $this->includeAnyTags = []; - $this->includeTags = []; - $this->prohibitedWords = []; - $this->invalidOperators = []; - $this->limit = 25; $this->validOperators = array_keys(config('search.operators')); $this->startTime = microtime(true); $this->accountRepository = app(AccountRepositoryInterface::class); @@ -293,15 +285,13 @@ class OperatorQuerySearch implements SearchInterface // must be valid operator: $inArray = in_array($operator, $this->validOperators, true); - if ($inArray) { - if ($this->updateCollector($operator, $value, $prohibited)) { - $this->operators->push([ - 'type' => self::getRootOperator($operator), - 'value' => $value, - 'prohibited' => $prohibited, - ]); - Log::debug(sprintf('Added operator type "%s"', $operator)); - } + if ($inArray && $this->updateCollector($operator, $value, $prohibited)) { + $this->operators->push([ + 'type' => self::getRootOperator($operator), + 'value' => $value, + 'prohibited' => $prohibited, + ]); + Log::debug(sprintf('Added operator type "%s"', $operator)); } if (!$inArray) { Log::debug(sprintf('Added INVALID operator type "%s"', $operator)); @@ -495,14 +485,14 @@ class OperatorQuerySearch implements SearchInterface return; } - if (0 === $accounts->count() && true === $prohibited) { + if (0 === $accounts->count() && $prohibited) { Log::debug('Found zero accounts, but the search is negated, so effectively we ignore the search parameter.'); return; } Log::debug(sprintf('Found %d accounts, will filter.', $accounts->count())); $filtered = $accounts->filter( - static fn (Account $account) => $stringMethod(strtolower($account->name), strtolower($value)) + static fn (Account $account): bool => $stringMethod(strtolower($account->name), strtolower($value)) ); if (0 === $filtered->count()) { @@ -530,7 +520,7 @@ class OperatorQuerySearch implements SearchInterface // search direction (default): for source accounts $searchTypes = [AccountTypeEnum::ASSET->value, AccountTypeEnum::MORTGAGE->value, AccountTypeEnum::LOAN->value, AccountTypeEnum::DEBT->value, AccountTypeEnum::REVENUE->value]; $collectorMethod = 'setSourceAccounts'; - if (true === $prohibited) { + if ($prohibited) { $collectorMethod = 'excludeSourceAccounts'; } @@ -539,7 +529,7 @@ class OperatorQuerySearch implements SearchInterface // destination can be $searchTypes = [AccountTypeEnum::ASSET->value, AccountTypeEnum::MORTGAGE->value, AccountTypeEnum::LOAN->value, AccountTypeEnum::DEBT->value, AccountTypeEnum::EXPENSE->value]; $collectorMethod = 'setDestinationAccounts'; - if (true === $prohibited) { + if ($prohibited) { $collectorMethod = 'excludeDestinationAccounts'; } } @@ -548,7 +538,7 @@ class OperatorQuerySearch implements SearchInterface if (SearchDirection::BOTH === $searchDirection) { $searchTypes = [AccountTypeEnum::ASSET->value, AccountTypeEnum::MORTGAGE->value, AccountTypeEnum::LOAN->value, AccountTypeEnum::DEBT->value, AccountTypeEnum::EXPENSE->value, AccountTypeEnum::REVENUE->value]; $collectorMethod = 'setAccounts'; - if (true === $prohibited) { + if ($prohibited) { $collectorMethod = 'excludeAccounts'; } } @@ -580,7 +570,7 @@ class OperatorQuerySearch implements SearchInterface // if found, do filter Log::debug(sprintf('Found %d accounts, will filter.', $accounts->count())); $filtered = $accounts->filter( - static function (Account $account) use ($value, $stringMethod) { + static function (Account $account) use ($value, $stringMethod): bool { // either IBAN or account number $ibanMatch = $stringMethod(strtolower((string)$account->iban), strtolower($value)); $accountNrMatch = false; diff --git a/app/Support/Search/QueryParser/GdbotsQueryParser.php b/app/Support/Search/QueryParser/GdbotsQueryParser.php index 209b09721a..95d65556e8 100644 --- a/app/Support/Search/QueryParser/GdbotsQueryParser.php +++ b/app/Support/Search/QueryParser/GdbotsQueryParser.php @@ -54,15 +54,15 @@ class GdbotsQueryParser implements QueryParserInterface try { $result = $this->parser->parse($query); $nodes = array_map( - fn (GdbotsNode\Node $node) => $this->convertNode($node), + $this->convertNode(...), $result->getNodes() ); return new NodeGroup($nodes); } catch (LogicException|TypeError $e) { fwrite(STDERR, "Setting up GdbotsQueryParserTest\n"); - app('log')->error($e->getMessage()); - app('log')->error(sprintf('Could not parse search: "%s".', $query)); + Log::error($e->getMessage()); + Log::error(sprintf('Could not parse search: "%s".', $query)); throw new FireflyException(sprintf('Invalid search value "%s". See the logs.', e($query)), 0, $e); } @@ -87,7 +87,7 @@ class GdbotsQueryParser implements QueryParserInterface return new NodeGroup( array_map( - fn (GdbotsNode\Node $subNode) => $this->convertNode($subNode), + $this->convertNode(...), $node->getNodes() ) ); diff --git a/app/Support/Steam.php b/app/Support/Steam.php index ebab95b7ae..dde23d2087 100644 --- a/app/Support/Steam.php +++ b/app/Support/Steam.php @@ -23,6 +23,7 @@ declare(strict_types=1); namespace FireflyIII\Support; +use Deprecated; use Carbon\Carbon; use Exception; use FireflyIII\Exceptions\FireflyException; @@ -78,7 +79,7 @@ class Steam $currency = $currencies[$account->id]; // second array - $accountSums = array_filter($arrayOfSums, fn ($entry) => $entry['account_id'] === $account->id); + $accountSums = array_filter($arrayOfSums, fn (array $entry): bool => $entry['account_id'] === $account->id); if (0 === count($accountSums)) { $result[$account->id] = $return; @@ -289,21 +290,21 @@ class Steam return str_replace($search, '', $string); } - /** - * @deprecated - * By default this method returns "smaller than or equal to", so be careful with END OF DAY. - * If you need end of day balance, use "inclusive = false". - * - * Returns the balance of an account at exact moment given. Array with at least one value. - * Always returns: - * "balance": balance in the account's currency OR user's primary currency if the account has no currency - * "EUR": balance in EUR (or whatever currencies the account has balance in) - * - * If the user has $convertToPrimary: - * "balance": balance in the account's currency OR user's primary currency if the account has no currency - * --> "pc_balance": balance in the user's primary currency, with all amounts converted to the primary currency. - * "EUR": balance in EUR (or whatever currencies the account has balance in) - */ + #[Deprecated(message: <<<'TXT' + + By default this method returns "smaller than or equal to", so be careful with END OF DAY. + If you need end of day balance, use "inclusive = false". + + Returns the balance of an account at exact moment given. Array with at least one value. + Always returns: + "balance": balance in the account's currency OR user's primary currency if the account has no currency + "EUR": balance in EUR (or whatever currencies the account has balance in) + + If the user has $convertToPrimary: + "balance": balance in the account's currency OR user's primary currency if the account has no currency + --> "pc_balance": balance in the user's primary currency, with all amounts converted to the primary currency. + "EUR": balance in EUR (or whatever currencies the account has balance in) + TXT)] public function finalAccountBalance(Account $account, Carbon $date, ?TransactionCurrency $primary = null, ?bool $convertToPrimary = null, bool $inclusive = true): array { diff --git a/app/Support/System/GeneratesInstallationId.php b/app/Support/System/GeneratesInstallationId.php index 732237214f..32ca760483 100644 --- a/app/Support/System/GeneratesInstallationId.php +++ b/app/Support/System/GeneratesInstallationId.php @@ -24,6 +24,7 @@ declare(strict_types=1); namespace FireflyIII\Support\System; +use Illuminate\Support\Facades\Log; use FireflyIII\Exceptions\FireflyException; use Ramsey\Uuid\Uuid; @@ -37,7 +38,7 @@ trait GeneratesInstallationId try { $config = app('fireflyconfig')->get('installation_id'); } catch (FireflyException) { - app('log')->info('Could not create or generate installation ID. Do not continue.'); + Log::info('Could not create or generate installation ID. Do not continue.'); return; } @@ -50,7 +51,7 @@ trait GeneratesInstallationId if (null === $config) { $uuid4 = Uuid::uuid4(); $uniqueId = (string)$uuid4; - app('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); } } diff --git a/app/Support/System/OAuthKeys.php b/app/Support/System/OAuthKeys.php index 0f66372a69..a41c56085b 100644 --- a/app/Support/System/OAuthKeys.php +++ b/app/Support/System/OAuthKeys.php @@ -24,6 +24,7 @@ declare(strict_types=1); namespace FireflyIII\Support\System; +use Illuminate\Support\Facades\Log; use FireflyIII\Exceptions\FireflyException; use FireflyIII\Support\Facades\FireflyConfig; use Illuminate\Contracts\Encryption\DecryptException; @@ -69,15 +70,11 @@ class OAuthKeys $privateKey = (string)FireflyConfig::get(self::PRIVATE_KEY)?->data; $publicKey = (string)FireflyConfig::get(self::PUBLIC_KEY)?->data; } catch (ContainerExceptionInterface|FireflyException|NotFoundExceptionInterface $e) { - app('log')->error(sprintf('Could not validate keysInDatabase(): %s', $e->getMessage())); - app('log')->error($e->getTraceAsString()); + Log::error(sprintf('Could not validate keysInDatabase(): %s', $e->getMessage())); + Log::error($e->getTraceAsString()); } } - if ('' !== $privateKey && '' !== $publicKey) { - return true; - } - - return false; + return '' !== $privateKey && '' !== $publicKey; } /** @@ -95,8 +92,8 @@ class OAuthKeys $privateContent = Crypt::decrypt($privateKey); $publicContent = Crypt::decrypt($publicKey); } catch (DecryptException $e) { - app('log')->error('Could not decrypt pub/private keypair.'); - app('log')->error($e->getMessage()); + Log::error('Could not decrypt pub/private keypair.'); + Log::error($e->getMessage()); // delete config vars from DB: FireflyConfig::delete(self::PRIVATE_KEY); diff --git a/app/Support/Twig/General.php b/app/Support/Twig/General.php index 840b7353d5..7ff9b09f3e 100644 --- a/app/Support/Twig/General.php +++ b/app/Support/Twig/General.php @@ -104,7 +104,7 @@ class General extends AbstractExtension { return new TwigFunction( 'activeRoutePartialObjectType', - static function ($context): string { + static function (array $context): string { [, $route, $objectType] = func_get_args(); $activeObjectType = $context['objectType'] ?? false; @@ -292,11 +292,7 @@ class General extends AbstractExtension 'hasRole', static function (string $role): bool { $repository = app(UserRepositoryInterface::class); - if ($repository->hasRole(auth()->user(), $role)) { - return true; - } - - return false; + return $repository->hasRole(auth()->user(), $role); } ); } diff --git a/app/Support/Twig/Rule.php b/app/Support/Twig/Rule.php index ea60a67a3e..afd1d49bb4 100644 --- a/app/Support/Twig/Rule.php +++ b/app/Support/Twig/Rule.php @@ -37,7 +37,7 @@ class Rule extends AbstractExtension { return new TwigFunction( 'allRuleActions', - static function () { + static function (): array { // array of valid values for actions $ruleActions = array_keys(Config::get('firefly.rule-actions')); $possibleActions = []; @@ -56,7 +56,7 @@ class Rule extends AbstractExtension { return new TwigFunction( 'allJournalTriggers', - static fn () => [ + static fn (): array => [ 'store-journal' => (string)trans('firefly.rule_trigger_store_journal'), 'update-journal' => (string)trans('firefly.rule_trigger_update_journal'), 'manual-activation' => (string)trans('firefly.rule_trigger_manual'), @@ -68,7 +68,7 @@ class Rule extends AbstractExtension { return new TwigFunction( 'allRuleTriggers', - static function () { + static function (): array { $ruleTriggers = array_keys(config('search.operators')); $possibleTriggers = []; foreach ($ruleTriggers as $key) { diff --git a/app/Support/Twig/TransactionGroupTwig.php b/app/Support/Twig/TransactionGroupTwig.php index 3033a84872..74c8199469 100644 --- a/app/Support/Twig/TransactionGroupTwig.php +++ b/app/Support/Twig/TransactionGroupTwig.php @@ -24,6 +24,7 @@ declare(strict_types=1); namespace FireflyIII\Support\Twig; +use Carbon\CarbonInterface; use Carbon\Carbon; use FireflyIII\Enums\AccountTypeEnum; use FireflyIII\Enums\TransactionTypeEnum; @@ -80,7 +81,7 @@ class TransactionGroupTwig extends AbstractExtension { return new TwigFunction( 'journalGetMetaDate', - static function (int $journalId, string $metaField) { + static function (int $journalId, string $metaField): CarbonInterface|Carbon { /** @var null|TransactionJournalMeta $entry */ $entry = DB::table('journal_meta') ->where('name', $metaField) @@ -122,7 +123,7 @@ class TransactionGroupTwig extends AbstractExtension { return new TwigFunction( 'journalHasMeta', - static function (int $journalId, string $metaField) { + static function (int $journalId, string $metaField): bool { $count = DB::table('journal_meta') ->where('name', $metaField) ->where('transaction_journal_id', $journalId) diff --git a/app/Support/Twig/Translation.php b/app/Support/Twig/Translation.php index d316895ed7..fca8a41fbb 100644 --- a/app/Support/Twig/Translation.php +++ b/app/Support/Twig/Translation.php @@ -23,6 +23,7 @@ declare(strict_types=1); namespace FireflyIII\Support\Twig; +use Illuminate\Contracts\Translation\Translator; use Override; use Twig\Extension\AbstractExtension; use Twig\TwigFilter; @@ -39,7 +40,7 @@ class Translation extends AbstractExtension return [ new TwigFilter( '_', - static fn ($name) => (string)trans(sprintf('firefly.%s', $name)), + static fn (string $name) => (string)trans(sprintf('firefly.%s', $name)), ['is_safe' => ['html']] ), ]; @@ -58,7 +59,7 @@ class Translation extends AbstractExtension { return new TwigFunction( 'journalLinkTranslation', - static function (string $direction, string $original) { + static function (string $direction, string $original): string|Translator|array { $key = sprintf('firefly.%s_%s', $original, $direction); $translation = trans($key); if ($key === $translation) { @@ -75,7 +76,7 @@ class Translation extends AbstractExtension { return new TwigFunction( '__', - static function (string $key) { + static function (string $key): string|Translator|array { $translation = trans($key); if ($key === $translation) { return $key; diff --git a/app/TransactionRules/Actions/AddTag.php b/app/TransactionRules/Actions/AddTag.php index 3823f7721f..d5e25c8be9 100644 --- a/app/TransactionRules/Actions/AddTag.php +++ b/app/TransactionRules/Actions/AddTag.php @@ -23,6 +23,7 @@ declare(strict_types=1); namespace FireflyIII\TransactionRules\Actions; +use Illuminate\Support\Facades\Log; use FireflyIII\Events\Model\Rule\RuleActionFailedOnArray; use FireflyIII\Events\TriggeredAuditLog; use FireflyIII\Factory\TagFactory; @@ -68,7 +69,7 @@ class AddTag implements ActionInterface if (0 === $count) { // add to journal: DB::table('tag_transaction_journal')->insert(['tag_id' => $tag->id, 'transaction_journal_id' => $journal['transaction_journal_id']]); - app('log')->debug(sprintf('RuleAction AddTag. Added tag #%d ("%s") to journal %d.', $tag->id, $tag->tag, $journal['transaction_journal_id'])); + Log::debug(sprintf('RuleAction AddTag. Added tag #%d ("%s") to journal %d.', $tag->id, $tag->tag, $journal['transaction_journal_id'])); /** @var TransactionJournal $object */ $object = TransactionJournal::find($journal['transaction_journal_id']); @@ -78,7 +79,7 @@ class AddTag implements ActionInterface return true; } - app('log')->debug( + Log::debug( sprintf('RuleAction AddTag fired but tag %d ("%s") was already added to journal %d.', $tag->id, $tag->tag, $journal['transaction_journal_id']) ); event(new RuleActionFailedOnArray($this->action, $journal, trans('rules.tag_already_added', ['tag' => $tagName]))); diff --git a/app/TransactionRules/Actions/AppendDescriptionToNotes.php b/app/TransactionRules/Actions/AppendDescriptionToNotes.php index 952d27fd3a..bff3b7b292 100644 --- a/app/TransactionRules/Actions/AppendDescriptionToNotes.php +++ b/app/TransactionRules/Actions/AppendDescriptionToNotes.php @@ -24,6 +24,7 @@ declare(strict_types=1); namespace FireflyIII\TransactionRules\Actions; +use Illuminate\Support\Facades\Log; use FireflyIII\Events\Model\Rule\RuleActionFailedOnArray; use FireflyIII\Events\TriggeredAuditLog; use FireflyIII\Models\Note; @@ -51,7 +52,7 @@ class AppendDescriptionToNotes implements ActionInterface /** @var null|TransactionJournal $object */ $object = TransactionJournal::where('user_id', $journal['user_id'])->find($journal['transaction_journal_id']); if (null === $object) { - app('log')->error(sprintf('No journal #%d belongs to user #%d.', $journal['transaction_journal_id'], $journal['user_id'])); + Log::error(sprintf('No journal #%d belongs to user #%d.', $journal['transaction_journal_id'], $journal['user_id'])); event(new RuleActionFailedOnArray($this->action, $journal, (string) trans('rules.journal_other_user'))); return false; diff --git a/app/TransactionRules/Actions/AppendNotes.php b/app/TransactionRules/Actions/AppendNotes.php index c27853d8ed..483accfd44 100644 --- a/app/TransactionRules/Actions/AppendNotes.php +++ b/app/TransactionRules/Actions/AppendNotes.php @@ -23,6 +23,7 @@ declare(strict_types=1); namespace FireflyIII\TransactionRules\Actions; +use Illuminate\Support\Facades\Log; use FireflyIII\Events\TriggeredAuditLog; use FireflyIII\Models\Note; use FireflyIII\Models\RuleAction; @@ -64,7 +65,7 @@ class AppendNotes implements ActionInterface /** @var TransactionJournal $object */ $object = TransactionJournal::where('user_id', $journal['user_id'])->find($journal['transaction_journal_id']); - app('log')->debug(sprintf('RuleAction AppendNotes appended "%s" to "%s".', $append, $before)); + Log::debug(sprintf('RuleAction AppendNotes appended "%s" to "%s".', $append, $before)); event(new TriggeredAuditLog($this->action->rule, $object, 'update_notes', $before, $text)); return true; diff --git a/app/TransactionRules/Actions/AppendNotesToDescription.php b/app/TransactionRules/Actions/AppendNotesToDescription.php index 86c46891b3..e9543f7f1d 100644 --- a/app/TransactionRules/Actions/AppendNotesToDescription.php +++ b/app/TransactionRules/Actions/AppendNotesToDescription.php @@ -24,6 +24,7 @@ declare(strict_types=1); namespace FireflyIII\TransactionRules\Actions; +use Illuminate\Support\Facades\Log; use FireflyIII\Events\Model\Rule\RuleActionFailedOnArray; use FireflyIII\Events\TriggeredAuditLog; use FireflyIII\Models\Note; @@ -48,20 +49,20 @@ class AppendNotesToDescription implements ActionInterface public function actOnArray(array $journal): bool { - app('log')->debug('Now in AppendNotesToDescription'); + Log::debug('Now in AppendNotesToDescription'); $this->refreshNotes($journal); /** @var null|TransactionJournal $object */ $object = TransactionJournal::where('user_id', $journal['user_id'])->find($journal['transaction_journal_id']); if (null === $object) { - app('log')->error(sprintf('No journal #%d belongs to user #%d.', $journal['transaction_journal_id'], $journal['user_id'])); + 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'))); return false; } $note = $object->notes()->first(); if (null === $note) { - app('log')->debug('Journal has no notes.'); + Log::debug('Journal has no notes.'); $note = new Note(); $note->noteable()->associate($object); $note->text = ''; @@ -71,7 +72,7 @@ class AppendNotesToDescription implements ActionInterface $before = $object->description; $object->description = trim(sprintf('%s %s', $object->description, (string) $this->clearString($note->text))); $object->save(); - app('log')->debug(sprintf('Journal description is updated to "%s".', $object->description)); + Log::debug(sprintf('Journal description is updated to "%s".', $object->description)); event(new TriggeredAuditLog($this->action->rule, $object, 'update_description', $before, $object->description)); diff --git a/app/TransactionRules/Actions/ClearBudget.php b/app/TransactionRules/Actions/ClearBudget.php index 08e7dce7fa..3d9ece4d31 100644 --- a/app/TransactionRules/Actions/ClearBudget.php +++ b/app/TransactionRules/Actions/ClearBudget.php @@ -23,6 +23,7 @@ declare(strict_types=1); namespace FireflyIII\TransactionRules\Actions; +use Illuminate\Support\Facades\Log; use FireflyIII\Events\Model\Rule\RuleActionFailedOnArray; use FireflyIII\Events\TriggeredAuditLog; use FireflyIII\Models\RuleAction; @@ -45,7 +46,7 @@ class ClearBudget implements ActionInterface $object = TransactionJournal::where('user_id', $journal['user_id'])->find($journal['transaction_journal_id']); $budget = $object->budgets()->first(); if (null === $budget) { - app('log')->debug(sprintf('RuleAction ClearBudget, no budget in journal #%d.', $journal['transaction_journal_id'])); + Log::debug(sprintf('RuleAction ClearBudget, no budget in journal #%d.', $journal['transaction_journal_id'])); event(new RuleActionFailedOnArray($this->action, $journal, trans('rules.journal_already_no_budget'))); return false; @@ -55,7 +56,7 @@ class ClearBudget implements ActionInterface event(new TriggeredAuditLog($this->action->rule, $object, 'clear_budget', $budget->name, null)); - app('log')->debug(sprintf('RuleAction ClearBudget removed all budgets from journal #%d.', $journal['transaction_journal_id'])); + Log::debug(sprintf('RuleAction ClearBudget removed all budgets from journal #%d.', $journal['transaction_journal_id'])); return true; } diff --git a/app/TransactionRules/Actions/ClearCategory.php b/app/TransactionRules/Actions/ClearCategory.php index 73fa40b3f0..05e3857bd5 100644 --- a/app/TransactionRules/Actions/ClearCategory.php +++ b/app/TransactionRules/Actions/ClearCategory.php @@ -23,6 +23,7 @@ declare(strict_types=1); namespace FireflyIII\TransactionRules\Actions; +use Illuminate\Support\Facades\Log; use FireflyIII\Events\Model\Rule\RuleActionFailedOnArray; use FireflyIII\Events\TriggeredAuditLog; use FireflyIII\Models\RuleAction; @@ -45,7 +46,7 @@ class ClearCategory implements ActionInterface $object = TransactionJournal::where('user_id', $journal['user_id'])->find($journal['transaction_journal_id']); $category = $object->categories()->first(); if (null === $category) { - app('log')->debug(sprintf('RuleAction ClearCategory, no category in journal #%d.', $journal['transaction_journal_id'])); + Log::debug(sprintf('RuleAction ClearCategory, no category in journal #%d.', $journal['transaction_journal_id'])); event(new RuleActionFailedOnArray($this->action, $journal, trans('rules.journal_already_no_category'))); return false; @@ -55,7 +56,7 @@ class ClearCategory implements ActionInterface event(new TriggeredAuditLog($this->action->rule, $object, 'clear_category', $category->name, null)); - app('log')->debug(sprintf('RuleAction ClearCategory removed all categories from journal #%d.', $journal['transaction_journal_id'])); + Log::debug(sprintf('RuleAction ClearCategory removed all categories from journal #%d.', $journal['transaction_journal_id'])); return true; } diff --git a/app/TransactionRules/Actions/ClearNotes.php b/app/TransactionRules/Actions/ClearNotes.php index 48e770012b..8e03c895c0 100644 --- a/app/TransactionRules/Actions/ClearNotes.php +++ b/app/TransactionRules/Actions/ClearNotes.php @@ -23,6 +23,7 @@ declare(strict_types=1); namespace FireflyIII\TransactionRules\Actions; +use Illuminate\Support\Facades\Log; use FireflyIII\Events\Model\Rule\RuleActionFailedOnArray; use FireflyIII\Events\TriggeredAuditLog; use FireflyIII\Models\Note; @@ -48,7 +49,7 @@ class ClearNotes implements ActionInterface /** @var null|Note $notes */ $notes = $object->notes()->first(); if (null === $notes) { - app('log')->debug(sprintf('RuleAction ClearNotes, journal #%d has no notes.', $journal['transaction_journal_id'])); + Log::debug(sprintf('RuleAction ClearNotes, journal #%d has no notes.', $journal['transaction_journal_id'])); event(new RuleActionFailedOnArray($this->action, $journal, trans('rules.journal_already_no_notes'))); return false; @@ -60,7 +61,7 @@ class ClearNotes implements ActionInterface ->where('noteable_type', TransactionJournal::class) ->delete() ; - app('log')->debug(sprintf('RuleAction ClearNotes removed all notes from journal #%d.', $journal['transaction_journal_id'])); + Log::debug(sprintf('RuleAction ClearNotes removed all notes from journal #%d.', $journal['transaction_journal_id'])); event(new TriggeredAuditLog($this->action->rule, $object, 'clear_notes', $before, null)); diff --git a/app/TransactionRules/Actions/ConvertToDeposit.php b/app/TransactionRules/Actions/ConvertToDeposit.php index b61599190d..cb95871410 100644 --- a/app/TransactionRules/Actions/ConvertToDeposit.php +++ b/app/TransactionRules/Actions/ConvertToDeposit.php @@ -24,6 +24,7 @@ declare(strict_types=1); namespace FireflyIII\TransactionRules\Actions; +use Illuminate\Support\Facades\Log; use FireflyIII\Enums\AccountTypeEnum; use FireflyIII\Enums\TransactionTypeEnum; use FireflyIII\Events\Model\Rule\RuleActionFailedOnArray; @@ -56,36 +57,36 @@ class ConvertToDeposit implements ActionInterface /** @var null|TransactionJournal $object */ $object = TransactionJournal::where('user_id', $journal['user_id'])->find($journal['transaction_journal_id']); if (null === $object) { - app('log')->error(sprintf('Cannot find journal #%d, cannot convert to deposit.', $journal['transaction_journal_id'])); + Log::error(sprintf('Cannot find journal #%d, cannot convert to deposit.', $journal['transaction_journal_id'])); event(new RuleActionFailedOnArray($this->action, $journal, trans('rules.journal_not_found'))); return false; } $groupCount = TransactionJournal::where('transaction_group_id', $journal['transaction_group_id'])->count(); if ($groupCount > 1) { - app('log')->error(sprintf('Group #%d has more than one transaction in it, cannot convert to deposit.', $journal['transaction_group_id'])); + Log::error(sprintf('Group #%d has more than one transaction in it, cannot convert to deposit.', $journal['transaction_group_id'])); event(new RuleActionFailedOnArray($this->action, $journal, trans('rules.split_group'))); return false; } - app('log')->debug(sprintf('Convert journal #%d to deposit.', $journal['transaction_journal_id'])); + Log::debug(sprintf('Convert journal #%d to deposit.', $journal['transaction_journal_id'])); $type = $object->transactionType->type; if (TransactionTypeEnum::DEPOSIT->value === $type) { - app('log')->error(sprintf('Journal #%d is already a deposit (rule #%d).', $journal['transaction_journal_id'], $this->action->rule_id)); + Log::error(sprintf('Journal #%d is already a deposit (rule #%d).', $journal['transaction_journal_id'], $this->action->rule_id)); event(new RuleActionFailedOnArray($this->action, $journal, trans('rules.is_already_deposit'))); return false; } if (TransactionTypeEnum::WITHDRAWAL->value === $type) { - app('log')->debug('Going to transform a withdrawal to a deposit.'); + Log::debug('Going to transform a withdrawal to a deposit.'); try { $res = $this->convertWithdrawalArray($object, $actionValue); } catch (FireflyException $e) { - app('log')->debug('Could not convert withdrawal to deposit.'); - app('log')->error($e->getMessage()); + Log::debug('Could not convert withdrawal to deposit.'); + Log::error($e->getMessage()); event(new RuleActionFailedOnArray($this->action, $journal, trans('rules.complex_error'))); return false; @@ -96,13 +97,13 @@ class ConvertToDeposit implements ActionInterface return $res; } if (TransactionTypeEnum::TRANSFER->value === $type) { - app('log')->debug('Going to transform a transfer to a deposit.'); + Log::debug('Going to transform a transfer to a deposit.'); try { $res = $this->convertTransferArray($object, $actionValue); } catch (FireflyException $e) { - app('log')->debug('Could not convert transfer to deposit.'); - app('log')->error($e->getMessage()); + Log::debug('Could not convert transfer to deposit.'); + Log::error($e->getMessage()); event(new RuleActionFailedOnArray($this->action, $journal, trans('rules.complex_error'))); return false; @@ -147,7 +148,7 @@ class ConvertToDeposit implements ActionInterface $opposingAccount = $factory->findOrCreate($opposingName, AccountTypeEnum::REVENUE->value); } - app('log')->debug(sprintf('ConvertToDeposit. Action value is "%s", new opposing name is "%s"', $actionValue, $opposingAccount->name)); + Log::debug(sprintf('ConvertToDeposit. Action value is "%s", new opposing name is "%s"', $actionValue, $opposingAccount->name)); // update the source transaction and put in the new revenue ID. DB::table('transactions') @@ -171,7 +172,7 @@ class ConvertToDeposit implements ActionInterface ->update(['transaction_type_id' => $newType->id, 'bill_id' => null]) ; - app('log')->debug('Converted withdrawal to deposit.'); + Log::debug('Converted withdrawal to deposit.'); return true; } @@ -235,7 +236,7 @@ class ConvertToDeposit implements ActionInterface $opposingAccount = $factory->findOrCreate($opposingName, AccountTypeEnum::REVENUE->value); } - app('log')->debug(sprintf('ConvertToDeposit. Action value is "%s", revenue name is "%s"', $actionValue, $opposingAccount->name)); + Log::debug(sprintf('ConvertToDeposit. Action value is "%s", revenue name is "%s"', $actionValue, $opposingAccount->name)); // update source transaction(s) to be revenue account DB::table('transactions') @@ -252,7 +253,7 @@ class ConvertToDeposit implements ActionInterface ->update(['transaction_type_id' => $newType->id, 'bill_id' => null]) ; - app('log')->debug('Converted transfer to deposit.'); + Log::debug('Converted transfer to deposit.'); return true; } diff --git a/app/TransactionRules/Actions/ConvertToTransfer.php b/app/TransactionRules/Actions/ConvertToTransfer.php index ba613d795f..0e4a7726b7 100644 --- a/app/TransactionRules/Actions/ConvertToTransfer.php +++ b/app/TransactionRules/Actions/ConvertToTransfer.php @@ -24,6 +24,7 @@ declare(strict_types=1); namespace FireflyIII\TransactionRules\Actions; +use Illuminate\Support\Facades\Log; use FireflyIII\Enums\TransactionTypeEnum; use FireflyIII\Events\Model\Rule\RuleActionFailedOnArray; use FireflyIII\Events\Model\Rule\RuleActionFailedOnObject; @@ -59,14 +60,14 @@ class ConvertToTransfer implements ActionInterface /** @var null|TransactionJournal $object */ $object = TransactionJournal::where('user_id', $journal['user_id'])->find($journal['transaction_journal_id']); if (null === $object) { - app('log')->error(sprintf('Cannot find journal #%d, cannot convert to transfer.', $journal['transaction_journal_id'])); + Log::error(sprintf('Cannot find journal #%d, cannot convert to transfer.', $journal['transaction_journal_id'])); event(new RuleActionFailedOnArray($this->action, $journal, trans('rules.journal_not_found'))); return false; } $groupCount = TransactionJournal::where('transaction_group_id', $journal['transaction_group_id'])->count(); if ($groupCount > 1) { - app('log')->error(sprintf('Group #%d has more than one transaction in it, cannot convert to transfer.', $journal['transaction_group_id'])); + Log::error(sprintf('Group #%d has more than one transaction in it, cannot convert to transfer.', $journal['transaction_group_id'])); event(new RuleActionFailedOnArray($this->action, $journal, trans('rules.split_group'))); return false; @@ -76,7 +77,7 @@ class ConvertToTransfer implements ActionInterface $user = $object->user; $journalId = $object->id; if (TransactionTypeEnum::TRANSFER->value === $type) { - app('log')->error( + Log::error( sprintf('Journal #%d is already a transfer so cannot be converted (rule #%d).', $object->id, $this->action->rule_id) ); event(new RuleActionFailedOnArray($this->action, $journal, trans('rules.is_already_transfer'))); @@ -105,7 +106,7 @@ class ConvertToTransfer implements ActionInterface $opposing = $repository->findByName($accountName, [$expectedType]); if (null === $opposing) { - app('log')->error( + Log::error( sprintf( 'Journal #%d cannot be converted because no valid %s account with name "%s" exists (rule #%d).', $expectedType, @@ -120,36 +121,36 @@ class ConvertToTransfer implements ActionInterface } if (TransactionTypeEnum::WITHDRAWAL->value === $type) { - app('log')->debug('Going to transform a withdrawal to a transfer.'); + Log::debug('Going to transform a withdrawal to a transfer.'); try { $res = $this->convertWithdrawalArray($object, $opposing); } catch (FireflyException $e) { - app('log')->debug('Could not convert withdrawal to transfer.'); - app('log')->error($e->getMessage()); + Log::debug('Could not convert withdrawal to transfer.'); + Log::error($e->getMessage()); event(new RuleActionFailedOnArray($this->action, $journal, trans('rules.complex_error'))); return false; } - if (false !== $res) { + if ($res) { event(new TriggeredAuditLog($this->action->rule, $object, 'update_transaction_type', TransactionTypeEnum::WITHDRAWAL->value, TransactionTypeEnum::TRANSFER->value)); } return $res; } // can only be a deposit at this point. - app('log')->debug('Going to transform a deposit to a transfer.'); + Log::debug('Going to transform a deposit to a transfer.'); try { $res = $this->convertDepositArray($object, $opposing); } catch (FireflyException $e) { - app('log')->debug('Could not convert deposit to transfer.'); - app('log')->error($e->getMessage()); + Log::debug('Could not convert deposit to transfer.'); + Log::error($e->getMessage()); event(new RuleActionFailedOnArray($this->action, $journal, trans('rules.complex_error'))); return false; } - if (false !== $res) { + if ($res) { event(new TriggeredAuditLog($this->action->rule, $object, 'update_transaction_type', TransactionTypeEnum::DEPOSIT->value, TransactionTypeEnum::TRANSFER->value)); } @@ -161,7 +162,7 @@ class ConvertToTransfer implements ActionInterface /** @var null|TransactionJournal $journal */ $journal = TransactionJournal::find($journalId); if (null === $journal) { - app('log')->error(sprintf('Journal #%d does not exist. Cannot convert to transfer.', $journalId)); + Log::error(sprintf('Journal #%d does not exist. Cannot convert to transfer.', $journalId)); return ''; } @@ -174,7 +175,7 @@ class ConvertToTransfer implements ActionInterface /** @var null|TransactionJournal $journal */ $journal = TransactionJournal::find($journalId); if (null === $journal) { - app('log')->error(sprintf('Journal #%d does not exist. Cannot convert to transfer.', $journalId)); + Log::error(sprintf('Journal #%d does not exist. Cannot convert to transfer.', $journalId)); return ''; } @@ -193,7 +194,7 @@ class ConvertToTransfer implements ActionInterface { $sourceAccount = $this->getSourceAccount($journal); if ($sourceAccount->id === $opposing->id) { - app('log')->error( + Log::error( vsprintf( 'Journal #%d has already has "%s" as a source asset. ConvertToTransfer failed. (rule #%d).', [$journal->id, $opposing->name, $this->action->rule_id] @@ -219,7 +220,7 @@ class ConvertToTransfer implements ActionInterface ->update(['transaction_type_id' => $newType->id, 'bill_id' => null]) ; - app('log')->debug('Converted withdrawal to transfer.'); + Log::debug('Converted withdrawal to transfer.'); return true; } @@ -248,7 +249,7 @@ class ConvertToTransfer implements ActionInterface { $destAccount = $this->getDestinationAccount($journal); if ($destAccount->id === $opposing->id) { - app('log')->error( + Log::error( vsprintf( 'Journal #%d has already has "%s" as a destination asset. ConvertToTransfer failed. (rule #%d).', [$journal->id, $opposing->name, $this->action->rule_id] @@ -274,7 +275,7 @@ class ConvertToTransfer implements ActionInterface ->update(['transaction_type_id' => $newType->id, 'bill_id' => null]) ; - app('log')->debug('Converted deposit to transfer.'); + Log::debug('Converted deposit to transfer.'); return true; } diff --git a/app/TransactionRules/Actions/ConvertToWithdrawal.php b/app/TransactionRules/Actions/ConvertToWithdrawal.php index 61fba99de4..803163ca83 100644 --- a/app/TransactionRules/Actions/ConvertToWithdrawal.php +++ b/app/TransactionRules/Actions/ConvertToWithdrawal.php @@ -24,6 +24,7 @@ declare(strict_types=1); namespace FireflyIII\TransactionRules\Actions; +use Illuminate\Support\Facades\Log; use FireflyIII\Enums\AccountTypeEnum; use FireflyIII\Enums\TransactionTypeEnum; use FireflyIII\Events\Model\Rule\RuleActionFailedOnArray; @@ -56,14 +57,14 @@ class ConvertToWithdrawal implements ActionInterface /** @var null|TransactionJournal $object */ $object = TransactionJournal::where('user_id', $journal['user_id'])->find($journal['transaction_journal_id']); if (null === $object) { - app('log')->error(sprintf('Cannot find journal #%d, cannot convert to withdrawal.', $journal['transaction_journal_id'])); + Log::error(sprintf('Cannot find journal #%d, cannot convert to withdrawal.', $journal['transaction_journal_id'])); event(new RuleActionFailedOnArray($this->action, $journal, trans('rules.journal_not_found'))); return false; } $groupCount = TransactionJournal::where('transaction_group_id', $journal['transaction_group_id'])->count(); if ($groupCount > 1) { - app('log')->error(sprintf('Group #%d has more than one transaction in it, cannot convert to withdrawal.', $journal['transaction_group_id'])); + Log::error(sprintf('Group #%d has more than one transaction in it, cannot convert to withdrawal.', $journal['transaction_group_id'])); event(new RuleActionFailedOnArray($this->action, $journal, trans('rules.split_group'))); return false; @@ -71,7 +72,7 @@ class ConvertToWithdrawal implements ActionInterface $type = $object->transactionType->type; if (TransactionTypeEnum::WITHDRAWAL->value === $type) { - app('log')->error(sprintf('Journal #%d is already a withdrawal (rule #%d).', $journal['transaction_journal_id'], $this->action->rule_id)); + Log::error(sprintf('Journal #%d is already a withdrawal (rule #%d).', $journal['transaction_journal_id'], $this->action->rule_id)); event(new RuleActionFailedOnArray($this->action, $journal, trans('rules.is_already_withdrawal'))); return false; @@ -82,13 +83,13 @@ class ConvertToWithdrawal implements ActionInterface return false; } if (TransactionTypeEnum::DEPOSIT->value === $type) { - app('log')->debug('Going to transform a deposit to a withdrawal.'); + Log::debug('Going to transform a deposit to a withdrawal.'); try { $res = $this->convertDepositArray($object, $actionValue); } catch (FireflyException $e) { - app('log')->debug('Could not convert transfer to deposit.'); - app('log')->error($e->getMessage()); + Log::debug('Could not convert transfer to deposit.'); + Log::error($e->getMessage()); event(new RuleActionFailedOnArray($this->action, $journal, trans('rules.complex_error'))); return false; @@ -98,13 +99,13 @@ class ConvertToWithdrawal implements ActionInterface return $res; } // can only be transfer at this point. - app('log')->debug('Going to transform a transfer to a withdrawal.'); + Log::debug('Going to transform a transfer to a withdrawal.'); try { $res = $this->convertTransferArray($object, $actionValue); } catch (FireflyException $e) { - app('log')->debug('Could not convert transfer to deposit.'); - app('log')->error($e->getMessage()); + Log::debug('Could not convert transfer to deposit.'); + Log::error($e->getMessage()); event(new RuleActionFailedOnArray($this->action, $journal, trans('rules.complex_error'))); return false; @@ -141,7 +142,7 @@ class ConvertToWithdrawal implements ActionInterface $opposingAccount = $factory->findOrCreate($opposingName, AccountTypeEnum::EXPENSE->value); } - app('log')->debug(sprintf('ConvertToWithdrawal. Action value is "%s", expense name is "%s"', $actionValue, $opposingName)); + Log::debug(sprintf('ConvertToWithdrawal. Action value is "%s", expense name is "%s"', $actionValue, $opposingName)); // update source transaction(s) to be the original destination account DB::table('transactions') @@ -164,7 +165,7 @@ class ConvertToWithdrawal implements ActionInterface ->update(['transaction_type_id' => $newType->id]) ; - app('log')->debug('Converted deposit to withdrawal.'); + Log::debug('Converted deposit to withdrawal.'); return true; } @@ -227,7 +228,7 @@ class ConvertToWithdrawal implements ActionInterface $opposingAccount = $factory->findOrCreate($opposingName, AccountTypeEnum::EXPENSE->value); } - app('log')->debug(sprintf('ConvertToWithdrawal. Action value is "%s", destination name is "%s"', $actionValue, $opposingName)); + Log::debug(sprintf('ConvertToWithdrawal. Action value is "%s", destination name is "%s"', $actionValue, $opposingName)); // update destination transaction(s) to be new expense account. DB::table('transactions') @@ -243,7 +244,7 @@ class ConvertToWithdrawal implements ActionInterface ->update(['transaction_type_id' => $newType->id]) ; - app('log')->debug('Converted transfer to withdrawal.'); + Log::debug('Converted transfer to withdrawal.'); return true; } diff --git a/app/TransactionRules/Actions/DeleteTransaction.php b/app/TransactionRules/Actions/DeleteTransaction.php index fec4cb3ad4..530d3967de 100644 --- a/app/TransactionRules/Actions/DeleteTransaction.php +++ b/app/TransactionRules/Actions/DeleteTransaction.php @@ -23,6 +23,7 @@ declare(strict_types=1); namespace FireflyIII\TransactionRules\Actions; +use Illuminate\Support\Facades\Log; use FireflyIII\Events\TriggeredAuditLog; use FireflyIII\Models\RuleAction; use FireflyIII\Models\TransactionGroup; @@ -46,7 +47,7 @@ class DeleteTransaction implements ActionInterface // destroy entire group. if (1 === $count) { - app('log')->debug( + Log::debug( sprintf( 'RuleAction DeleteTransaction DELETED the entire transaction group of journal #%d ("%s").', $journal['transaction_journal_id'], @@ -63,7 +64,7 @@ class DeleteTransaction implements ActionInterface return true; } - app('log')->debug( + Log::debug( sprintf('RuleAction DeleteTransaction DELETED transaction journal #%d ("%s").', $journal['transaction_journal_id'], $journal['description']) ); diff --git a/app/TransactionRules/Actions/MoveDescriptionToNotes.php b/app/TransactionRules/Actions/MoveDescriptionToNotes.php index 62711bf5e6..9d33d00438 100644 --- a/app/TransactionRules/Actions/MoveDescriptionToNotes.php +++ b/app/TransactionRules/Actions/MoveDescriptionToNotes.php @@ -24,6 +24,7 @@ declare(strict_types=1); namespace FireflyIII\TransactionRules\Actions; +use Illuminate\Support\Facades\Log; use FireflyIII\Events\Model\Rule\RuleActionFailedOnArray; use FireflyIII\Events\TriggeredAuditLog; use FireflyIII\Models\Note; @@ -46,7 +47,7 @@ class MoveDescriptionToNotes implements ActionInterface /** @var null|TransactionJournal $object */ $object = TransactionJournal::where('user_id', $journal['user_id'])->find($journal['transaction_journal_id']); if (null === $object) { - app('log')->error(sprintf('No journal #%d belongs to user #%d.', $journal['transaction_journal_id'], $journal['user_id'])); + 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'))); return false; diff --git a/app/TransactionRules/Actions/MoveNotesToDescription.php b/app/TransactionRules/Actions/MoveNotesToDescription.php index 6852f5644b..26ed48c2b6 100644 --- a/app/TransactionRules/Actions/MoveNotesToDescription.php +++ b/app/TransactionRules/Actions/MoveNotesToDescription.php @@ -24,6 +24,7 @@ declare(strict_types=1); namespace FireflyIII\TransactionRules\Actions; +use Illuminate\Support\Facades\Log; use FireflyIII\Events\Model\Rule\RuleActionFailedOnArray; use FireflyIII\Events\TriggeredAuditLog; use FireflyIII\Models\RuleAction; @@ -52,7 +53,7 @@ class MoveNotesToDescription implements ActionInterface /** @var null|TransactionJournal $object */ $object = TransactionJournal::where('user_id', $journal['user_id'])->find($journal['transaction_journal_id']); if (null === $object) { - app('log')->error(sprintf('No journal #%d belongs to user #%d.', $journal['transaction_journal_id'], $journal['user_id'])); + 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'))); return false; diff --git a/app/TransactionRules/Actions/PrependNotes.php b/app/TransactionRules/Actions/PrependNotes.php index e4e8249c8b..71bdfb028e 100644 --- a/app/TransactionRules/Actions/PrependNotes.php +++ b/app/TransactionRules/Actions/PrependNotes.php @@ -23,6 +23,7 @@ declare(strict_types=1); namespace FireflyIII\TransactionRules\Actions; +use Illuminate\Support\Facades\Log; use FireflyIII\Events\TriggeredAuditLog; use FireflyIII\Models\Note; use FireflyIII\Models\RuleAction; @@ -53,7 +54,7 @@ class PrependNotes implements ActionInterface } $before = $dbNote->text; $after = $this->action->getValue($journal); - app('log')->debug(sprintf('RuleAction PrependNotes prepended "%s" to "%s".', $after, $dbNote->text)); + Log::debug(sprintf('RuleAction PrependNotes prepended "%s" to "%s".', $after, $dbNote->text)); $text = sprintf('%s%s', $after, $dbNote->text); $dbNote->text = $text; $dbNote->save(); diff --git a/app/TransactionRules/Actions/RemoveAllTags.php b/app/TransactionRules/Actions/RemoveAllTags.php index cf5d7ee783..f21a6c2254 100644 --- a/app/TransactionRules/Actions/RemoveAllTags.php +++ b/app/TransactionRules/Actions/RemoveAllTags.php @@ -23,6 +23,7 @@ declare(strict_types=1); namespace FireflyIII\TransactionRules\Actions; +use Illuminate\Support\Facades\Log; use FireflyIII\Events\Model\Rule\RuleActionFailedOnArray; use FireflyIII\Events\TriggeredAuditLog; use FireflyIII\Models\RuleAction; @@ -44,12 +45,12 @@ class RemoveAllTags implements ActionInterface DB::table('tag_transaction_journal')->where('transaction_journal_id', $journal['transaction_journal_id'])->delete(); $count = DB::table('tag_transaction_journal')->where('transaction_journal_id', $journal['transaction_journal_id'])->count(); if (0 === $count) { - app('log')->debug(sprintf('RuleAction RemoveAllTags, journal #%d has no tags.', $journal['transaction_journal_id'])); + Log::debug(sprintf('RuleAction RemoveAllTags, journal #%d has no tags.', $journal['transaction_journal_id'])); event(new RuleActionFailedOnArray($this->action, $journal, trans('rules.no_tags_to_remove'))); return false; } - app('log')->debug(sprintf('RuleAction RemoveAllTags removed all tags from journal %d.', $journal['transaction_journal_id'])); + Log::debug(sprintf('RuleAction RemoveAllTags removed all tags from journal %d.', $journal['transaction_journal_id'])); /** @var TransactionJournal $object */ $object = TransactionJournal::where('user_id', $journal['user_id'])->find($journal['transaction_journal_id']); diff --git a/app/TransactionRules/Actions/RemoveTag.php b/app/TransactionRules/Actions/RemoveTag.php index 956835b2e3..80c8f13066 100644 --- a/app/TransactionRules/Actions/RemoveTag.php +++ b/app/TransactionRules/Actions/RemoveTag.php @@ -23,6 +23,7 @@ declare(strict_types=1); namespace FireflyIII\TransactionRules\Actions; +use Illuminate\Support\Facades\Log; use FireflyIII\Events\Model\Rule\RuleActionFailedOnArray; use FireflyIII\Events\TriggeredAuditLog; use FireflyIII\Models\RuleAction; @@ -50,7 +51,7 @@ class RemoveTag implements ActionInterface // if tag does not exist, no need to continue: if (null === $tag) { - app('log')->debug( + Log::debug( sprintf('RuleAction RemoveTag tried to remove tag "%s" from journal #%d but no such tag exists.', $name, $journal['transaction_journal_id']) ); event(new RuleActionFailedOnArray($this->action, $journal, trans('rules.cannot_find_tag', ['tag' => $name]))); @@ -59,7 +60,7 @@ class RemoveTag implements ActionInterface } $count = DB::table('tag_transaction_journal')->where('transaction_journal_id', $journal['transaction_journal_id'])->where('tag_id', $tag->id)->count(); if (0 === $count) { - app('log')->debug( + Log::debug( sprintf('RuleAction RemoveTag tried to remove tag "%s" from journal #%d but no such tag is linked.', $name, $journal['transaction_journal_id']) ); event(new RuleActionFailedOnArray($this->action, $journal, trans('rules.cannot_unlink_tag', ['tag' => $name]))); @@ -67,7 +68,7 @@ class RemoveTag implements ActionInterface return false; } - app('log')->debug(sprintf('RuleAction RemoveTag removed tag #%d ("%s") from journal #%d.', $tag->id, $tag->tag, $journal['transaction_journal_id'])); + Log::debug(sprintf('RuleAction RemoveTag removed tag #%d ("%s") from journal #%d.', $tag->id, $tag->tag, $journal['transaction_journal_id'])); DB::table('tag_transaction_journal') ->where('transaction_journal_id', $journal['transaction_journal_id']) ->where('tag_id', $tag->id) diff --git a/app/TransactionRules/Actions/SetAmount.php b/app/TransactionRules/Actions/SetAmount.php index c7c2e47518..4c362e74c7 100644 --- a/app/TransactionRules/Actions/SetAmount.php +++ b/app/TransactionRules/Actions/SetAmount.php @@ -24,6 +24,7 @@ declare(strict_types=1); namespace FireflyIII\TransactionRules\Actions; +use Illuminate\Support\Facades\Log; use FireflyIII\Events\Model\Rule\RuleActionFailedOnArray; use FireflyIII\Events\TriggeredAuditLog; use FireflyIII\Models\RuleAction; @@ -47,7 +48,7 @@ class SetAmount implements ActionInterface // not on slpit transactions $groupCount = TransactionJournal::where('transaction_group_id', $journal['transaction_group_id'])->count(); if ($groupCount > 1) { - app('log')->error(sprintf('Group #%d has more than one transaction in it, cannot convert to transfer.', $journal['transaction_group_id'])); + Log::error(sprintf('Group #%d has more than one transaction in it, cannot convert to transfer.', $journal['transaction_group_id'])); event(new RuleActionFailedOnArray($this->action, $journal, trans('rules.split_group'))); return false; @@ -56,7 +57,7 @@ class SetAmount implements ActionInterface $value = $this->action->getValue($journal); if (!is_numeric($value) || 0 === bccomp($value, '0')) { - app('log')->debug(sprintf('RuleAction SetAmount, amount "%s" is not a number or is zero, will not continue.', $value)); + Log::debug(sprintf('RuleAction SetAmount, amount "%s" is not a number or is zero, will not continue.', $value)); event(new RuleActionFailedOnArray($this->action, $journal, trans('rules.journal_invalid_amount', ['amount' => $value]))); return false; diff --git a/app/TransactionRules/Actions/SetBudget.php b/app/TransactionRules/Actions/SetBudget.php index 54bb75902b..4aa0c06243 100644 --- a/app/TransactionRules/Actions/SetBudget.php +++ b/app/TransactionRules/Actions/SetBudget.php @@ -23,6 +23,7 @@ declare(strict_types=1); namespace FireflyIII\TransactionRules\Actions; +use Illuminate\Support\Facades\Log; use FireflyIII\Enums\TransactionTypeEnum; use FireflyIII\Events\Model\Rule\RuleActionFailedOnArray; use FireflyIII\Events\TriggeredAuditLog; @@ -49,7 +50,7 @@ class SetBudget implements ActionInterface $budget = $user->budgets()->where('name', $search)->first(); if (null === $budget) { - app('log')->debug( + Log::debug( sprintf( 'RuleAction SetBudget could not set budget of journal #%d to "%s" because no such budget exists.', $journal['transaction_journal_id'], @@ -62,7 +63,7 @@ class SetBudget implements ActionInterface } if (TransactionTypeEnum::WITHDRAWAL->value !== $journal['transaction_type_type']) { - app('log')->debug( + Log::debug( sprintf( 'RuleAction SetBudget could not set budget of journal #%d to "%s" because journal is a %s.', $journal['transaction_journal_id'], @@ -86,7 +87,7 @@ class SetBudget implements ActionInterface return false; } - app('log')->debug( + Log::debug( sprintf('RuleAction SetBudget set the budget of journal #%d to budget #%d ("%s").', $journal['transaction_journal_id'], $budget->id, $budget->name) ); diff --git a/app/TransactionRules/Actions/SetCategory.php b/app/TransactionRules/Actions/SetCategory.php index c546dcad1a..0ac36cd83e 100644 --- a/app/TransactionRules/Actions/SetCategory.php +++ b/app/TransactionRules/Actions/SetCategory.php @@ -23,6 +23,7 @@ declare(strict_types=1); namespace FireflyIII\TransactionRules\Actions; +use Illuminate\Support\Facades\Log; use FireflyIII\Events\Model\Rule\RuleActionFailedOnArray; use FireflyIII\Events\TriggeredAuditLog; use FireflyIII\Factory\CategoryFactory; @@ -47,7 +48,7 @@ class SetCategory implements ActionInterface $user = User::find($journal['user_id']); $search = $this->action->getValue($journal); if (null === $user) { - app('log')->error(sprintf('Journal has no valid user ID so action SetCategory("%s") cannot be applied', $search), $journal); + Log::error(sprintf('Journal has no valid user ID so action SetCategory("%s") cannot be applied', $search), $journal); event(new RuleActionFailedOnArray($this->action, $journal, trans('rules.no_such_journal'))); return false; @@ -58,7 +59,7 @@ class SetCategory implements ActionInterface $factory->setUser($user); $category = $factory->findOrCreate(null, $search); if (null === $category) { - app('log')->debug( + Log::debug( sprintf( 'RuleAction SetCategory could not set category of journal #%d to "%s" because no such category exists.', $journal['transaction_journal_id'], @@ -70,7 +71,7 @@ class SetCategory implements ActionInterface return false; } - app('log')->debug( + Log::debug( sprintf( 'RuleAction SetCategory set the category of journal #%d to category #%d ("%s").', $journal['transaction_journal_id'], diff --git a/app/TransactionRules/Actions/SetDescription.php b/app/TransactionRules/Actions/SetDescription.php index d6cc04fd6a..66c0023450 100644 --- a/app/TransactionRules/Actions/SetDescription.php +++ b/app/TransactionRules/Actions/SetDescription.php @@ -64,7 +64,7 @@ class SetDescription implements ActionInterface ->update(['description' => $after]) ; - app('log')->debug( + Log::debug( sprintf( 'RuleAction SetDescription changed the description of journal #%d from "%s" to "%s".', $journal['transaction_journal_id'], diff --git a/app/TransactionRules/Actions/SetDestinationAccount.php b/app/TransactionRules/Actions/SetDestinationAccount.php index b749889eb1..c2e71b0f24 100644 --- a/app/TransactionRules/Actions/SetDestinationAccount.php +++ b/app/TransactionRules/Actions/SetDestinationAccount.php @@ -23,6 +23,7 @@ declare(strict_types=1); namespace FireflyIII\TransactionRules\Actions; +use Illuminate\Support\Facades\Log; use FireflyIII\Enums\TransactionTypeEnum; use FireflyIII\Events\Model\Rule\RuleActionFailedOnArray; use FireflyIII\Events\TriggeredAuditLog; @@ -58,7 +59,7 @@ class SetDestinationAccount implements ActionInterface $this->repository = app(AccountRepositoryInterface::class); if (null === $object) { - app('log')->error('Could not find journal.'); + Log::error('Could not find journal.'); event(new RuleActionFailedOnArray($this->action, $journal, trans('rules.no_such_journal'))); return false; @@ -69,7 +70,7 @@ class SetDestinationAccount implements ActionInterface // if this is a transfer or a deposit, the new destination account must be an asset account or a default account, and it MUST exist: $newAccount = $this->findAssetAccount($type, $accountName); if ((TransactionTypeEnum::DEPOSIT->value === $type || TransactionTypeEnum::TRANSFER->value === $type) && !$newAccount instanceof Account) { - app('log')->error( + Log::error( sprintf( 'Cant change destination account of journal #%d because no asset account with name "%s" exists.', $object->id, @@ -85,20 +86,20 @@ class SetDestinationAccount implements ActionInterface /** @var null|Transaction $source */ $source = $object->transactions()->where('amount', '<', 0)->first(); if (null === $source) { - app('log')->error('Could not find source transaction.'); + Log::error('Could not find source transaction.'); event(new RuleActionFailedOnArray($this->action, $journal, trans('rules.cannot_find_source_transaction'))); return false; } // account must not be deleted (in the meantime): if (null === $source->account) { - app('log')->error('Could not find source transaction account.'); + Log::error('Could not find source transaction account.'); event(new RuleActionFailedOnArray($this->action, $journal, trans('rules.cannot_find_source_transaction_account'))); return false; } if ($newAccount instanceof Account && $newAccount->id === $source->account_id) { - app('log')->error( + Log::error( sprintf( 'New destination account ID #%d and current source account ID #%d are the same. Do nothing.', $newAccount->id, @@ -117,7 +118,7 @@ class SetDestinationAccount implements ActionInterface $newAccount = $this->findWithdrawalDestinationAccount($accountName); } if (!$newAccount instanceof Account) { - app('log')->error( + Log::error( sprintf( 'No destination account found for name "%s".', $accountName @@ -129,7 +130,7 @@ class SetDestinationAccount implements ActionInterface return false; } - app('log')->debug(sprintf('New destination account is #%d ("%s").', $newAccount->id, $newAccount->name)); + Log::debug(sprintf('New destination account is #%d ("%s").', $newAccount->id, $newAccount->name)); event(new TriggeredAuditLog($this->action->rule, $object, 'set_destination', null, $newAccount->name)); @@ -140,7 +141,7 @@ class SetDestinationAccount implements ActionInterface ->update(['account_id' => $newAccount->id]) ; - app('log')->debug(sprintf('Updated journal #%d (group #%d) and gave it new destination account ID.', $object->id, $object->transaction_group_id)); + Log::debug(sprintf('Updated journal #%d (group #%d) and gave it new destination account ID.', $object->id, $object->transaction_group_id)); return true; } @@ -150,7 +151,7 @@ class SetDestinationAccount implements ActionInterface // switch on type: $allowed = config(sprintf('firefly.expected_source_types.destination.%s', $type)); $allowed = is_array($allowed) ? $allowed : []; - app('log')->debug(sprintf('Check config for expected_source_types.destination.%s, result is', $type), $allowed); + Log::debug(sprintf('Check config for expected_source_types.destination.%s, result is', $type), $allowed); return $this->repository->findByName($accountName, $allowed); } @@ -170,7 +171,7 @@ class SetDestinationAccount implements ActionInterface ]; $account = $this->repository->store($data); } - app('log')->debug(sprintf('Found or created expense account #%d ("%s")', $account->id, $account->name)); + Log::debug(sprintf('Found or created expense account #%d ("%s")', $account->id, $account->name)); return $account; } diff --git a/app/TransactionRules/Actions/SetDestinationToCashAccount.php b/app/TransactionRules/Actions/SetDestinationToCashAccount.php index 967e07928d..34aa5392c3 100644 --- a/app/TransactionRules/Actions/SetDestinationToCashAccount.php +++ b/app/TransactionRules/Actions/SetDestinationToCashAccount.php @@ -24,6 +24,7 @@ declare(strict_types=1); namespace FireflyIII\TransactionRules\Actions; +use Illuminate\Support\Facades\Log; use FireflyIII\Enums\TransactionTypeEnum; use FireflyIII\Events\Model\Rule\RuleActionFailedOnArray; use FireflyIII\Events\TriggeredAuditLog; @@ -54,14 +55,14 @@ class SetDestinationToCashAccount implements ActionInterface $repository = app(AccountRepositoryInterface::class); if (null === $object) { - app('log')->error('Could not find journal.'); + Log::error('Could not find journal.'); event(new RuleActionFailedOnArray($this->action, $journal, trans('rules.no_such_journal'))); return false; } $type = $object->transactionType->type; if (TransactionTypeEnum::WITHDRAWAL->value !== $type) { - app('log')->error('Transaction must be withdrawal.'); + Log::error('Transaction must be withdrawal.'); event(new RuleActionFailedOnArray($this->action, $journal, trans('rules.not_withdrawal'))); return false; @@ -75,20 +76,20 @@ class SetDestinationToCashAccount implements ActionInterface /** @var null|Transaction $source */ $source = $object->transactions()->where('amount', '<', 0)->first(); if (null === $source) { - app('log')->error('Could not find source transaction.'); + Log::error('Could not find source transaction.'); event(new RuleActionFailedOnArray($this->action, $journal, trans('rules.cannot_find_source_transaction'))); return false; } // account must not be deleted (in the meantime): if (null === $source->account) { - app('log')->error('Could not find source transaction account.'); + Log::error('Could not find source transaction account.'); event(new RuleActionFailedOnArray($this->action, $journal, trans('rules.cannot_find_source_transaction_account'))); return false; } if ($cashAccount->id === $source->account_id) { - app('log')->error( + Log::error( sprintf( 'New destination account ID #%d and current source account ID #%d are the same. Do nothing.', $cashAccount->id, @@ -110,7 +111,7 @@ class SetDestinationToCashAccount implements ActionInterface ->update(['account_id' => $cashAccount->id]) ; - app('log')->debug(sprintf('Updated journal #%d (group #%d) and gave it new destination account ID.', $object->id, $object->transaction_group_id)); + Log::debug(sprintf('Updated journal #%d (group #%d) and gave it new destination account ID.', $object->id, $object->transaction_group_id)); return true; } diff --git a/app/TransactionRules/Actions/SetNotes.php b/app/TransactionRules/Actions/SetNotes.php index a3c144fa11..26e48501bb 100644 --- a/app/TransactionRules/Actions/SetNotes.php +++ b/app/TransactionRules/Actions/SetNotes.php @@ -23,6 +23,7 @@ declare(strict_types=1); namespace FireflyIII\TransactionRules\Actions; +use Illuminate\Support\Facades\Log; use FireflyIII\Events\TriggeredAuditLog; use FireflyIII\Models\Note; use FireflyIII\Models\RuleAction; @@ -54,7 +55,7 @@ class SetNotes implements ActionInterface $dbNote->text = $newNotes; $dbNote->save(); - app('log')->debug( + Log::debug( sprintf( 'RuleAction SetNotes changed the notes of journal #%d from "%s" to "%s".', $journal['transaction_journal_id'], diff --git a/app/TransactionRules/Actions/SetSourceAccount.php b/app/TransactionRules/Actions/SetSourceAccount.php index 3eddb9e7c7..ba6ae75d8e 100644 --- a/app/TransactionRules/Actions/SetSourceAccount.php +++ b/app/TransactionRules/Actions/SetSourceAccount.php @@ -23,6 +23,7 @@ declare(strict_types=1); namespace FireflyIII\TransactionRules\Actions; +use Illuminate\Support\Facades\Log; use FireflyIII\Enums\TransactionTypeEnum; use FireflyIII\Events\Model\Rule\RuleActionFailedOnArray; use FireflyIII\Events\TriggeredAuditLog; @@ -57,7 +58,7 @@ class SetSourceAccount implements ActionInterface $object = $user->transactionJournals()->find((int) $journal['transaction_journal_id']); $this->repository = app(AccountRepositoryInterface::class); if (null === $object) { - app('log')->error('Could not find journal.'); + Log::error('Could not find journal.'); event(new RuleActionFailedOnArray($this->action, $journal, trans('rules.no_such_journal'))); return false; @@ -68,7 +69,7 @@ class SetSourceAccount implements ActionInterface // if this is a transfer or a withdrawal, the new source account must be an asset account or a default account, and it MUST exist: $newAccount = $this->findAssetAccount($type, $accountName); if ((TransactionTypeEnum::WITHDRAWAL->value === $type || TransactionTypeEnum::TRANSFER->value === $type) && !$newAccount instanceof Account) { - app('log')->error( + Log::error( sprintf('Cant change source account of journal #%d because no asset account with name "%s" exists.', $object->id, $accountName) ); event(new RuleActionFailedOnArray($this->action, $journal, trans('rules.cannot_find_asset', ['name' => $accountName]))); @@ -80,20 +81,20 @@ class SetSourceAccount implements ActionInterface /** @var null|Transaction $destination */ $destination = $object->transactions()->where('amount', '>', 0)->first(); if (null === $destination) { - app('log')->error('Could not find destination transaction.'); + Log::error('Could not find destination transaction.'); event(new RuleActionFailedOnArray($this->action, $journal, trans('rules.cannot_find_destination_transaction'))); return false; } // account must not be deleted (in the meantime): if (null === $destination->account) { - app('log')->error('Could not find destination transaction account.'); + Log::error('Could not find destination transaction account.'); event(new RuleActionFailedOnArray($this->action, $journal, trans('rules.cannot_find_destination_transaction_account'))); return false; } if ($newAccount instanceof Account && $newAccount->id === $destination->account_id) { - app('log')->error( + Log::error( sprintf( 'New source account ID #%d and current destination account ID #%d are the same. Do nothing.', $newAccount->id, @@ -111,7 +112,7 @@ class SetSourceAccount implements ActionInterface $newAccount = $this->findDepositSourceAccount($accountName); } - app('log')->debug(sprintf('New source account is #%d ("%s").', $newAccount->id, $newAccount->name)); + Log::debug(sprintf('New source account is #%d ("%s").', $newAccount->id, $newAccount->name)); // update source transaction with new source account: DB::table('transactions') @@ -122,7 +123,7 @@ class SetSourceAccount implements ActionInterface event(new TriggeredAuditLog($this->action->rule, $object, 'set_source', null, $newAccount->name)); - app('log')->debug(sprintf('Updated journal #%d (group #%d) and gave it new source account ID.', $object->id, $object->transaction_group_id)); + Log::debug(sprintf('Updated journal #%d (group #%d) and gave it new source account ID.', $object->id, $object->transaction_group_id)); return true; } @@ -132,7 +133,7 @@ class SetSourceAccount implements ActionInterface // switch on type: $allowed = config(sprintf('firefly.expected_source_types.source.%s', $type)); $allowed = is_array($allowed) ? $allowed : []; - app('log')->debug(sprintf('Check config for expected_source_types.source.%s, result is', $type), $allowed); + Log::debug(sprintf('Check config for expected_source_types.source.%s, result is', $type), $allowed); return $this->repository->findByName($accountName, $allowed); } @@ -153,7 +154,7 @@ class SetSourceAccount implements ActionInterface ]; $account = $this->repository->store($data); } - app('log')->debug(sprintf('Found or created revenue account #%d ("%s")', $account->id, $account->name)); + Log::debug(sprintf('Found or created revenue account #%d ("%s")', $account->id, $account->name)); return $account; } diff --git a/app/TransactionRules/Actions/SetSourceToCashAccount.php b/app/TransactionRules/Actions/SetSourceToCashAccount.php index bb83c36908..9cea693e82 100644 --- a/app/TransactionRules/Actions/SetSourceToCashAccount.php +++ b/app/TransactionRules/Actions/SetSourceToCashAccount.php @@ -24,6 +24,7 @@ declare(strict_types=1); namespace FireflyIII\TransactionRules\Actions; +use Illuminate\Support\Facades\Log; use FireflyIII\Enums\TransactionTypeEnum; use FireflyIII\Events\Model\Rule\RuleActionFailedOnArray; use FireflyIII\Events\TriggeredAuditLog; @@ -54,14 +55,14 @@ class SetSourceToCashAccount implements ActionInterface $repository = app(AccountRepositoryInterface::class); if (null === $object) { - app('log')->error('Could not find journal.'); + Log::error('Could not find journal.'); event(new RuleActionFailedOnArray($this->action, $journal, trans('rules.no_such_journal'))); return false; } $type = $object->transactionType->type; if (TransactionTypeEnum::DEPOSIT->value !== $type) { - app('log')->error('Transaction must be deposit.'); + Log::error('Transaction must be deposit.'); event(new RuleActionFailedOnArray($this->action, $journal, trans('rules.not_deposit'))); return false; @@ -75,20 +76,20 @@ class SetSourceToCashAccount implements ActionInterface /** @var null|Transaction $destination */ $destination = $object->transactions()->where('amount', '>', 0)->first(); if (null === $destination) { - app('log')->error('Could not find destination transaction.'); + Log::error('Could not find destination transaction.'); event(new RuleActionFailedOnArray($this->action, $journal, trans('rules.cannot_find_destination_transaction'))); return false; } // account must not be deleted (in the meantime): if (null === $destination->account) { - app('log')->error('Could not find destination transaction account.'); + Log::error('Could not find destination transaction account.'); event(new RuleActionFailedOnArray($this->action, $journal, trans('rules.cannot_find_destination_transaction_account'))); return false; } if ($cashAccount->id === $destination->account_id) { - app('log')->error( + Log::error( sprintf( 'New source account ID #%d and current destination account ID #%d are the same. Do nothing.', $cashAccount->id, @@ -110,7 +111,7 @@ class SetSourceToCashAccount implements ActionInterface ->update(['account_id' => $cashAccount->id]) ; - app('log')->debug(sprintf('Updated journal #%d (group #%d) and gave it new source account ID.', $object->id, $object->transaction_group_id)); + Log::debug(sprintf('Updated journal #%d (group #%d) and gave it new source account ID.', $object->id, $object->transaction_group_id)); return true; } diff --git a/app/TransactionRules/Actions/SwitchAccounts.php b/app/TransactionRules/Actions/SwitchAccounts.php index e49ea4a19d..5ee4219b0d 100644 --- a/app/TransactionRules/Actions/SwitchAccounts.php +++ b/app/TransactionRules/Actions/SwitchAccounts.php @@ -24,6 +24,7 @@ declare(strict_types=1); namespace FireflyIII\TransactionRules\Actions; +use Illuminate\Support\Facades\Log; use FireflyIII\Enums\TransactionTypeEnum; use FireflyIII\Events\Model\Rule\RuleActionFailedOnArray; use FireflyIII\Events\TriggeredAuditLog; @@ -47,14 +48,14 @@ class SwitchAccounts implements ActionInterface /** @var null|TransactionJournal $object */ $object = TransactionJournal::where('user_id', $journal['user_id'])->find($journal['transaction_journal_id']); if (null === $object) { - app('log')->error(sprintf('Cannot find journal #%d, cannot switch accounts.', $journal['transaction_journal_id'])); + Log::error(sprintf('Cannot find journal #%d, cannot switch accounts.', $journal['transaction_journal_id'])); event(new RuleActionFailedOnArray($this->action, $journal, trans('rules.no_such_journal'))); return false; } $groupCount = TransactionJournal::where('transaction_group_id', $journal['transaction_group_id'])->count(); if ($groupCount > 1) { - app('log')->error(sprintf('Group #%d has more than one transaction in it, cannot switch accounts.', $journal['transaction_group_id'])); + Log::error(sprintf('Group #%d has more than one transaction in it, cannot switch accounts.', $journal['transaction_group_id'])); event(new RuleActionFailedOnArray($this->action, $journal, trans('rules.split_group'))); return false; @@ -62,7 +63,7 @@ class SwitchAccounts implements ActionInterface $type = $object->transactionType->type; if (TransactionTypeEnum::TRANSFER->value !== $type) { - app('log')->error(sprintf('Journal #%d is NOT a transfer (rule #%d), cannot switch accounts.', $journal['transaction_journal_id'], $this->action->rule_id)); + Log::error(sprintf('Journal #%d is NOT a transfer (rule #%d), cannot switch accounts.', $journal['transaction_journal_id'], $this->action->rule_id)); event(new RuleActionFailedOnArray($this->action, $journal, trans('rules.is_not_transfer'))); return false; @@ -74,7 +75,7 @@ class SwitchAccounts implements ActionInterface /** @var null|Transaction $destTransaction */ $destTransaction = $object->transactions()->where('amount', '>', 0)->first(); 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)); + Log::error(sprintf('Journal #%d has no source or destination transaction (rule #%d), cannot switch accounts.', $journal['transaction_journal_id'], $this->action->rule_id)); event(new RuleActionFailedOnArray($this->action, $journal, trans('rules.cannot_find_accounts'))); return false; diff --git a/app/TransactionRules/Engine/SearchRuleEngine.php b/app/TransactionRules/Engine/SearchRuleEngine.php index 70f55f4d24..fbebad10cd 100644 --- a/app/TransactionRules/Engine/SearchRuleEngine.php +++ b/app/TransactionRules/Engine/SearchRuleEngine.php @@ -45,9 +45,10 @@ use Illuminate\Support\Facades\Log; class SearchRuleEngine implements RuleEngineInterface { private readonly Collection $groups; - private array $operators; - private bool $refreshTriggers; - private array $resultCount; + private array $operators = []; + // always collect the triggers from the database, unless indicated otherwise. + private bool $refreshTriggers = true; + private array $resultCount = []; private readonly Collection $rules; private User $user; @@ -55,11 +56,6 @@ class SearchRuleEngine implements RuleEngineInterface { $this->rules = new Collection(); $this->groups = new Collection(); - $this->operators = []; - $this->resultCount = []; - - // always collect the triggers from the database, unless indicated otherwise. - $this->refreshTriggers = true; } public function addOperator(array $operator): void @@ -119,7 +115,7 @@ class SearchRuleEngine implements RuleEngineInterface Log::debug(sprintf('SearchRuleEngine:: add a rule trigger (no context): %s:true', $ruleTrigger->trigger_type)); $searchArray[$ruleTrigger->trigger_type][] = 'true'; } - if (true === $needsContext) { + if ($needsContext) { Log::debug(sprintf('SearchRuleEngine:: add a rule trigger (context): %s:"%s"', $ruleTrigger->trigger_type, $ruleTrigger->trigger_value)); $searchArray[$ruleTrigger->trigger_type][] = sprintf('"%s"', $ruleTrigger->trigger_value); } @@ -288,7 +284,7 @@ class SearchRuleEngine implements RuleEngineInterface // make collection unique $unique = $total->unique( - static function (array $group) { + static function (array $group): string { $str = ''; foreach ($group['transactions'] as $transaction) { $str = sprintf('%s%d', $str, $transaction['transaction_journal_id']); @@ -319,7 +315,7 @@ class SearchRuleEngine implements RuleEngineInterface /** @var Rule $rule */ foreach ($this->rules as $rule) { // @phpstan-ignore-line $result = $this->fireRule($rule); - if (true === $result && true === $rule->stop_processing) { + if ($result && true === $rule->stop_processing) { Log::debug(sprintf('Rule #%d has triggered and executed, but calls to stop processing. Since not in the context of a group, do not stop.', $rule->id)); } if (false === $result && true === $rule->stop_processing) { @@ -378,7 +374,7 @@ class SearchRuleEngine implements RuleEngineInterface $this->processResults($rule, $collection); $result = $collection->count() > 0; - if (true === $result) { + if ($result) { Log::debug(sprintf('SearchRuleEngine:: Done. Rule #%d was triggered (on %d transaction(s)).', $rule->id, $collection->count())); return true; @@ -428,7 +424,7 @@ class SearchRuleEngine implements RuleEngineInterface continue; } $break = $this->processRuleAction($ruleAction, $transaction); - if (true === $break) { + if ($break) { break; } } @@ -444,7 +440,7 @@ class SearchRuleEngine implements RuleEngineInterface $actionClass = ActionFactory::getAction($ruleAction); $result = $actionClass->actOnArray($transaction); $journalId = $transaction['transaction_journal_id'] ?? 0; - if (true === $result) { + if ($result) { $this->resultCount[$journalId] = array_key_exists($journalId, $this->resultCount) ? $this->resultCount[$journalId]++ : 1; Log::debug( sprintf( @@ -460,7 +456,7 @@ class SearchRuleEngine implements RuleEngineInterface } // pick up from the action if it actually acted or not: - if (true === $ruleAction->stop_processing && true === $result) { + if (true === $ruleAction->stop_processing && $result) { Log::debug(sprintf('Rule action "%s" reports changes AND asks to break, so break!', $ruleAction->action_type)); return true; @@ -527,7 +523,7 @@ class SearchRuleEngine implements RuleEngineInterface foreach ($rules as $rule) { Log::debug(sprintf('Going to fire rule #%d with order #%d from group #%d', $rule->id, $rule->order, $group->id)); $result = $this->fireRule($rule); - if (true === $result && true === $rule->stop_processing) { + if ($result && true === $rule->stop_processing) { Log::debug(sprintf('The rule was triggered and rule->stop_processing = true, so group #%d will stop processing further rules.', $group->id)); return; diff --git a/app/TransactionRules/Expressions/ActionExpression.php b/app/TransactionRules/Expressions/ActionExpression.php index 6e578c8444..e940f2fb5f 100644 --- a/app/TransactionRules/Expressions/ActionExpression.php +++ b/app/TransactionRules/Expressions/ActionExpression.php @@ -90,11 +90,11 @@ class ActionExpression { $this->expressionLanguage = app(ExpressionLanguage::class); - $this->isExpression = self::isExpression($this->expr); + $this->isExpression = $this->isExpression($this->expr); $this->validationError = $this->validate(); } - private static function isExpression(string $expr): bool + private function isExpression(string $expr): bool { return str_starts_with($expr, '=') && strlen($expr) > 1; } diff --git a/app/TransactionRules/Factory/ActionFactory.php b/app/TransactionRules/Factory/ActionFactory.php index 23780bce6d..c05dca063a 100644 --- a/app/TransactionRules/Factory/ActionFactory.php +++ b/app/TransactionRules/Factory/ActionFactory.php @@ -23,6 +23,7 @@ declare(strict_types=1); namespace FireflyIII\TransactionRules\Factory; +use Illuminate\Support\Facades\Log; use FireflyIII\Exceptions\FireflyException; use FireflyIII\Models\RuleAction; use FireflyIII\Support\Domain; @@ -47,7 +48,7 @@ class ActionFactory public static function getAction(RuleAction $action): ActionInterface { $class = self::getActionClass($action->action_type); - app('log')->debug(sprintf('self::getActionClass("%s") = "%s"', $action->action_type, $class)); + Log::debug(sprintf('self::getActionClass("%s") = "%s"', $action->action_type, $class)); return new $class($action); // @phpstan-ignore-line } diff --git a/app/Transformers/AbstractTransformer.php b/app/Transformers/AbstractTransformer.php index d741ba0cf7..1be605aaf1 100644 --- a/app/Transformers/AbstractTransformer.php +++ b/app/Transformers/AbstractTransformer.php @@ -24,6 +24,7 @@ declare(strict_types=1); namespace FireflyIII\Transformers; +use Deprecated; use League\Fractal\TransformerAbstract; use Symfony\Component\HttpFoundation\ParameterBag; @@ -34,17 +35,13 @@ abstract class AbstractTransformer extends TransformerAbstract { protected ParameterBag $parameters; - /** - * @deprecated - */ + #[Deprecated] final public function getParameters(): ParameterBag { return $this->parameters; } - /** - * @deprecated - */ + #[Deprecated] final public function setParameters(ParameterBag $parameters): void { $this->parameters = $parameters; diff --git a/app/Transformers/BudgetLimitTransformer.php b/app/Transformers/BudgetLimitTransformer.php index 12107e5636..edd1287ee3 100644 --- a/app/Transformers/BudgetLimitTransformer.php +++ b/app/Transformers/BudgetLimitTransformer.php @@ -51,10 +51,8 @@ class BudgetLimitTransformer extends AbstractTransformer /** * Include Budget - * - * @return Item */ - public function includeBudget(BudgetLimit $limit) + public function includeBudget(BudgetLimit $limit): Item { // enrich budget $budget = $limit->budget; diff --git a/app/Transformers/PiggyBankEventTransformer.php b/app/Transformers/PiggyBankEventTransformer.php index d5097b6136..a4fc3ea440 100644 --- a/app/Transformers/PiggyBankEventTransformer.php +++ b/app/Transformers/PiggyBankEventTransformer.php @@ -36,7 +36,7 @@ use FireflyIII\Support\Facades\Steam; class PiggyBankEventTransformer extends AbstractTransformer { private readonly TransactionCurrency $primaryCurrency; - private bool $convertToPrimary; + private readonly bool $convertToPrimary; /** * PiggyBankEventTransformer constructor. diff --git a/app/Transformers/RecurrenceTransformer.php b/app/Transformers/RecurrenceTransformer.php index d2e1bb914c..03d7058184 100644 --- a/app/Transformers/RecurrenceTransformer.php +++ b/app/Transformers/RecurrenceTransformer.php @@ -32,11 +32,6 @@ use Illuminate\Support\Facades\Log; */ class RecurrenceTransformer extends AbstractTransformer { - /** - * RecurrenceTransformer constructor. - */ - public function __construct() {} - /** * Transform the recurring transaction. */ diff --git a/app/Transformers/TransactionGroupTransformer.php b/app/Transformers/TransactionGroupTransformer.php index 93ac1558ab..86e70b36bc 100644 --- a/app/Transformers/TransactionGroupTransformer.php +++ b/app/Transformers/TransactionGroupTransformer.php @@ -259,12 +259,7 @@ class TransactionGroupTransformer extends AbstractTransformer return (string) $array[$key]; } - - if (null !== $default) { - return $default; - } - - return null; + return $default; } /** @@ -429,7 +424,7 @@ class TransactionGroupTransformer extends AbstractTransformer private function getSourceTransaction(TransactionJournal $journal): Transaction { $result = $journal->transactions->first( - static function (Transaction $transaction) { + static function (Transaction $transaction): bool { return (float) $transaction->amount < 0; // lame but it works. } ); @@ -446,7 +441,7 @@ class TransactionGroupTransformer extends AbstractTransformer private function getDestinationTransaction(TransactionJournal $journal): Transaction { $result = $journal->transactions->first( - static function (Transaction $transaction) { + static function (Transaction $transaction): bool { return (float) $transaction->amount > 0; // lame but it works } ); diff --git a/app/Transformers/UserGroupTransformer.php b/app/Transformers/UserGroupTransformer.php index 486db21253..d89ac03fe7 100644 --- a/app/Transformers/UserGroupTransformer.php +++ b/app/Transformers/UserGroupTransformer.php @@ -36,16 +36,9 @@ use Illuminate\Support\Collection; */ class UserGroupTransformer extends AbstractTransformer { - private array $inUse; - private array $memberships; - private array $membershipsVisible; - - public function __construct() - { - $this->memberships = []; - $this->membershipsVisible = []; - $this->inUse = []; - } + private array $inUse = []; + private array $memberships = []; + private array $membershipsVisible = []; public function collectMetaData(Collection $objects): Collection { diff --git a/app/Transformers/WebhookTransformer.php b/app/Transformers/WebhookTransformer.php index d402cd7852..9eace066e5 100644 --- a/app/Transformers/WebhookTransformer.php +++ b/app/Transformers/WebhookTransformer.php @@ -31,11 +31,6 @@ use FireflyIII\Models\Webhook; */ class WebhookTransformer extends AbstractTransformer { - /** - * WebhookTransformer constructor. - */ - public function __construct() {} - /** * Transform webhook. */ diff --git a/app/Validation/Account/DepositValidation.php b/app/Validation/Account/DepositValidation.php index 36cd7e7d35..574f00cb9b 100644 --- a/app/Validation/Account/DepositValidation.php +++ b/app/Validation/Account/DepositValidation.php @@ -37,9 +37,9 @@ trait DepositValidation protected function validateDepositDestination(array $array): bool { $result = null; - $accountId = array_key_exists('id', $array) ? $array['id'] : null; - $accountName = array_key_exists('name', $array) ? $array['name'] : null; - $accountIban = array_key_exists('iban', $array) ? $array['iban'] : null; + $accountId = $array['id'] ?? null; + $accountName = $array['name'] ?? null; + $accountIban = $array['iban'] ?? null; Log::debug('Now in validateDepositDestination', $array); @@ -89,10 +89,10 @@ trait DepositValidation */ protected function validateDepositSource(array $array): bool { - $accountId = array_key_exists('id', $array) ? $array['id'] : null; - $accountName = array_key_exists('name', $array) ? $array['name'] : null; - $accountIban = array_key_exists('iban', $array) ? $array['iban'] : null; - $accountNumber = array_key_exists('number', $array) ? $array['number'] : null; + $accountId = $array['id'] ?? null; + $accountName = $array['name'] ?? null; + $accountIban = $array['iban'] ?? null; + $accountNumber = $array['number'] ?? null; Log::debug('Now in validateDepositSource', $array); // null = we found nothing at all or didn't even search diff --git a/app/Validation/Account/LiabilityValidation.php b/app/Validation/Account/LiabilityValidation.php index 4c08694ecf..b66c84651b 100644 --- a/app/Validation/Account/LiabilityValidation.php +++ b/app/Validation/Account/LiabilityValidation.php @@ -24,6 +24,7 @@ declare(strict_types=1); namespace FireflyIII\Validation\Account; +use Illuminate\Support\Facades\Log; use FireflyIII\Enums\AccountTypeEnum; use FireflyIII\Models\Account; use FireflyIII\Models\AccountType; @@ -35,23 +36,23 @@ trait LiabilityValidation { protected function validateLCDestination(array $array): bool { - app('log')->debug('Now in validateLCDestination', $array); + Log::debug('Now in validateLCDestination', $array); $result = null; - $accountId = array_key_exists('id', $array) ? $array['id'] : null; - $accountName = array_key_exists('name', $array) ? $array['name'] : null; + $accountId = $array['id'] ?? null; + $accountName = $array['name'] ?? null; $validTypes = config('firefly.valid_liabilities'); // 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. if (null !== $accountId) { if (AccountTypeEnum::LIABILITY_CREDIT->value !== $this->source?->accountType?->type) { - app('log')->error('Source account is not a liability.'); + Log::error('Source account is not a liability.'); return false; } $result = $this->findExistingAccount($validTypes, $array); if (null === $result) { - app('log')->error('Destination account is not a liability.'); + Log::error('Destination account is not a liability.'); return false; } @@ -60,11 +61,11 @@ trait LiabilityValidation } if (null !== $accountName && '' !== $accountName) { - app('log')->debug('Destination ID is null, now we can assume the destination is a (new) liability credit account.'); + Log::debug('Destination ID is null, now we can assume the destination is a (new) liability credit account.'); return true; } - app('log')->error('Destination ID is null, but destination name is also NULL.'); + Log::error('Destination ID is null, but destination name is also NULL.'); return false; } @@ -74,35 +75,35 @@ trait LiabilityValidation */ protected function validateLCSource(array $array): bool { - app('log')->debug('Now in validateLCSource', $array); + Log::debug('Now in validateLCSource', $array); // if the array has an ID and ID is not null, try to find it and check type. // this account must be a liability - $accountId = array_key_exists('id', $array) ? $array['id'] : null; + $accountId = $array['id'] ?? null; if (null !== $accountId) { - app('log')->debug('Source ID is not null, assume were looking for a liability.'); + Log::debug('Source ID is not null, assume were looking for a liability.'); // find liability credit: $result = $this->findExistingAccount(config('firefly.valid_liabilities'), $array); if (null === $result) { - app('log')->error('Did not find a liability account, return false.'); + Log::error('Did not find a liability account, return false.'); return false; } - app('log')->debug(sprintf('Return true, found #%d ("%s")', $result->id, $result->name)); + Log::debug(sprintf('Return true, found #%d ("%s")', $result->id, $result->name)); $this->setSource($result); return true; } // if array has name and is not null, return true. - $accountName = array_key_exists('name', $array) ? $array['name'] : null; + $accountName = $array['name'] ?? null; $result = true; if ('' === $accountName || null === $accountName) { - app('log')->error('Array must have a name, is not the case, return false.'); + Log::error('Array must have a name, is not the case, return false.'); $result = false; } - if (true === $result) { - app('log')->error('Array has a name, return true.'); + if ($result) { + Log::error('Array has a name, return true.'); // set the source to be a (dummy) revenue account. $account = new Account(); $accountType = AccountType::whereType(AccountTypeEnum::LIABILITY_CREDIT->value)->first(); diff --git a/app/Validation/Account/OBValidation.php b/app/Validation/Account/OBValidation.php index b0633c63f9..39d2b5fc22 100644 --- a/app/Validation/Account/OBValidation.php +++ b/app/Validation/Account/OBValidation.php @@ -37,8 +37,8 @@ trait OBValidation protected function validateOBDestination(array $array): bool { $result = null; - $accountId = array_key_exists('id', $array) ? $array['id'] : null; - $accountName = array_key_exists('name', $array) ? $array['name'] : null; + $accountId = $array['id'] ?? null; + $accountName = $array['name'] ?? null; Log::debug('Now in validateOBDestination', $array); // source can be any of the following types. @@ -83,8 +83,8 @@ trait OBValidation */ protected function validateOBSource(array $array): bool { - $accountId = array_key_exists('id', $array) ? $array['id'] : null; - $accountName = array_key_exists('name', $array) ? $array['name'] : null; + $accountId = $array['id'] ?? null; + $accountName = $array['name'] ?? null; Log::debug('Now in validateOBSource', $array); $result = null; // source can be any of the following types. diff --git a/app/Validation/Account/ReconciliationValidation.php b/app/Validation/Account/ReconciliationValidation.php index 52b97201d4..91514fc092 100644 --- a/app/Validation/Account/ReconciliationValidation.php +++ b/app/Validation/Account/ReconciliationValidation.php @@ -24,6 +24,7 @@ declare(strict_types=1); namespace FireflyIII\Validation\Account; +use Illuminate\Support\Facades\Log; use FireflyIII\Models\Account; /** @@ -36,8 +37,8 @@ trait ReconciliationValidation protected function validateReconciliationDestination(array $array): bool { - $accountId = array_key_exists('id', $array) ? $array['id'] : null; - $accountName = array_key_exists('name', $array) ? $array['name'] : null; + $accountId = $array['id'] ?? null; + $accountName = $array['name'] ?? null; // if both are NULL, the destination is valid because the reconciliation // is expected to be "negative", i.e. the money flows towards the // destination to the asset account which is the source. @@ -47,19 +48,19 @@ trait ReconciliationValidation } // after that, search for it expecting an asset account or a liability. - app('log')->debug('Now in validateReconciliationDestination', $array); + Log::debug('Now in validateReconciliationDestination', $array); // source can be any of the following types. $validTypes = array_keys($this->combinations[$this->transactionType]); $search = $this->findExistingAccount($validTypes, $array); if (null === $search) { $this->sourceError = (string) trans('validation.reconciliation_source_bad_data', ['id' => $accountId, 'name' => $accountName]); - app('log')->warning('Not a valid source. Cant find it.', $validTypes); + Log::warning('Not a valid source. Cant find it.', $validTypes); return false; } $this->setSource($search); - app('log')->debug('Valid source account!'); + Log::debug('Valid source account!'); return true; } @@ -69,32 +70,32 @@ trait ReconciliationValidation */ protected function validateReconciliationSource(array $array): bool { - $accountId = array_key_exists('id', $array) ? $array['id'] : null; - $accountName = array_key_exists('name', $array) ? $array['name'] : null; + $accountId = $array['id'] ?? null; + $accountName = $array['name'] ?? null; // if both are NULL, the source is valid because the reconciliation // is expected to be "positive", i.e. the money flows from the // source to the asset account that is the destination. if (null === $accountId && null === $accountName) { - app('log')->debug('The source is valid because ID and name are NULL.'); + Log::debug('The source is valid because ID and name are NULL.'); $this->setSource(new Account()); return true; } // after that, search for it expecting an asset account or a liability. - app('log')->debug('Now in validateReconciliationSource', $array); + Log::debug('Now in validateReconciliationSource', $array); // source can be any of the following types. $validTypes = array_keys($this->combinations[$this->transactionType]); $search = $this->findExistingAccount($validTypes, $array); if (null === $search) { $this->sourceError = (string) trans('validation.reconciliation_source_bad_data', ['id' => $accountId, 'name' => $accountName]); - app('log')->warning('Not a valid source. Cant find it.', $validTypes); + Log::warning('Not a valid source. Cant find it.', $validTypes); return false; } $this->setSource($search); - app('log')->debug('Valid source account!'); + Log::debug('Valid source account!'); return true; } diff --git a/app/Validation/Account/TransferValidation.php b/app/Validation/Account/TransferValidation.php index ff01b7eab6..6efcff3fe6 100644 --- a/app/Validation/Account/TransferValidation.php +++ b/app/Validation/Account/TransferValidation.php @@ -24,6 +24,7 @@ declare(strict_types=1); namespace FireflyIII\Validation\Account; +use Illuminate\Support\Facades\Log; use FireflyIII\Models\Account; /** @@ -33,17 +34,17 @@ trait TransferValidation { protected function validateTransferDestination(array $array): bool { - $accountId = array_key_exists('id', $array) ? $array['id'] : null; - $accountName = array_key_exists('name', $array) ? $array['name'] : null; - $accountIban = array_key_exists('iban', $array) ? $array['iban'] : null; - app('log')->debug('Now in validateTransferDestination', $array); + $accountId = $array['id'] ?? null; + $accountName = $array['name'] ?? null; + $accountIban = $array['iban'] ?? null; + Log::debug('Now in validateTransferDestination', $array); // source can be any of the following types. $validTypes = $this->combinations[$this->transactionType][$this->source->accountType->type] ?? []; if (null === $accountId && null === $accountName && null === $accountIban && false === $this->canCreateTypes($validTypes)) { // if both values are NULL we return false, // because the destination of a transfer can't be created. $this->destError = (string) trans('validation.transfer_dest_need_data'); - app('log')->error('Both values are NULL, cant create transfer destination.'); + Log::error('Both values are NULL, cant create transfer destination.'); return false; } @@ -74,11 +75,11 @@ trait TransferValidation protected function validateTransferSource(array $array): bool { - $accountId = array_key_exists('id', $array) ? $array['id'] : null; - $accountName = array_key_exists('name', $array) ? $array['name'] : null; - $accountIban = array_key_exists('iban', $array) ? $array['iban'] : null; - $accountNumber = array_key_exists('number', $array) ? $array['number'] : null; - app('log')->debug('Now in validateTransferSource', $array); + $accountId = $array['id'] ?? null; + $accountName = $array['name'] ?? null; + $accountIban = $array['iban'] ?? null; + $accountNumber = $array['number'] ?? null; + Log::debug('Now in validateTransferSource', $array); // source can be any of the following types. $validTypes = array_keys($this->combinations[$this->transactionType]); if (null === $accountId && null === $accountName @@ -87,7 +88,7 @@ trait TransferValidation // if both values are NULL we return false, // because the source of a withdrawal can't be created. $this->sourceError = (string) trans('validation.transfer_source_need_data'); - app('log')->warning('Not a valid source, need more data.'); + Log::warning('Not a valid source, need more data.'); return false; } @@ -96,12 +97,12 @@ trait TransferValidation $search = $this->findExistingAccount($validTypes, $array); if (null === $search) { $this->sourceError = (string) trans('validation.transfer_source_bad_data', ['id' => $accountId, 'name' => $accountName]); - app('log')->warning('Not a valid source, cant find it.', $validTypes); + Log::warning('Not a valid source, cant find it.', $validTypes); return false; } $this->setSource($search); - app('log')->debug('Valid source!'); + Log::debug('Valid source!'); return true; } diff --git a/app/Validation/Account/WithdrawalValidation.php b/app/Validation/Account/WithdrawalValidation.php index ac2a06d825..3abd29b17b 100644 --- a/app/Validation/Account/WithdrawalValidation.php +++ b/app/Validation/Account/WithdrawalValidation.php @@ -35,9 +35,9 @@ trait WithdrawalValidation { protected function validateGenericSource(array $array): bool { - $accountId = array_key_exists('id', $array) ? $array['id'] : null; - $accountName = array_key_exists('name', $array) ? $array['name'] : null; - $accountIban = array_key_exists('iban', $array) ? $array['iban'] : null; + $accountId = $array['id'] ?? null; + $accountName = $array['name'] ?? null; + $accountIban = $array['iban'] ?? null; Log::debug('Now in validateGenericSource', $array); // source can be any of the following types. $validTypes = [AccountTypeEnum::ASSET->value, AccountTypeEnum::REVENUE->value, AccountTypeEnum::LOAN->value, AccountTypeEnum::DEBT->value, AccountTypeEnum::MORTGAGE->value]; @@ -70,10 +70,10 @@ trait WithdrawalValidation protected function validateWithdrawalDestination(array $array): bool { - $accountId = array_key_exists('id', $array) ? $array['id'] : null; - $accountName = array_key_exists('name', $array) ? $array['name'] : null; - $accountIban = array_key_exists('iban', $array) ? $array['iban'] : null; - $accountNumber = array_key_exists('number', $array) ? $array['number'] : null; + $accountId = $array['id'] ?? null; + $accountName = $array['name'] ?? null; + $accountIban = $array['iban'] ?? null; + $accountNumber = $array['number'] ?? null; Log::debug('Now in validateWithdrawalDestination()', $array); // source can be any of the following types. $validTypes = $this->combinations[$this->transactionType][$this->source->accountType->type] ?? []; @@ -121,10 +121,10 @@ trait WithdrawalValidation protected function validateWithdrawalSource(array $array): bool { - $accountId = array_key_exists('id', $array) ? $array['id'] : null; - $accountName = array_key_exists('name', $array) ? $array['name'] : null; - $accountIban = array_key_exists('iban', $array) ? $array['iban'] : null; - $accountNumber = array_key_exists('number', $array) ? $array['number'] : null; + $accountId = $array['id'] ?? null; + $accountName = $array['name'] ?? null; + $accountIban = $array['iban'] ?? null; + $accountNumber = $array['number'] ?? null; Log::debug('Now in validateWithdrawalSource', $array); // source can be any of the following types. diff --git a/app/Validation/AccountValidator.php b/app/Validation/AccountValidator.php index 0605b82bf0..385ead80da 100644 --- a/app/Validation/AccountValidator.php +++ b/app/Validation/AccountValidator.php @@ -50,11 +50,11 @@ class AccountValidator use TransferValidation; use WithdrawalValidation; - public bool $createMode; - public string $destError; - public ?Account $destination; - public ?Account $source; - public string $sourceError; + public bool $createMode = false; + public string $destError = 'No error yet.'; + public ?Account $destination = null; + public ?Account $source = null; + public string $sourceError = 'No error yet.'; private AccountRepositoryInterface $accountRepository; private array $combinations; private string $transactionType; @@ -64,12 +64,7 @@ class AccountValidator */ public function __construct() { - $this->createMode = false; - $this->destError = 'No error yet.'; - $this->sourceError = 'No error yet.'; $this->combinations = config('firefly.source_dests'); - $this->source = null; - $this->destination = null; $this->accountRepository = app(AccountRepositoryInterface::class); } @@ -235,11 +230,7 @@ class AccountValidator protected function canCreateType(string $accountType): bool { $canCreate = [AccountTypeEnum::EXPENSE->value, AccountTypeEnum::REVENUE->value, AccountTypeEnum::INITIAL_BALANCE->value, AccountTypeEnum::LIABILITY_CREDIT->value]; - if (in_array($accountType, $canCreate, true)) { - return true; - } - - return false; + return in_array($accountType, $canCreate, true); } /** @@ -253,10 +244,10 @@ class AccountValidator { Log::debug('Now in findExistingAccount', [$validTypes, $data]); Log::debug('The search will be reversed!'); - $accountId = array_key_exists('id', $data) ? $data['id'] : null; - $accountIban = array_key_exists('iban', $data) ? $data['iban'] : null; - $accountNumber = array_key_exists('number', $data) ? $data['number'] : null; - $accountName = array_key_exists('name', $data) ? $data['name'] : null; + $accountId = $data['id'] ?? null; + $accountIban = $data['iban'] ?? null; + $accountNumber = $data['number'] ?? null; + $accountName = $data['name'] ?? null; // find by ID if (null !== $accountId && $accountId > 0) { diff --git a/app/Validation/Api/Data/Bulk/ValidatesBulkTransactionQuery.php b/app/Validation/Api/Data/Bulk/ValidatesBulkTransactionQuery.php index 8f8cffba91..89ea275b39 100644 --- a/app/Validation/Api/Data/Bulk/ValidatesBulkTransactionQuery.php +++ b/app/Validation/Api/Data/Bulk/ValidatesBulkTransactionQuery.php @@ -24,8 +24,8 @@ declare(strict_types=1); namespace FireflyIII\Validation\Api\Data\Bulk; +use Illuminate\Contracts\Validation\Validator; use FireflyIII\Repositories\Account\AccountRepositoryInterface; -use Illuminate\Validation\Validator; use function Safe\json_decode; diff --git a/app/Validation/AutoBudget/ValidatesAutoBudgetRequest.php b/app/Validation/AutoBudget/ValidatesAutoBudgetRequest.php index 581e0da61c..28bad253e3 100644 --- a/app/Validation/AutoBudget/ValidatesAutoBudgetRequest.php +++ b/app/Validation/AutoBudget/ValidatesAutoBudgetRequest.php @@ -24,7 +24,7 @@ declare(strict_types=1); namespace FireflyIII\Validation\AutoBudget; -use Illuminate\Validation\Validator; +use Illuminate\Contracts\Validation\Validator; /** * Trait ValidatesAutoBudgetRequest @@ -40,10 +40,10 @@ trait ValidatesAutoBudgetRequest $type = $data['auto_budget_type'] ?? ''; /** @var null|float|int|string $amount */ - $amount = array_key_exists('auto_budget_amount', $data) ? $data['auto_budget_amount'] : null; - $period = array_key_exists('auto_budget_period', $data) ? $data['auto_budget_period'] : null; + $amount = $data['auto_budget_amount'] ?? null; + $period = $data['auto_budget_period'] ?? null; $currencyId = array_key_exists('auto_budget_currency_id', $data) ? (int) $data['auto_budget_currency_id'] : null; - $currencyCode = array_key_exists('auto_budget_currency_code', $data) ? $data['auto_budget_currency_code'] : null; + $currencyCode = $data['auto_budget_currency_code'] ?? null; if (is_numeric($type)) { $type = (int) $type; } diff --git a/app/Validation/CurrencyValidation.php b/app/Validation/CurrencyValidation.php index 52bad8ff61..3409114cb6 100644 --- a/app/Validation/CurrencyValidation.php +++ b/app/Validation/CurrencyValidation.php @@ -24,8 +24,8 @@ declare(strict_types=1); namespace FireflyIII\Validation; +use Illuminate\Contracts\Validation\Validator; use Illuminate\Support\Facades\Log; -use Illuminate\Validation\Validator; /** * Trait CurrencyValidation @@ -44,7 +44,7 @@ trait CurrencyValidation if ($validator->errors()->count() > 0) { return; } - app('log')->debug('Now in validateForeignCurrencyInformation()'); + Log::debug('Now in validateForeignCurrencyInformation()'); $transactions = $this->getTransactionsArray($validator); foreach ($transactions as $index => $transaction) { diff --git a/app/Validation/FireflyValidator.php b/app/Validation/FireflyValidator.php index e420a44f50..380d2e4e48 100644 --- a/app/Validation/FireflyValidator.php +++ b/app/Validation/FireflyValidator.php @@ -123,11 +123,7 @@ class FireflyValidator extends Validator } $regex = '/^[a-z]{6}[0-9a-z]{2}([0-9a-z]{3})?\z/i'; $result = preg_match($regex, $value); - if (0 === $result) { - return false; - } - - return true; + return 0 !== $result; } public function validateExistingMfaCode(mixed $attribute, mixed $value): bool @@ -459,7 +455,7 @@ class FireflyValidator extends Validator * * @SuppressWarnings("PHPMD.UnusedFormalParameter") */ - public function validateSecurePassword($attribute, $value): bool + public function validateSecurePassword($attribute, string $value): bool { $verify = false; if (array_key_exists('verify_password', $this->data)) { diff --git a/app/Validation/GroupValidation.php b/app/Validation/GroupValidation.php index 84c32cfc90..61acde4f07 100644 --- a/app/Validation/GroupValidation.php +++ b/app/Validation/GroupValidation.php @@ -24,10 +24,11 @@ declare(strict_types=1); namespace FireflyIII\Validation; +use Illuminate\Support\Facades\Log; +use Illuminate\Contracts\Validation\Validator; use FireflyIII\Exceptions\FireflyException; use FireflyIII\Models\Transaction; use FireflyIII\Models\TransactionGroup; -use Illuminate\Validation\Validator; /** * Trait GroupValidation. @@ -89,7 +90,7 @@ trait GroupValidation protected function preventUpdateReconciled(Validator $validator, TransactionGroup $transactionGroup): void { - app('log')->debug(sprintf('Now in %s', __METHOD__)); + Log::debug(sprintf('Now in %s', __METHOD__)); $count = Transaction::leftJoin('transaction_journals', 'transaction_journals.id', 'transactions.transaction_journal_id') ->leftJoin('transaction_groups', 'transaction_groups.id', 'transaction_journals.transaction_group_id') @@ -97,7 +98,7 @@ trait GroupValidation ->where('transactions.reconciled', 1)->where('transactions.amount', '<', 0)->count('transactions.id') ; if (0 === $count) { - app('log')->debug(sprintf('Transaction is not reconciled, done with %s', __METHOD__)); + Log::debug(sprintf('Transaction is not reconciled, done with %s', __METHOD__)); return; } @@ -123,7 +124,7 @@ trait GroupValidation } } - app('log')->debug(sprintf('Done with %s', __METHOD__)); + Log::debug(sprintf('Done with %s', __METHOD__)); } /** @@ -135,7 +136,7 @@ trait GroupValidation if ($validator->errors()->count() > 0) { return; } - app('log')->debug('Now in GroupValidation::validateDescriptions()'); + Log::debug('Now in GroupValidation::validateDescriptions()'); $transactions = $this->getTransactionsArray($validator); $validDescriptions = 0; foreach ($transactions as $transaction) { @@ -158,7 +159,7 @@ trait GroupValidation if ($validator->errors()->count() > 0) { return; } - app('log')->debug('Now in validateGroupDescription()'); + Log::debug('Now in validateGroupDescription()'); $data = $validator->getData(); $transactions = $this->getTransactionsArray($validator); @@ -175,12 +176,12 @@ trait GroupValidation */ protected function validateJournalIds(Validator $validator, TransactionGroup $transactionGroup): void { - app('log')->debug(sprintf('Now in GroupValidation::validateJournalIds(%d)', $transactionGroup->id)); + Log::debug(sprintf('Now in GroupValidation::validateJournalIds(%d)', $transactionGroup->id)); $transactions = $this->getTransactionsArray($validator); if (count($transactions) < 2) { // no need for validation. - app('log')->debug(sprintf('%d transaction(s) in submission, can skip this check.', count($transactions))); + Log::debug(sprintf('%d transaction(s) in submission, can skip this check.', count($transactions))); return; } @@ -204,17 +205,17 @@ trait GroupValidation if (array_key_exists('transaction_journal_id', $transaction)) { $journalId = $transaction['transaction_journal_id']; } - app('log')->debug(sprintf('Now in validateJournalId(%d, %d)', $index, $journalId)); + Log::debug(sprintf('Now in validateJournalId(%d, %d)', $index, $journalId)); if (0 === $journalId || '' === $journalId || '0' === $journalId) { - app('log')->debug('Submitted 0, will accept to be used in a new transaction.'); + Log::debug('Submitted 0, will accept to be used in a new transaction.'); return; } $journalId = (int) $journalId; $count = $transactionGroup->transactionJournals()->where('transaction_journals.id', $journalId)->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('Invalid submission: Each split must have transaction_journal_id (either valid ID or 0).'); + Log::warning(sprintf('Transaction group #%d has %d journals with ID %d', $transactionGroup->id, $count, $journalId)); + 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')); } } diff --git a/app/Validation/RecurrenceValidation.php b/app/Validation/RecurrenceValidation.php index 52b829203e..a76bd8b19a 100644 --- a/app/Validation/RecurrenceValidation.php +++ b/app/Validation/RecurrenceValidation.php @@ -24,10 +24,11 @@ declare(strict_types=1); namespace FireflyIII\Validation; +use Illuminate\Support\Facades\Log; +use Illuminate\Contracts\Validation\Validator; use Carbon\Carbon; use FireflyIII\Models\Recurrence; use FireflyIII\Models\RecurrenceTransaction; -use Illuminate\Validation\Validator; use InvalidArgumentException; /** @@ -50,22 +51,22 @@ trait RecurrenceValidation // grab model from parameter and try to set the transaction type from it if ('invalid' === $transactionType) { - app('log')->debug('Type is invalid but we will search for it.'); + Log::debug('Type is invalid but we will search for it.'); /** @var null|Recurrence $recurrence */ $recurrence = $this->route()?->parameter('recurrence'); if (null !== $recurrence) { - app('log')->debug('There is a recurrence in the route.'); + Log::debug('There is a recurrence in the route.'); // ok so we have a recurrence should be able to extract type somehow. /** @var null|RecurrenceTransaction $first */ $first = $recurrence->recurrenceTransactions()->first(); if (null !== $first) { $transactionType = null !== $first->transactionType ? $first->transactionType->type : 'withdrawal'; - app('log')->debug(sprintf('Determined type to be %s.', $transactionType)); + Log::debug(sprintf('Determined type to be %s.', $transactionType)); } if (null === $first) { - app('log')->warning('Just going to assume type is a withdrawal.'); + Log::warning('Just going to assume type is a withdrawal.'); $transactionType = 'withdrawal'; } } @@ -76,7 +77,7 @@ trait RecurrenceValidation /** @var AccountValidator $accountValidator */ $accountValidator = app(AccountValidator::class); - app('log')->debug(sprintf('Going to loop %d transaction(s)', count($transactions))); + Log::debug(sprintf('Going to loop %d transaction(s)', count($transactions))); foreach ($transactions as $index => $transaction) { $transactionType = $transaction['type'] ?? $transactionType; $accountValidator->setTransactionType($transactionType); @@ -296,7 +297,7 @@ trait RecurrenceValidation try { Carbon::createFromFormat('Y-m-d', $moment); } catch (InvalidArgumentException $e) { // @phpstan-ignore-line - app('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')); } } @@ -306,12 +307,12 @@ trait RecurrenceValidation */ protected function validateTransactionId(Recurrence $recurrence, Validator $validator): void { - app('log')->debug('Now in validateTransactionId'); + Log::debug('Now in validateTransactionId'); $transactions = $this->getTransactionData(); $submittedTrCount = count($transactions); if (0 === $submittedTrCount) { - app('log')->warning('[b] User submitted no transactions.'); + Log::warning('[b] User submitted no transactions.'); $validator->errors()->add('transactions', (string) trans('validation.at_least_one_transaction')); return; @@ -320,31 +321,31 @@ trait RecurrenceValidation if (1 === $submittedTrCount && 1 === $originalTrCount) { $first = $transactions[0]; // can safely assume index 0. if (!array_key_exists('id', $first)) { - app('log')->debug('Single count and no ID, done.'); + Log::debug('Single count and no ID, done.'); return; // home safe! } $id = $first['id']; if ('' === (string) $id) { - app('log')->debug('Single count and empty ID, done.'); + Log::debug('Single count and empty ID, done.'); return; // home safe! } $integer = (int) $id; $secondCount = $recurrence->recurrenceTransactions()->where('recurrences_transactions.id', $integer)->count(); - app('log')->debug(sprintf('Result of ID count: %d', $secondCount)); + Log::debug(sprintf('Result of ID count: %d', $secondCount)); if (0 === $secondCount) { $validator->errors()->add('transactions.0.id', (string) trans('validation.id_does_not_match', ['id' => $integer])); } - app('log')->debug('Single ID validation done.'); + Log::debug('Single ID validation done.'); return; } - app('log')->debug('Multi ID validation.'); + Log::debug('Multi ID validation.'); $idsMandatory = false; if ($submittedTrCount < $originalTrCount) { - app('log')->debug(sprintf('User submits %d transaction, recurrence has %d transactions. All entries must have ID.', $submittedTrCount, $originalTrCount)); + Log::debug(sprintf('User submits %d transaction, recurrence has %d transactions. All entries must have ID.', $submittedTrCount, $originalTrCount)); $idsMandatory = true; } @@ -362,41 +363,41 @@ trait RecurrenceValidation $unmatchedIds = 0; foreach ($transactions as $index => $transaction) { - app('log')->debug(sprintf('Now at %d/%d', $index + 1, $submittedTrCount)); + Log::debug(sprintf('Now at %d/%d', $index + 1, $submittedTrCount)); if (!is_array($transaction)) { - app('log')->warning('Not an array. Give error.'); + Log::warning('Not an array. Give error.'); $validator->errors()->add(sprintf('transactions.%d.id', $index), (string) trans('validation.at_least_one_transaction')); return; } if (!array_key_exists('id', $transaction) && $idsMandatory) { - app('log')->warning('ID is mandatory but array has no ID.'); + Log::warning('ID is mandatory but array has no ID.'); $validator->errors()->add(sprintf('transactions.%d.id', $index), (string) trans('validation.need_id_to_match')); return; } if (array_key_exists('id', $transaction)) { // don't matter if $idsMandatory - app('log')->debug('Array has ID.'); + Log::debug('Array has ID.'); $idCount = $recurrence->recurrenceTransactions()->where('recurrences_transactions.id', (int) $transaction['id'])->count(); if (0 === $idCount) { - app('log')->debug('ID does not exist or no match. Count another unmatched ID.'); + Log::debug('ID does not exist or no match. Count another unmatched ID.'); ++$unmatchedIds; } } if (!array_key_exists('id', $transaction) && !$idsMandatory) { - app('log')->debug('Array has no ID but was not mandatory at this point.'); + Log::debug('Array has no ID but was not mandatory at this point.'); ++$unmatchedIds; } } // if too many don't match, but you haven't submitted more than already present: $maxUnmatched = max(1, $submittedTrCount - $originalTrCount); - app('log')->debug(sprintf('Submitted: %d. Original: %d. User can submit %d unmatched transactions.', $submittedTrCount, $originalTrCount, $maxUnmatched)); + Log::debug(sprintf('Submitted: %d. Original: %d. User can submit %d unmatched transactions.', $submittedTrCount, $originalTrCount, $maxUnmatched)); if ($unmatchedIds > $maxUnmatched) { - app('log')->warning(sprintf('Too many unmatched transactions (%d).', $unmatchedIds)); + Log::warning(sprintf('Too many unmatched transactions (%d).', $unmatchedIds)); $validator->errors()->add('transactions.0.id', (string) trans('validation.too_many_unmatched')); return; } - app('log')->debug('Done with ID validation.'); + Log::debug('Done with ID validation.'); } } diff --git a/app/Validation/TransactionValidation.php b/app/Validation/TransactionValidation.php index b44333bd90..be8270f264 100644 --- a/app/Validation/TransactionValidation.php +++ b/app/Validation/TransactionValidation.php @@ -24,6 +24,7 @@ declare(strict_types=1); namespace FireflyIII\Validation; +use Illuminate\Contracts\Validation\Validator; use FireflyIII\Enums\AccountTypeEnum; use FireflyIII\Enums\TransactionTypeEnum; use FireflyIII\Exceptions\FireflyException; @@ -36,7 +37,6 @@ use FireflyIII\Repositories\Account\AccountRepository; use FireflyIII\Repositories\Account\AccountRepositoryInterface; use FireflyIII\User; use Illuminate\Support\Facades\Log; -use Illuminate\Validation\Validator; /** * Trait TransactionValidation @@ -302,11 +302,7 @@ trait TransactionValidation private function isLiability(Account $account): bool { $type = $account->accountType->type; - if (in_array($type, config('firefly.valid_liabilities'), true)) { - return true; - } - - return false; + return in_array($type, config('firefly.valid_liabilities'), true); } private function isAsset(Account $account): bool @@ -327,11 +323,7 @@ trait TransactionValidation if ('' === $transaction['foreign_amount']) { return false; } - if (0 === bccomp('0', (string) $transaction['foreign_amount'])) { - return false; - } - - return true; + return 0 !== bccomp('0', (string) $transaction['foreign_amount']); } /** @@ -758,12 +750,8 @@ trait TransactionValidation // source ID's are equal, return void. return true; } - if ($this->arrayEqual($comparison['source_name'])) { - // source names are equal, return void. - return true; - } - - return false; + // source names are equal, return void. + return (bool) $this->arrayEqual($comparison['source_name']); } private function arrayEqual(array $array): bool @@ -777,12 +765,8 @@ trait TransactionValidation // destination ID's are equal, return void. return true; } - if ($this->arrayEqual($comparison['destination_name'])) { - // destination names are equal, return void. - return true; - } - - return false; + // destination names are equal, return void. + return (bool) $this->arrayEqual($comparison['destination_name']); } private function compareAccountDataTransfer(array $comparison): bool @@ -799,11 +783,7 @@ trait TransactionValidation // destination ID's are equal, return void. return true; } - if ($this->arrayEqual($comparison['destination_name'])) { - // destination names are equal, return void. - return true; - } - - return false; + // destination names are equal, return void. + return (bool) $this->arrayEqual($comparison['destination_name']); } } diff --git a/bootstrap/app.php b/bootstrap/app.php index f384f4ba78..63d02d4f5b 100644 --- a/bootstrap/app.php +++ b/bootstrap/app.php @@ -42,8 +42,6 @@ bcscale(12); if (!function_exists('envNonEmpty')) { /** - * @param string $key - * @param string|int|bool|null $default * * @return mixed|null */ @@ -59,12 +57,6 @@ if (!function_exists('envNonEmpty')) { } if (!function_exists('stringIsEqual')) { - /** - * @param string $left - * @param string $right - * - * @return bool - */ function stringIsEqual(string $left, string $right): bool { return $left === $right; diff --git a/config/app.php b/config/app.php index 7600ef8514..2dad30bc1e 100644 --- a/config/app.php +++ b/config/app.php @@ -156,7 +156,7 @@ return [ 'RuleForm' => RuleForm::class, ], - 'asset_url' => env('ASSET_URL', null), + 'asset_url' => env('ASSET_URL'), /* |-------------------------------------------------------------------------- diff --git a/config/auth.php b/config/auth.php index de43714e23..7159b7e590 100644 --- a/config/auth.php +++ b/config/auth.php @@ -41,7 +41,7 @@ return [ 'passwords' => 'users', ], 'guard_header' => envNonEmpty('AUTHENTICATION_GUARD_HEADER', 'REMOTE_USER'), - 'guard_email' => envNonEmpty('AUTHENTICATION_GUARD_EMAIL', null), + 'guard_email' => envNonEmpty('AUTHENTICATION_GUARD_EMAIL'), /* |-------------------------------------------------------------------------- diff --git a/config/database.php b/config/database.php index 77fe7499e7..cd557e2bc4 100644 --- a/config/database.php +++ b/config/database.php @@ -41,12 +41,12 @@ if (false !== $databaseUrl) { } // Get SSL parameters from .env file. -$mysql_ssl_ca_dir = envNonEmpty('MYSQL_SSL_CAPATH', null); -$mysql_ssl_ca_file = envNonEmpty('MYSQL_SSL_CA', null); -$mysql_ssl_cert = envNonEmpty('MYSQL_SSL_CERT', null); -$mysql_ssl_key = envNonEmpty('MYSQL_SSL_KEY', null); -$mysql_ssl_ciphers = envNonEmpty('MYSQL_SSL_CIPHER', null); -$mysql_ssl_verify = envNonEmpty('MYSQL_SSL_VERIFY_SERVER_CERT', null); +$mysql_ssl_ca_dir = envNonEmpty('MYSQL_SSL_CAPATH'); +$mysql_ssl_ca_file = envNonEmpty('MYSQL_SSL_CA'); +$mysql_ssl_cert = envNonEmpty('MYSQL_SSL_CERT'); +$mysql_ssl_key = envNonEmpty('MYSQL_SSL_KEY'); +$mysql_ssl_ciphers = envNonEmpty('MYSQL_SSL_CIPHER'); +$mysql_ssl_verify = envNonEmpty('MYSQL_SSL_VERIFY_SERVER_CERT'); $mySqlSSLOptions = []; $useSSL = envNonEmpty('MYSQL_USE_SSL', false); @@ -145,7 +145,7 @@ return [ 'host' => envNonEmpty('REDIS_HOST', '127.0.0.1'), 'port' => envNonEmpty('REDIS_PORT', 6379), 'username' => env('REDIS_USERNAME'), - 'password' => env('REDIS_PASSWORD', null), + 'password' => env('REDIS_PASSWORD'), 'database' => env('REDIS_DB', '0'), ], 'cache' => [ @@ -155,7 +155,7 @@ return [ 'host' => envNonEmpty('REDIS_HOST', '127.0.0.1'), 'port' => envNonEmpty('REDIS_PORT', 6379), 'username' => env('REDIS_USERNAME'), - 'password' => env('REDIS_PASSWORD', null), + 'password' => env('REDIS_PASSWORD'), 'database' => env('REDIS_CACHE_DB', '1'), ], ], diff --git a/config/debugbar.php b/config/debugbar.php index e96846011b..3e980f35a9 100644 --- a/config/debugbar.php +++ b/config/debugbar.php @@ -36,7 +36,7 @@ return [ | */ - 'enabled' => env('DEBUGBAR_ENABLED', null), + 'enabled' => env('DEBUGBAR_ENABLED'), 'except' => [ 'telescope*', 'horizon*', diff --git a/config/session.php b/config/session.php index 8881108f8b..6f099565cb 100644 --- a/config/session.php +++ b/config/session.php @@ -34,8 +34,8 @@ return [ 'lottery' => [2, 100], 'cookie' => env('COOKIE_NAME', 'firefly_iii_session'), 'path' => env('COOKIE_PATH', '/'), - 'domain' => env('COOKIE_DOMAIN', null), - 'secure' => env('COOKIE_SECURE', null), + 'domain' => env('COOKIE_DOMAIN'), + 'secure' => env('COOKIE_SECURE'), 'http_only' => true, 'same_site' => env('COOKIE_SAMESITE', 'lax'), ]; diff --git a/routes/channels.php b/routes/channels.php index 92bf6b22ef..e5e9a52dbc 100644 --- a/routes/channels.php +++ b/routes/channels.php @@ -37,5 +37,5 @@ use Illuminate\Support\Facades\Broadcast; Broadcast::channel( 'App.User.{id}', - static fn ($user, $id) => (int)$user->id === (int)$id + static fn ($user, $id): bool => (int)$user->id === (int)$id ); diff --git a/routes/web.php b/routes/web.php index 4f05a8622c..7d5b40234c 100644 --- a/routes/web.php +++ b/routes/web.php @@ -42,7 +42,7 @@ Route::group( Route::get('/authorize', ['uses' => 'AuthorizationController@authorize', 'as' => 'authorizations.authorize', 'middleware' => 'user-full-auth']); // the rest - $guard = config('passport.guard', null); + $guard = config('passport.guard'); Route::middleware(['web', null !== $guard ? 'auth:'.$guard : 'auth'])->group(function (): void { Route::post('/token/refresh', ['uses' => 'TransientTokenController@refresh', 'as' => 'token.refresh']); Route::post('/authorize', ['uses' => 'ApproveAuthorizationController@approve', 'as' => 'authorizations.approve']); diff --git a/tests/integration/Api/Chart/AccountControllerTest.php b/tests/integration/Api/Chart/AccountControllerTest.php index f0afcd93e9..fbb60429c0 100644 --- a/tests/integration/Api/Chart/AccountControllerTest.php +++ b/tests/integration/Api/Chart/AccountControllerTest.php @@ -25,6 +25,7 @@ declare(strict_types=1); namespace Tests\integration\Api\Chart; +use FireflyIII\User; use Override; use Illuminate\Foundation\Testing\RefreshDatabase; use Tests\integration\TestCase; @@ -37,14 +38,14 @@ use Tests\integration\TestCase; final class AccountControllerTest extends TestCase { use RefreshDatabase; - private $user; + private ?User $user = null; #[Override] protected function setUp(): void { parent::setUp(); - if (!isset($this->user)) { + if (!$this->user instanceof User) { $this->user = $this->createAuthenticatedUser(); } $this->actingAs($this->user); diff --git a/tests/integration/Api/Chart/BalanceControllerTest.php b/tests/integration/Api/Chart/BalanceControllerTest.php index 4ad490d9f6..bcfc308467 100644 --- a/tests/integration/Api/Chart/BalanceControllerTest.php +++ b/tests/integration/Api/Chart/BalanceControllerTest.php @@ -25,6 +25,7 @@ declare(strict_types=1); namespace Tests\integration\Api\Chart; +use FireflyIII\User; use Override; use Illuminate\Foundation\Testing\RefreshDatabase; use Tests\integration\TestCase; @@ -37,14 +38,14 @@ use Tests\integration\TestCase; final class BalanceControllerTest extends TestCase { use RefreshDatabase; - private $user; + private ?User $user = null; #[Override] protected function setUp(): void { parent::setUp(); - if (!isset($this->user)) { + if (!$this->user instanceof User) { $this->user = $this->createAuthenticatedUser(); } $this->actingAs($this->user); diff --git a/tests/integration/Api/Chart/BudgetControllerTest.php b/tests/integration/Api/Chart/BudgetControllerTest.php index d0f9c980af..f565dcda28 100644 --- a/tests/integration/Api/Chart/BudgetControllerTest.php +++ b/tests/integration/Api/Chart/BudgetControllerTest.php @@ -25,6 +25,7 @@ declare(strict_types=1); namespace Tests\integration\Api\Chart; +use FireflyIII\User; use Override; use Illuminate\Foundation\Testing\RefreshDatabase; use Tests\integration\TestCase; @@ -37,14 +38,14 @@ use Tests\integration\TestCase; final class BudgetControllerTest extends TestCase { use RefreshDatabase; - private $user; + private ?User $user = null; #[Override] protected function setUp(): void { parent::setUp(); - if (!isset($this->user)) { + if (!$this->user instanceof User) { $this->user = $this->createAuthenticatedUser(); } $this->actingAs($this->user); diff --git a/tests/integration/Api/Chart/CategoryControllerTest.php b/tests/integration/Api/Chart/CategoryControllerTest.php index 045dc61691..ed77df6a98 100644 --- a/tests/integration/Api/Chart/CategoryControllerTest.php +++ b/tests/integration/Api/Chart/CategoryControllerTest.php @@ -25,6 +25,7 @@ declare(strict_types=1); namespace Tests\integration\Api\Chart; +use FireflyIII\User; use Override; use Illuminate\Foundation\Testing\RefreshDatabase; use Tests\integration\TestCase; @@ -37,14 +38,14 @@ use Tests\integration\TestCase; final class CategoryControllerTest extends TestCase { use RefreshDatabase; - private $user; + private ?User $user = null; #[Override] protected function setUp(): void { parent::setUp(); - if (!isset($this->user)) { + if (!$this->user instanceof User) { $this->user = $this->createAuthenticatedUser(); } $this->actingAs($this->user); diff --git a/tests/integration/Api/Models/Account/ListControllerTest.php b/tests/integration/Api/Models/Account/ListControllerTest.php index d22823fefb..2d508a7796 100644 --- a/tests/integration/Api/Models/Account/ListControllerTest.php +++ b/tests/integration/Api/Models/Account/ListControllerTest.php @@ -25,6 +25,7 @@ declare(strict_types=1); namespace Tests\integration\Api\Models\Account; +use Override; use FireflyIII\Enums\AccountTypeEnum; use FireflyIII\Factory\AttachmentFactory; use FireflyIII\Models\Account; @@ -43,6 +44,7 @@ final class ListControllerTest extends TestCase private User $user; private Account $account; + #[Override] protected function setUp(): void { parent::setUp(); diff --git a/tests/integration/Api/Models/Account/ShowControllerTest.php b/tests/integration/Api/Models/Account/ShowControllerTest.php index e952e63b16..c80943f01d 100644 --- a/tests/integration/Api/Models/Account/ShowControllerTest.php +++ b/tests/integration/Api/Models/Account/ShowControllerTest.php @@ -25,6 +25,7 @@ declare(strict_types=1); namespace Tests\integration\Api\Models\Account; +use Override; use FireflyIII\Enums\AccountTypeEnum; use FireflyIII\Models\Account; use FireflyIII\User; @@ -41,6 +42,7 @@ final class ShowControllerTest extends TestCase use RefreshDatabase; private User $user; + #[Override] protected function setUp(): void { parent::setUp(); diff --git a/tests/integration/Api/System/AboutControllerTest.php b/tests/integration/Api/System/AboutControllerTest.php index 6ffb04b044..71db85f1ea 100644 --- a/tests/integration/Api/System/AboutControllerTest.php +++ b/tests/integration/Api/System/AboutControllerTest.php @@ -24,6 +24,7 @@ declare(strict_types=1); namespace Tests\integration\Api\System; +use FireflyIII\User; use Illuminate\Foundation\Testing\RefreshDatabase; use Illuminate\Testing\Fluent\AssertableJson; use Tests\integration\TestCase; @@ -39,14 +40,14 @@ use Override; final class AboutControllerTest extends TestCase { use RefreshDatabase; - private $user; + private ?User $user = null; #[Override] protected function setUp(): void { parent::setUp(); - if (!isset($this->user)) { + if (!$this->user instanceof User) { $this->user = $this->createAuthenticatedUser(); } $this->actingAs($this->user); @@ -74,7 +75,7 @@ final class AboutControllerTest extends TestCase $response->assertOk(); $response->assertJson( - fn (AssertableJson $json) => $json + fn (AssertableJson $json): AssertableJson => $json ->where('data.attributes.email', $this->user->email) ->where('data.attributes.role', $this->user->role) );